Skip to content

[Validator] Add simple helper ConstraintViolationList::hasViolation #33229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ CHANGELOG
* removed `ValidatorBuilderInterface`
* passing a null message when instantiating a `ConstraintViolation` is not allowed
* changed the default value of `Length::$allowEmptyString` to `false` and made it optional
* add the `hasViolation` method to `ConstraintViolationListInterface`

4.4.0
-----
Expand Down
8 changes: 8 additions & 0 deletions src/Symfony/Component/Validator/ConstraintViolationList.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,12 @@ public function findByCodes($codes)

return new static($violations);
}

/**
* {@inheritdoc}
*/
public function hasViolation(): bool
{
return 0 !== \count($this->violations);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,11 @@ public function set(int $offset, ConstraintViolationInterface $violation);
* @param int $offset The offset to remove
*/
public function remove(int $offset);

/**
* Return Whether the list contains or not violation.
*
* @return bool Whether the list contains or not violation
*/
public function hasViolation(): bool;
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,14 @@ public function testFindByCodes($code, $violationsCount)
$this->assertCount($violationsCount, $specificErrors);
}

/**
* @dataProvider hasViolationProvider
*/
public function testHasViolation(bool $expected, ConstraintViolationList $violationList)
{
$this->assertEquals($expected, $violationList->hasViolation());
}

public function findByCodesProvider()
{
return [
Expand All @@ -155,6 +163,16 @@ public function findByCodesProvider()
];
}

public function hasViolationProvider()
{
$violation = $this->getViolation('Error', null, null, 'code1');

return [
[true, new ConstraintViolationList([$violation])],
[false, new ConstraintViolationList],
];
}

protected function getViolation($message, $root = null, $propertyPath = null, $code = null)
{
return new ConstraintViolation($message, $message, [], $root, $propertyPath, null, null, $code);
Expand Down