Pull merge.
[yaffs-website] / web / core / modules / workspaces / src / Plugin / Validation / Constraint / EntityReferenceSupportedNewEntitiesConstraintValidator.php
1 <?php
2
3 namespace Drupal\workspaces\Plugin\Validation\Constraint;
4
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\Core\Entity\EntityTypeManagerInterface;
7 use Drupal\workspaces\WorkspaceManagerInterface;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
9 use Symfony\Component\Validator\Constraint;
10 use Symfony\Component\Validator\ConstraintValidator;
11
12 /**
13  * Checks if new entities created for entity reference fields are supported.
14  */
15 class EntityReferenceSupportedNewEntitiesConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
16
17   /**
18    * The workspace manager.
19    *
20    * @var \Drupal\workspaces\WorkspaceManagerInterface
21    */
22   protected $workspaceManager;
23
24   /**
25    * The entity type manager.
26    *
27    * @var \Drupal\Core\Entity\EntityTypeManagerInterface
28    */
29   protected $entityTypeManager;
30
31   /**
32    * Creates a new EntityReferenceSupportedNewEntitiesConstraintValidator instance.
33    */
34   public function __construct(WorkspaceManagerInterface $workspaceManager, EntityTypeManagerInterface $entityTypeManager) {
35     $this->workspaceManager = $workspaceManager;
36     $this->entityTypeManager = $entityTypeManager;
37   }
38
39   /**
40    * {@inheritdoc}
41    */
42   public static function create(ContainerInterface $container) {
43     return new static(
44       $container->get('workspaces.manager'),
45       $container->get('entity_type.manager')
46     );
47   }
48
49   /**
50    * {@inheritdoc}
51    */
52   public function validate($value, Constraint $constraint) {
53     if ($this->workspaceManager->getActiveWorkspace()->isDefaultWorkspace()) {
54       return;
55     }
56
57     $target_entity_type_id = $value->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
58     $target_entity_type = $this->entityTypeManager->getDefinition($target_entity_type_id);
59
60     if ($value->hasNewEntity() && !$this->workspaceManager->isEntityTypeSupported($target_entity_type)) {
61       $this->context->addViolation($constraint->message, ['%collection_label' => $target_entity_type->getCollectionLabel()]);
62     }
63   }
64
65 }