Skip to content
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

NEW Wire up symfony/validator #11123

Merged
Merged
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 composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"symfony/mailer": "^6.1",
"symfony/mime": "^6.1",
"symfony/translation": "^6.1",
"symfony/validator": "^6.1",
"symfony/yaml": "^6.1",
"ext-ctype": "*",
"ext-dom": "*",
Expand Down
46 changes: 46 additions & 0 deletions src/Core/Validation/ConstraintValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace SilverStripe\Core\Validation;

use InvalidArgumentException;
use SilverStripe\ORM\ValidationResult;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\Validation;

/**
* Helper class to abstract away wiring up symfony/validator and getting ValidationResult from validating
* symfony validator constraints.
*/
class ConstraintValidator
{
/**
* Validate a value by a constraint
*
* @param Constraint|Constraint[] $constraints a constraint or array of constraints to validate against
* @param string $fieldName The field name the value relates to, if relevant
*/
public static function validate(mixed $value, Constraint|array $constraints, string $fieldName = ''): ValidationResult
{
if (is_array($constraints) && empty($constraints)) {
throw new InvalidArgumentException('$constraints must not be an empty array');
}

// Perform validation
$validator = Validation::createValidator();
$violations = $validator->validate($value, $constraints);

// Convert value to ValidationResult
$result = ValidationResult::create();
/** @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
if ($fieldName) {
$result->addFieldError($fieldName, $violation->getMessage());
} else {
$result->addError($violation->getMessage());
}
}

return $result;
}
}
Loading
Loading