Skip to content

Commit

Permalink
Merge pull request #78 from adam-vessey/feature/edtf-constraints
Browse files Browse the repository at this point in the history
EDTF validation constraint
  • Loading branch information
rosiel authored Mar 2, 2022
2 parents 6854095 + 569e38d commit 415d8de
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Plugin/Field/FieldType/ExtendedDateTimeFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* description = @Translation("Extended Date Time Format field"),
* default_formatter = "edtf_default",
* default_widget = "edtf_default",
* constraints = {
* "EDTF" = {},
* },
* )
*/
class ExtendedDateTimeFormat extends StringItem {
Expand Down
25 changes: 25 additions & 0 deletions src/Plugin/Validation/Constraint/EDTF.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Drupal\controlled_access_terms\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
* EDTF constraint plugin.
*
* @Constraint(
* id = "EDTF",
* label = @Translation("EDTF", context = "Validation"),
* type = "string",
* )
*/
class EDTF extends Constraint {

/**
* Invalid format message template.
*
* @var string
*/
public $invalid = '%value is not valid EDTF: %verbose';

}
38 changes: 38 additions & 0 deletions src/Plugin/Validation/Constraint/EDTFValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Drupal\controlled_access_terms\Plugin\Validation\Constraint;

use Drupal\controlled_access_terms\EDTFUtils;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
* EDTF validation handler.
*/
class EDTFValidator extends ConstraintValidator {

/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
if (!$constraint instanceof EDTF) {
throw new UnexpectedTypeException($constraint, EDTF::class);
}
if (NULL === $value) {
return;
}

foreach ($value->getValue() as $val) {
foreach (EDTFUtils::validate($val, TRUE, TRUE, FALSE) as $error) {
$this->context->buildViolation($constraint->invalid)
->setParameter('%value', $val)
->setParameter('%verbose', $error)
->addViolation();
}
}

}

}

0 comments on commit 415d8de

Please sign in to comment.