blob: c14abad28c1fd89e0dce4c3168aa14bb4397a2c5 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3namespace LdapRecord\Models\Concerns;
4
5use Closure;
6use InvalidArgumentException;
7use LdapRecord\Models\Scope;
8
9trait HasGlobalScopes
10{
11 /**
12 * Register a new global scope on the model.
13 *
14 * @param Scope|Closure|string $scope
15 * @param Closure|null $implementation
16 *
17 * @throws InvalidArgumentException
18 *
19 * @return mixed
20 */
21 public static function addGlobalScope($scope, Closure $implementation = null)
22 {
23 if (is_string($scope) && ! is_null($implementation)) {
24 return static::$globalScopes[static::class][$scope] = $implementation;
25 } elseif ($scope instanceof Closure) {
26 return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope;
27 } elseif ($scope instanceof Scope) {
28 return static::$globalScopes[static::class][get_class($scope)] = $scope;
29 }
30
31 throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.');
32 }
33
34 /**
35 * Determine if a model has a global scope.
36 *
37 * @param Scope|string $scope
38 *
39 * @return bool
40 */
41 public static function hasGlobalScope($scope)
42 {
43 return ! is_null(static::getGlobalScope($scope));
44 }
45
46 /**
47 * Get a global scope registered with the model.
48 *
49 * @param Scope|string $scope
50 *
51 * @return Scope|Closure|null
52 */
53 public static function getGlobalScope($scope)
54 {
55 if (array_key_exists(static::class, static::$globalScopes)) {
56 $scopeName = is_string($scope) ? $scope : get_class($scope);
57
58 return array_key_exists($scopeName, static::$globalScopes[static::class])
59 ? static::$globalScopes[static::class][$scopeName]
60 : null;
61 }
62 }
63
64 /**
65 * Get the global scopes for this class instance.
66 *
67 * @return array
68 */
69 public function getGlobalScopes()
70 {
71 return array_key_exists(static::class, static::$globalScopes)
72 ? static::$globalScopes[static::class]
73 : [];
74 }
75}