Skip to content

Instantly share code, notes, and snippets.

@GeniJaho
Created March 31, 2025 11:03
Show Gist options
  • Save GeniJaho/cb2e2747bf84203f97105cf80b71c813 to your computer and use it in GitHub Desktop.
Save GeniJaho/cb2e2747bf84203f97105cf80b71c813 to your computer and use it in GitHub Desktop.
DoNotEagerLoadByDefault PHPStan rule
<?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