DateRecurRulePartConstraintValidator.php in Recurring Dates Field 3.x
File
src/Plugin/Validation/Constraint/DateRecurRulePartConstraintValidator.php
View source
<?php
declare (strict_types=1);
namespace Drupal\date_recur\Plugin\Validation\Constraint;
use Drupal\date_recur\DateRecurHelper;
use Drupal\date_recur\DateRecurRruleMap;
use Drupal\date_recur\Exception\DateRecurRulePartIncompatible;
use Drupal\date_recur\Plugin\Field\FieldType\DateRecurItem;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class DateRecurRulePartConstraintValidator extends ConstraintValidator {
protected $frequencyLabels = NULL;
protected $partLabels = NULL;
public function validate($value, Constraint $constraint) : void {
assert($value instanceof DateRecurItem);
assert($constraint instanceof DateRecurRulePartConstraint);
$fieldList = $value
->getParent();
$grid = $fieldList
->getPartGrid();
if (empty($value->rrule)) {
return;
}
try {
$helper = DateRecurHelper::create($value->rrule, new \DateTime());
} catch (\Exception $e) {
return;
}
foreach ($helper
->getRules() as $rule) {
$frequency = $rule
->getFrequency();
if (!$grid
->isFrequencyAllowed($frequency)) {
$frequencyLabels = $this
->getFrequencyLabels();
$frequencyLabel = $frequencyLabels[$frequency] ?? $frequency;
$this->context
->addViolation($constraint->disallowedFrequency, [
'%frequency' => $frequencyLabel,
]);
continue;
}
$parts = $rule
->getParts();
unset($parts['FREQ']);
foreach (array_keys($parts) as $part) {
try {
if (!$grid
->isPartAllowed($frequency, $part)) {
$partLabels = $this
->getPartLabels();
$partLabel = $partLabels[$part] ?? $part;
$this->context
->addViolation($constraint->disallowedPart, [
'%part' => $partLabel,
]);
}
} catch (DateRecurRulePartIncompatible $e) {
$frequencyLabels = $this
->getFrequencyLabels();
$frequencyLabel = $frequencyLabels[$frequency] ?? $frequency;
$partLabels = $this
->getPartLabels();
$partLabel = $partLabels[$part] ?? $part;
$this->context
->addViolation($constraint->incompatiblePart, [
'%frequency' => $frequencyLabel,
'%part' => $partLabel,
]);
}
}
}
}
protected function getFrequencyLabels() : array {
if (!isset($this->frequencyLabels)) {
$this->frequencyLabels = DateRecurRruleMap::frequencyLabels();
}
return $this->frequencyLabels;
}
protected function getPartLabels() : array {
if (!isset($this->partLabels)) {
$this->partLabels = DateRecurRruleMap::partLabels();
}
return $this->partLabels;
}
}