1

我正在使用验证器组件来验证数组。

我的验证是有条件的,所以我创建了组。

但我无法让它正常工作。验证器在检查约束时会忽略这些组。

这是我的(单元)测试:

public function testValidator()
{
   $book = array(
        'title' => 'My Book',
        'author' => array(
            'first_name' => 'Fabien',
            'last_name'  => 'Potencier',
        ),
    );

    $constraint = new Assert\Collection(array(
        'groups' => array('MyGroup'),
        'fields' => array(
            'title' => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
            'author' => new Assert\Collection(array(
                'groups' => array('MyGroup'),
                'fields' => array(
                    'first_name' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 10))),
                    'last_name'  => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
                )
            )),
        )
    ));
    // $this->v is the validator service
    $errors = $this->v->validateValue($book, $constraint, null, array('MyGroup'));

    $this->assertEquals(1, $errors->count(), $errors);
}

结果是:

PHPUnit 3.7.14 by Sebastian Bergmann.

Configuration read from phpunit.xml

.F

Time: 0 seconds, Memory: 3.00Mb

There was 1 failure:


1) WebFactory\ValidationNormalizer\Tests\ValidationNormalizerTest::testValidator
[title]:
    This value is too short. It should have 10 characters or more.
[author][first_name]:
    This value is too short. It should have 10 characters or more.
[author][last_name]:
    This value is too short. It should have 10 characters or more.

Failed asserting that 3 matches expected 1.

src/WebFactory/ValidationNormalizer/Tests/ValidationNormalizerTest.php:64

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

我只想验证 MyGroup 约束。

错误在哪里?

4

1 回答 1

0

您已将整个收藏添加到您的组“MyGroup”。

  'author' => new Assert\Collection(array(
      'groups' => array('MyGroup'),

因此它验证了整个数组

'author' => array(
     'first_name' => 'Fabien',
      'last_name'  => 'Potencier',
),

...如果您将验证组指定为“MyGroup”。这种行为是正确的。

如果您只想在使用验证组“MyGroup”时验证“title”和“lastname”,请使用:

$constraint = new Assert\Collection(array(
    'fields' => array(
        'title' => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
        'author' => new Assert\Collection(array(
            'fields' => array(
                'first_name' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 10))),
                'last_name'  => new Assert\Length(array('min' => 10, 'groups' => 'MyGroup')),
            )
        )),
    )
));
于 2013-05-24T07:23:51.693 回答