feature #20509 [Serializer] Allow to specify a single value in @Groups (dunglas)

This PR was squashed before being merged into the 3.3-dev branch (closes #20509).

Discussion
----------

[Serializer] Allow to specify a single value in @Groups

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | https://github.com/symfony/symfony/pull/19374#issuecomment-256688002
| License       | MIT
| Doc PR        | todo

Tiny DX improvement:

Before:

```php
use Symfony\Component\Serializer\Annotation\Groups;

class Product
{
    /**
     * @Groups({"admins"})
     */
    public $itemsSold;
}
```

Now allowed:

```php
use Symfony\Component\Serializer\Annotation\Groups;

class Product
{
    /**
     * @Groups("admins")
     */
    public $itemsSold;
}
```

Commits
-------

926aa48 [Serializer] Allow to specify a single value in @Groups
This commit is contained in:
Fabien Potencier 2016-12-02 12:58:15 +01:00
commit fe454e42e1
2 changed files with 13 additions and 10 deletions

View File

@ -24,7 +24,7 @@ use Symfony\Component\Serializer\Exception\InvalidArgumentException;
class Groups
{
/**
* @var array
* @var string[]
*/
private $groups;
@ -39,23 +39,20 @@ class Groups
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" cannot be empty.', get_class($this)));
}
if (!is_array($data['value'])) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be an array of strings.', get_class($this)));
}
foreach ($data['value'] as $group) {
$value = (array) $data['value'];
foreach ($value as $group) {
if (!is_string($group)) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be an array of strings.', get_class($this)));
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be a string or an array of strings.', get_class($this)));
}
}
$this->groups = $data['value'];
$this->groups = $value;
}
/**
* Gets groups.
*
* @return array
* @return string[]
*/
public function getGroups()
{

View File

@ -31,7 +31,7 @@ class GroupsTest extends \PHPUnit_Framework_TestCase
*/
public function testNotAnArrayGroupsParameter()
{
new Groups(array('value' => 'coopTilleuls'));
new Groups(array('value' => 12));
}
/**
@ -49,4 +49,10 @@ class GroupsTest extends \PHPUnit_Framework_TestCase
$groups = new Groups(array('value' => $validData));
$this->assertEquals($validData, $groups->getGroups());
}
public function testSingleGroup()
{
$groups = new Groups(array('value' => 'a'));
$this->assertEquals(array('a'), $groups->getGroups());
}
}