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

EDTF validation constraint #78

Merged
merged 4 commits into from
Mar 2, 2022
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
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();
}
}

}

}