Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?php |
| 2 | |
| 3 | namespace LdapRecord\Models\Concerns; |
| 4 | |
| 5 | use Closure; |
| 6 | use InvalidArgumentException; |
| 7 | use LdapRecord\Models\Scope; |
| 8 | |
| 9 | trait 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 | * |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 17 | * @return mixed |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 18 | * |
| 19 | * @throws InvalidArgumentException |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 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 | } |