LinkAccessConstraintValidator.php in Drupal 9
File
core/modules/link/src/Plugin/Validation/Constraint/LinkAccessConstraintValidator.php
View source
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class LinkAccessConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
protected $current_user;
public function __construct(AccountProxyInterface $current_user) {
$this->current_user = $current_user;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('current_user'));
}
public function validate($value, Constraint $constraint) {
if (isset($value)) {
try {
$url = $value
->getUrl();
} catch (\InvalidArgumentException $e) {
return;
}
$allowed = $this->current_user
->hasPermission('link to any page') || $url
->access();
if (!$allowed) {
$this->context
->addViolation($constraint->message, [
'@uri' => $value->uri,
]);
}
}
}
}