ReferenceAccessConstraintValidator.php in Drupal 9
File
core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/ReferenceAccessConstraintValidator.php
View source
<?php
namespace Drupal\Core\Entity\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ReferenceAccessConstraintValidator extends ConstraintValidator {
public function validate($value, Constraint $constraint) {
if (!isset($value)) {
return;
}
$id = $value->target_id;
if (empty($id)) {
return;
}
$referenced_entity = $value->entity;
if ($referenced_entity) {
$entity = $value
->getEntity();
$check_permission = TRUE;
if (!$entity
->isNew()) {
$existing_entity = \Drupal::entityTypeManager()
->getStorage($entity
->getEntityTypeId())
->loadUnchanged($entity
->id());
$referenced_entities = $existing_entity->{$value
->getFieldDefinition()
->getName()}
->referencedEntities();
foreach ($referenced_entities as $ref) {
if (isset($referenced_entities[$ref
->id()])) {
$check_permission = FALSE;
break;
}
}
}
if ($check_permission && !$referenced_entity
->access('view')) {
$type = $value
->getFieldDefinition()
->getSetting('target_type');
$this->context
->addViolation($constraint->message, [
'%type' => $type,
'%id' => $id,
]);
}
}
}
}