-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add validator that leverages symfony/validation constraints.
- Loading branch information
1 parent
a5cf78c
commit 068479e
Showing
2 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
<?php | ||
|
||
namespace Signify\ComposableValidators\Validators; | ||
|
||
use Signify\ComposableValidators\Traits\ValidatesMultipleFieldsWithConfig; | ||
use SilverStripe\Forms\FormField; | ||
use SilverStripe\Core\Validation\ConstraintValidator; | ||
|
||
/** | ||
* A validator which Validates values based on symfony validation constraints. | ||
* | ||
* Configuration values for this validator are a constraint or array of constraints to validate each field value against. | ||
* For example: | ||
* $validator->addField('IpAddress', new Symfony\Component\Validator\Constraints\Ip()); | ||
* | ||
* See https://symfony.com/doc/current/reference/constraints.html for a list of constraints. | ||
* | ||
* This validator is best used within an AjaxCompositeValidator in conjunction with | ||
* a SimpleFieldsValidator. | ||
*/ | ||
class ConstraintsValidator extends BaseValidator | ||
{ | ||
use ValidatesMultipleFieldsWithConfig; | ||
|
||
/** | ||
* Validates that the required blocks exist in the configured positions. | ||
* | ||
* @param array $data | ||
* @return bool | ||
*/ | ||
public function php($data) | ||
{ | ||
foreach ($this->getFields() as $fieldName => $constraint) { | ||
$value = isset($data[$fieldName]) ? $data[$fieldName] : null; | ||
$this->result->combineAnd(ConstraintValidator::validate($value, $constraint, $fieldName)); | ||
} | ||
|
||
return $this->result->isValid(); | ||
} | ||
|
||
protected function getValidationHintForField(FormField $field): ?array | ||
{ | ||
// @TODO decide if there's a nice way to implement this | ||
return null; | ||
} | ||
} |