Created
March 31, 2025 11:03
-
-
Save GeniJaho/cb2e2747bf84203f97105cf80b71c813 to your computer and use it in GitHub Desktop.
DoNotEagerLoadByDefault PHPStan rule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
use PhpParser\Node; | |
use PhpParser\Node\Stmt\Property; | |
use PHPStan\Analyser\Scope; | |
use PHPStan\Rules\Rule; | |
use PHPStan\Rules\RuleErrorBuilder; | |
class DoNotEagerLoadByDefault implements Rule | |
{ | |
public function getNodeType(): string | |
{ | |
return Property::class; | |
} | |
/** | |
* @param Property $node | |
*/ | |
public function processNode(Node $node, Scope $scope): array | |
{ | |
if ($node->props === []) { | |
return []; | |
} | |
if ($node->props[0]->name->toString() !== 'with') { | |
return []; | |
} | |
$classReflection = $scope->getClassReflection(); | |
if ($classReflection === null) { | |
return []; | |
} | |
if (!$classReflection->isSubclassOf(Model::class)) { | |
return []; | |
} | |
return [ | |
RuleErrorBuilder::message('Eager loading should not be done by default.') | |
->identifier('custom.noEagerLoadingByDefault') | |
->build(), | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment