| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace Illuminate\Database\Eloquent\Concerns;
|
|
|
4 |
|
|
|
5 |
use Closure;
|
|
|
6 |
use Illuminate\Database\Eloquent\Scope;
|
|
|
7 |
use Illuminate\Support\Arr;
|
|
|
8 |
use InvalidArgumentException;
|
|
|
9 |
|
|
|
10 |
trait HasGlobalScopes
|
|
|
11 |
{
|
|
|
12 |
/**
|
|
|
13 |
* Register a new global scope on the model.
|
|
|
14 |
*
|
|
|
15 |
* @param \Illuminate\Database\Eloquent\Scope|\Closure|string $scope
|
|
|
16 |
* @param \Illuminate\Database\Eloquent\Scope|\Closure|null $implementation
|
|
|
17 |
* @return mixed
|
|
|
18 |
*
|
|
|
19 |
* @throws \InvalidArgumentException
|
|
|
20 |
*/
|
|
|
21 |
public static function addGlobalScope($scope, $implementation = null)
|
|
|
22 |
{
|
|
|
23 |
if (is_string($scope) && ($implementation instanceof Closure || $implementation instanceof Scope)) {
|
|
|
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 \Illuminate\Database\Eloquent\Scope|string $scope
|
|
|
38 |
* @return bool
|
|
|
39 |
*/
|
|
|
40 |
public static function hasGlobalScope($scope)
|
|
|
41 |
{
|
|
|
42 |
return ! is_null(static::getGlobalScope($scope));
|
|
|
43 |
}
|
|
|
44 |
|
|
|
45 |
/**
|
|
|
46 |
* Get a global scope registered with the model.
|
|
|
47 |
*
|
|
|
48 |
* @param \Illuminate\Database\Eloquent\Scope|string $scope
|
|
|
49 |
* @return \Illuminate\Database\Eloquent\Scope|\Closure|null
|
|
|
50 |
*/
|
|
|
51 |
public static function getGlobalScope($scope)
|
|
|
52 |
{
|
|
|
53 |
if (is_string($scope)) {
|
|
|
54 |
return Arr::get(static::$globalScopes, static::class.'.'.$scope);
|
|
|
55 |
}
|
|
|
56 |
|
|
|
57 |
return Arr::get(
|
|
|
58 |
static::$globalScopes, static::class.'.'.get_class($scope)
|
|
|
59 |
);
|
|
|
60 |
}
|
|
|
61 |
|
|
|
62 |
/**
|
|
|
63 |
* Get the global scopes for this class instance.
|
|
|
64 |
*
|
|
|
65 |
* @return array
|
|
|
66 |
*/
|
|
|
67 |
public function getGlobalScopes()
|
|
|
68 |
{
|
|
|
69 |
return Arr::get(static::$globalScopes, static::class, []);
|
|
|
70 |
}
|
|
|
71 |
}
|