Pull merge.
[yaffs-website] / web / core / lib / Drupal / Core / Validation / Plugin / Validation / Constraint / AllowedValuesConstraintValidator.php
1 <?php
2
3 namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
4
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\Core\Session\AccountInterface;
7 use Drupal\Core\TypedData\OptionsProviderInterface;
8 use Drupal\Core\TypedData\ComplexDataInterface;
9 use Drupal\Core\TypedData\Validation\TypedDataAwareValidatorTrait;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
11 use Symfony\Component\Validator\Constraint;
12 use Symfony\Component\Validator\Constraints\ChoiceValidator;
13
14 /**
15  * Validates the AllowedValues constraint.
16  */
17 class AllowedValuesConstraintValidator extends ChoiceValidator implements ContainerInjectionInterface {
18
19   use TypedDataAwareValidatorTrait;
20
21   /**
22    * The current user.
23    *
24    * @var \Drupal\Core\Session\AccountInterface
25    */
26   protected $currentUser;
27
28   /**
29    * {@inheritdoc}
30    */
31   public static function create(ContainerInterface $container) {
32     return new static($container->get('current_user'));
33   }
34
35   /**
36    * Constructs a new AllowedValuesConstraintValidator.
37    *
38    * @param \Drupal\Core\Session\AccountInterface $current_user
39    *   The current user.
40    */
41   public function __construct(AccountInterface $current_user) {
42     $this->currentUser = $current_user;
43   }
44
45   /**
46    * {@inheritdoc}
47    */
48   public function validate($value, Constraint $constraint) {
49     $typed_data = $this->getTypedData();
50     if ($typed_data instanceof OptionsProviderInterface) {
51       $allowed_values = $typed_data->getSettableValues($this->currentUser);
52       $constraint->choices = $allowed_values;
53
54       // If the data is complex, we have to validate its main property.
55       if ($typed_data instanceof ComplexDataInterface) {
56         $name = $typed_data->getDataDefinition()->getMainPropertyName();
57         if (!isset($name)) {
58           throw new \LogicException('Cannot validate allowed values for complex data without a main property.');
59         }
60         $value = $typed_data->get($name)->getValue();
61       }
62     }
63
64     // The parent implementation ignores values that are not set, but makes
65     // sure some choices are available firstly. However, we want to support
66     // empty choices for undefined values; for instance, if a term reference
67     // field points to an empty vocabulary.
68     if (!isset($value)) {
69       return;
70     }
71
72     parent::validate($value, $constraint);
73   }
74
75 }