Skip to content

Commit caee0bd

Browse files
authored
class-name string argument for global scopes (#49802)
1 parent 740543c commit caee0bd

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,11 @@ public static function addGlobalScope($scope, $implementation = null)
2626
return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope;
2727
} elseif ($scope instanceof Scope) {
2828
return static::$globalScopes[static::class][get_class($scope)] = $scope;
29+
} elseif (is_string($scope) && class_exists($scope) && is_subclass_of($scope, Scope::class)) {
30+
return static::$globalScopes[static::class][$scope] = new $scope;
2931
}
3032

31-
throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.');
33+
throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope or be a class name of a class extending '.Scope::class);
3234
}
3335

3436
/**

tests/Database/DatabaseEloquentGlobalScopesTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ public function testGlobalScopeCanBeRemoved()
4343
$this->assertEquals([], $query->getBindings());
4444
}
4545

46+
public function testClassNameGlobalScopeIsApplied()
47+
{
48+
$model = new EloquentClassNameGlobalScopesTestModel;
49+
$query = $model->newQuery();
50+
$this->assertSame('select * from "table" where "active" = ?', $query->toSql());
51+
$this->assertEquals([1], $query->getBindings());
52+
}
53+
4654
public function testClosureGlobalScopeIsApplied()
4755
{
4856
$model = new EloquentClosureGlobalScopesTestModel;
@@ -190,6 +198,18 @@ public static function boot()
190198
}
191199
}
192200

201+
class EloquentClassNameGlobalScopesTestModel extends Model
202+
{
203+
protected $table = 'table';
204+
205+
public static function boot()
206+
{
207+
static::addGlobalScope(ActiveScope::class);
208+
209+
parent::boot();
210+
}
211+
}
212+
193213
class ActiveScope implements Scope
194214
{
195215
public function apply(Builder $builder, Model $model)

0 commit comments

Comments
 (0)