617ddd43c7ab00eb398ec9f269d2ed096d8e7e51
[yaffs-website] / Plugin / EntityBrowser / WidgetValidation / Cardinality.php
1 <?php
2
3 namespace Drupal\entity_browser\Plugin\EntityBrowser\WidgetValidation;
4
5 use Drupal\entity_browser\Element\EntityBrowserElement;
6 use Drupal\entity_browser\WidgetValidationBase;
7 use Symfony\Component\Validator\ConstraintViolation;
8 use Symfony\Component\Validator\ConstraintViolationList;
9
10 /**
11  * Validates that the widget returns the appropriate number of elements.
12  *
13  * @EntityBrowserWidgetValidation(
14  *   id = "cardinality",
15  *   label = @Translation("Cardinality validator")
16  * )
17  */
18 class Cardinality extends WidgetValidationBase {
19
20   /**
21    * {@inheritdoc}
22    */
23   public function validate(array $entities, $options = []) {
24     $violations = new ConstraintViolationList();
25
26     // As this validation happens at a level above the individual entities,
27     // we implement logic without using Constraint Plugins.
28     $count = count($entities);
29     $max = $options['cardinality'];
30     if ($max !== EntityBrowserElement::CARDINALITY_UNLIMITED && $count > $max) {
31       $message = $this->formatPlural($max, 'You can not select more than 1 entity.', 'You can not select more than @count entities.');
32       $violation = new ConstraintViolation($message, $message, [], $count, '', $count);
33       $violations->add($violation);
34     }
35
36     return $violations;
37   }
38
39 }