Skip to content

Commit

Permalink
fix: model scopes should not be considered dynamic where (#158)
Browse files Browse the repository at this point in the history
  • Loading branch information
canvural authored Jul 16, 2023
1 parent 909bdcc commit 3d9ba82
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Rules/NoDynamicWhereRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
use PHPStan\Type\TypeCombinator;

use function sprintf;
use function strpos;
use function str_starts_with;
use function ucfirst;

/** @implements Rule<MethodCall> */
final class NoDynamicWhereRule implements Rule
Expand Down Expand Up @@ -62,7 +63,7 @@ public function processNode(Node $node, Scope $scope): array

$methodName = $node->name->toString();

if ($methodName === 'where' || strpos($methodName, 'where') !== 0) {
if ($methodName === 'where' || ! str_starts_with($methodName, 'where')) {
return [];
}

Expand Down Expand Up @@ -101,6 +102,7 @@ public function processNode(Node $node, Scope $scope): array

if (
$this->provider->getClass(Model::class)->hasNativeMethod($methodName) ||
$model && $this->provider->getClass($model)->hasNativeMethod('scope' . ucfirst($methodName)) ||
$this->provider->getClass($eloquentBuilder)->hasNativeMethod($methodName) ||
$this->provider->getClass(QueryBuilder::class)->hasNativeMethod($methodName) ||
$this->provider->getClass(BelongsToMany::class)->hasNativeMethod($methodName)
Expand Down Expand Up @@ -153,7 +155,7 @@ private function findModel(ClassReflection $calledOnReflection): string|null
) {
$modelType = $calledOnReflection->getActiveTemplateTypeMap()->getType('TModelClass');

if ($modelType === null || ! $modelType instanceof ObjectType) {
if (! $modelType instanceof ObjectType) {
return null;
}

Expand Down
17 changes: 17 additions & 0 deletions tests/Rules/data/dynamic-where.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,20 @@ public function fooWherePivotNotNull(): BelongsToMany
return $this->belongsToMany(Foo::class)->wherePivotNotNull('pivot_field');
}
}

class ModelWithScope extends Model
{
public function testScope()
{
return $this->whereFooBar();
}

/**
* @param Builder<Foo> $query
* @phpstan-return Builder<Foo>
*/
public function scopeWhereFooBar($query): Builder
{
return $query->where('foo', 'bar');
}
}

0 comments on commit 3d9ba82

Please sign in to comment.