3 namespace Drupal\entity_module_test\EventSubscriber;
5 use Drupal\entity\QueryAccess\ConditionGroup;
6 use Drupal\entity\QueryAccess\QueryAccessEvent;
7 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9 class QueryAccessSubscriber implements EventSubscriberInterface {
14 public static function getSubscribedEvents() {
16 'entity.query_access.entity_test_enhanced' => 'onQueryAccess',
21 * Modifies the access conditions based on the current user.
23 * This is just a convenient example for testing. A real subscriber would
24 * ignore the account and extend the conditions to cover additional factors,
25 * such as a custom entity field.
27 * @param \Drupal\entity\QueryAccess\QueryAccessEvent $event
30 public function onQueryAccess(QueryAccessEvent $event) {
31 $conditions = $event->getConditions();
32 $email = $event->getAccount()->getEmail();
34 if ($email == 'user1@example.com') {
35 // This user should not have access to any entities.
36 $conditions->alwaysFalse();
38 elseif ($email == 'user2@example.com') {
39 // This user should have access to entities with the IDs 1, 2, and 3.
40 // The query access handler might have already set ->alwaysFalse()
41 // due to the user not having any other access, so we make sure
42 // to undo it with $conditions->alwaysFalse(TRUE).
43 $conditions->alwaysFalse(FALSE);
44 $conditions->addCondition('id', ['1', '2', '3']);
46 elseif ($email == 'user3@example.com') {
47 // This user should only have access to entities assigned to "marketing",
48 // or unassigned entities.
49 $conditions->alwaysFalse(FALSE);
50 $conditions->addCondition((new ConditionGroup('OR'))
51 ->addCondition('assigned', NULL, 'IS NULL')
52 // Confirm that explicitly specifying the property name works.
53 ->addCondition('assigned.value', 'marketing')