Skip to content

Commit 24af544

Browse files
author
Billy
authored
feat: support for statically added closure global scopes (#140)
1 parent 0eb823d commit 24af544

File tree

3 files changed

+37
-7
lines changed

3 files changed

+37
-7
lines changed

src/PowerJoinClause.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,11 @@ public function withGlobalScopes(): self
9191
}
9292

9393
foreach ($this->model->getGlobalScopes() as $scope) {
94+
if ($scope instanceof Closure) {
95+
$scope->call($this, $this);
96+
continue;
97+
}
98+
9499
(new $scope())->apply($this, $this->model);
95100
}
96101

tests/JoinWithGlobalScopeTest.php

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,10 @@
22

33
namespace Kirschbaum\PowerJoins\Tests;
44

5-
use Kirschbaum\PowerJoins\PowerJoins;
6-
use Kirschbaum\PowerJoins\Tests\Models\Post;
7-
use Kirschbaum\PowerJoins\Tests\Models\User;
8-
use Kirschbaum\PowerJoins\Tests\Models\Image;
9-
use Kirschbaum\PowerJoins\Tests\Models\Comment;
10-
use Kirschbaum\PowerJoins\Tests\Models\Category;
115
use Illuminate\Database\Eloquent\Relations\HasMany;
12-
use Kirschbaum\PowerJoins\Tests\Models\UserProfile;
6+
use Kirschbaum\PowerJoins\Tests\Models\PostWithClosureGlobalScope;
137
use Kirschbaum\PowerJoins\Tests\Models\PostWithGlobalScope;
8+
use Kirschbaum\PowerJoins\Tests\Models\User;
149

1510
class JoinWithGlobalScopeTest extends TestCase
1611
{
@@ -29,4 +24,19 @@ public function posts(): HasMany
2924
$query = $user->query()->joinRelationship('posts', fn ($join) => $join->withGlobalScopes())->toSql();
3025
$this->assertStringContainsString('"posts"."published" = ?', $query);
3126
}
27+
28+
public function test_join_with_closure_global_scope_applied()
29+
{
30+
$user = new class extends User {
31+
public function posts(): HasMany
32+
{
33+
return $this->hasMany(PostWithClosureGlobalScope::class, 'user_id');
34+
}
35+
};
36+
37+
$this->assertCount(0, $user->query()->joinRelationship('posts', fn ($join) => $join->withGlobalScopes())->get());
38+
39+
$query = $user->query()->joinRelationship('posts', fn ($join) => $join->withGlobalScopes())->toSql();
40+
$this->assertStringContainsString('"posts"."published" = ?', $query);
41+
}
3242
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
namespace Kirschbaum\PowerJoins\Tests\Models;
4+
5+
class PostWithClosureGlobalScope extends Post
6+
{
7+
protected static function boot()
8+
{
9+
parent::boot();
10+
11+
static::addGlobalScope('published', function ($builder) {
12+
$builder->where('posts.published', true);
13+
});
14+
}
15+
}

0 commit comments

Comments
 (0)