diff --git a/src/Plugin/Validation/Constraint/ItemsCountConstraintValidator.php b/src/Plugin/Validation/Constraint/ItemsCountConstraintValidator.php index c78f3ec..26d7625 100644 --- a/src/Plugin/Validation/Constraint/ItemsCountConstraintValidator.php +++ b/src/Plugin/Validation/Constraint/ItemsCountConstraintValidator.php @@ -18,7 +18,7 @@ class ItemsCountConstraintValidator extends ConstraintValidator { return; } - if ($value->get($constraint->sourceFieldName)->isEmpty()) { + if ($value->get($constraint->sourceFieldName)->isEmpty() && $value->getFieldDefinition($constraint->sourceFieldName)->isRequired()) { $this->context->addViolation($constraint->message); } } diff --git a/tests/src/Unit/ConstraintsTest.php b/tests/src/Unit/ConstraintsTest.php index fb1edd6..6edadda 100644 --- a/tests/src/Unit/ConstraintsTest.php +++ b/tests/src/Unit/ConstraintsTest.php @@ -67,6 +67,13 @@ class TestMediaEntityConstraints { */ protected $sourceFields = []; + /** + * The source field definitions. + * + * @var array + */ + protected $sourceFieldDefinitions = []; + /** * TestMediaEntityConstraints constructor. * @@ -77,6 +84,7 @@ class TestMediaEntityConstraints { */ public function __construct($name, $value = NULL) { $this->sourceFields[$name] = new TestField($value); + $this->sourceFieldDefinitions[$name] = new TestFieldDefinition(); } /** @@ -86,6 +94,13 @@ class TestMediaEntityConstraints { return $this->sourceFields[$name]; } + /** + * Mocks getFieldDefinition() on \Drupal\Core\Entity\FieldableEntityInterface. + */ + public function getFieldDefinition($name) { + return $this->sourceFieldDefinitions[$name]; + } + } /** @@ -118,3 +133,18 @@ class TestField { } } + +/** + * Mock class for field definitions. + * All test fields will be required since we're testing validation constraints. + */ +class TestFieldDefinition { + + /** + * Mocks isRequired() on \Drupal\Core\Field\FieldDefinitionInterface. + */ + public function isRequired() { + return true; + } + +}