1<?php
2
3namespace Drupal\Tests\user\Kernel;
4
5use Drupal\field\Entity\FieldConfig;
6use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
7use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
8use Drupal\user\Entity\Role;
9
10/**
11 * Tests the user reference field functionality.
12 *
13 * @group user
14 */
15class UserEntityReferenceTest extends EntityKernelTestBase {
16
17  use EntityReferenceTestTrait;
18
19  /**
20   * A randomly-generated role for testing purposes.
21   *
22   * @var \Drupal\user\RoleInterface
23   */
24  protected $role1;
25
26  /**
27   * A randomly-generated role for testing purposes.
28   *
29   * @var \Drupal\user\RoleInterface
30   */
31  protected $role2;
32
33  /**
34   * {@inheritdoc}
35   */
36  protected function setUp() {
37    parent::setUp();
38
39    $this->role1 = Role::create([
40      'id' => strtolower($this->randomMachineName(8)),
41      'label' => $this->randomMachineName(8),
42    ]);
43    $this->role1->save();
44
45    $this->role2 = Role::create([
46      'id' => strtolower($this->randomMachineName(8)),
47      'label' => $this->randomMachineName(8),
48    ]);
49    $this->role2->save();
50
51    $this->createEntityReferenceField('user', 'user', 'user_reference', 'User reference', 'user');
52  }
53
54  /**
55   * Tests user selection by roles.
56   */
57  public function testUserSelectionByRole() {
58    $field_definition = FieldConfig::loadByName('user', 'user', 'user_reference');
59    $handler_settings = $field_definition->getSetting('handler_settings');
60    $handler_settings['filter']['role'] = [
61      $this->role1->id() => $this->role1->id(),
62      $this->role2->id() => 0,
63    ];
64    $handler_settings['filter']['type'] = 'role';
65    $field_definition->setSetting('handler_settings', $handler_settings);
66    $field_definition->save();
67
68    $user1 = $this->createUser(['name' => 'aabb']);
69    $user1->addRole($this->role1->id());
70    $user1->save();
71
72    $user2 = $this->createUser(['name' => 'aabbb']);
73    $user2->addRole($this->role1->id());
74    $user2->save();
75
76    $user3 = $this->createUser(['name' => 'aabbbb']);
77    $user3->addRole($this->role2->id());
78    $user3->save();
79
80    /** @var \Drupal\Core\Entity\EntityAutocompleteMatcherInterface $autocomplete */
81    $autocomplete = \Drupal::service('entity.autocomplete_matcher');
82
83    $matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabb');
84    $this->assertCount(2, $matches);
85    $users = [];
86    foreach ($matches as $match) {
87      $users[] = $match['label'];
88    }
89    $this->assertContains($user1->label(), $users);
90    $this->assertContains($user2->label(), $users);
91    $this->assertNotContains($user3->label(), $users);
92
93    $matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabbbb');
94    $this->assertCount(0, $matches);
95  }
96
97}
98