Bristol SU Support Package
PermissionTester.php
Go to the documentation of this file.
1 <?php
2 
4 
15 use Exception;
16 
21 {
22 
28  private $testers = [];
29 
37  public function evaluate(string $ability): bool
38  {
39  /*
40  * We always need to pass a user in. This is always possible, since you will always be logged into a database user.
41  * By default, we take from authentication. If this is null, we take from the database user
42  */
43  $user = app(Authentication::class)->getUser();
44  if ($user === null && ($dbUser = app(UserAuthentication::class)->getUser()) !== null) {
45  $user = app(UserRepository::class)->getById($dbUser->control_id);
46  }
47 
48  $result = $this->evaluateFor($ability, $user, app(Authentication::class)->getGroup(), app(Authentication::class)->getRole());
49  return ($result ?? false);
50  }
51 
62  public function evaluateFor(string $ability, ?User $user = null, ?Group $group = null, ?Role $role = null): bool
63  {
64  $tester = $this->getChain();
65  return ($tester->handle($this->getPermission($ability), $user, $group, $role) ?? false);
66  }
67 
77  public function getChain()
78  {
79  if (count($this->testers) === 0) {
80  throw new Exception('No testers registered');
81  }
83  for ($i = 0; $i < (count($testers) - 1); $i++) {
84  $testers[$i]->setNext($testers[$i + 1]);
85  }
86  return $testers[0];
87  }
88 
95  private function getPermission(string $ability): Permission
96  {
97  return app(PermissionRepositoryContract::class)->get($ability);
98  }
99 
106  public function register(Tester $tester, $position = null)
107  {
108  if ($position === null) {
109  $this->testers[] = $tester;
110  } else {
111  array_splice($this->testers, $position, 0, [$tester]);
112  }
113 
114  }
115 }
evaluateFor(string $ability, ?User $user=null, ?Group $group=null, ?Role $role=null)