HasGlobalScopes.php 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Concerns;
  3. use Closure;
  4. use Illuminate\Support\Arr;
  5. use InvalidArgumentException;
  6. use Illuminate\Database\Eloquent\Scope;
  7. trait HasGlobalScopes
  8. {
  9. /**
  10. * Register a new global scope on the model.
  11. *
  12. * @param \Illuminate\Database\Eloquent\Scope|\Closure|string $scope
  13. * @param \Closure|null $implementation
  14. * @return mixed
  15. *
  16. * @throws \InvalidArgumentException
  17. */
  18. public static function addGlobalScope($scope, Closure $implementation = null)
  19. {
  20. if (is_string($scope) && ! is_null($implementation)) {
  21. return static::$globalScopes[static::class][$scope] = $implementation;
  22. } elseif ($scope instanceof Closure) {
  23. return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope;
  24. } elseif ($scope instanceof Scope) {
  25. return static::$globalScopes[static::class][get_class($scope)] = $scope;
  26. }
  27. throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.');
  28. }
  29. /**
  30. * Determine if a model has a global scope.
  31. *
  32. * @param \Illuminate\Database\Eloquent\Scope|string $scope
  33. * @return bool
  34. */
  35. public static function hasGlobalScope($scope)
  36. {
  37. return ! is_null(static::getGlobalScope($scope));
  38. }
  39. /**
  40. * Get a global scope registered with the model.
  41. *
  42. * @param \Illuminate\Database\Eloquent\Scope|string $scope
  43. * @return \Illuminate\Database\Eloquent\Scope|\Closure|null
  44. */
  45. public static function getGlobalScope($scope)
  46. {
  47. if (is_string($scope)) {
  48. return Arr::get(static::$globalScopes, static::class.'.'.$scope);
  49. }
  50. return Arr::get(
  51. static::$globalScopes, static::class.'.'.get_class($scope)
  52. );
  53. }
  54. /**
  55. * Get the global scopes for this class instance.
  56. *
  57. * @return array
  58. */
  59. public function getGlobalScopes()
  60. {
  61. return Arr::get(static::$globalScopes, static::class, []);
  62. }
  63. }