Skip to content

Commit

Permalink
feature #19764 [Config] Add ExprBuilder::ifEmpty() (ogizanagi)
Browse files Browse the repository at this point in the history
This PR was merged into the 3.2-dev branch.

Discussion
----------

[Config] Add ExprBuilder::ifEmpty()

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets |
| License       | MIT
| Doc PR        | symfony/symfony-docs#6922

Useful for instance when you don't expect to have a key set in the resolved config if its content is empty:

```php
$builder = new TreeBuilder();
$tree = $builder
    ->root('matcher')
        ->children()
            ->arrayNode('references_to_exclude')
                ->validate()
                    ->ifEmpty()
                    ->thenUnset()
                ->end()
                ->prototype('scalar')->end()
            ->end()
        ->end()
    ->end()
    ->buildTree()
;

$tree->finalize(['references_to_exclude' => ['foo', 'bar']]);
>>> ['references_to_exclude' => ['foo', 'bar']]

$tree->finalize(['references_to_exclude' => []]);
>>> []
```

Commits
-------

4e46f64 [Config] Add ExprBuilder::ifEmpty()
  • Loading branch information
fabpot committed Aug 31, 2016
2 parents 2cd6c63 + 4e46f64 commit 4fbf80d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Symfony/Component/Config/Definition/Builder/ExprBuilder.php
Expand Up @@ -97,6 +97,18 @@ public function ifNull()
return $this;
}

/**
* Tests if the value is empty.
*
* @return ExprBuilder
*/
public function ifEmpty()
{
$this->ifPart = function ($v) { return empty($v); };

return $this;
}

/**
* Tests if the value is an array.
*
Expand Down
Expand Up @@ -75,6 +75,21 @@ public function testIfNullExpression()
$this->assertFinalizedValueIs('value', $test);
}

public function testIfEmptyExpression()
{
$test = $this->getTestBuilder()
->ifEmpty()
->then($this->returnClosure('new_value'))
->end();
$this->assertFinalizedValueIs('new_value', $test, array('key' => array()));

$test = $this->getTestBuilder()
->ifEmpty()
->then($this->returnClosure('new_value'))
->end();
$this->assertFinalizedValueIs('value', $test);
}

public function testIfArrayExpression()
{
$test = $this->getTestBuilder()
Expand Down

0 comments on commit 4fbf80d

Please sign in to comment.