|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpStanMigrationRules\Rules\Laravel; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\StaticCall; |
| 9 | +use PhpParser\Node\Identifier; |
| 10 | +use PhpParser\Node\Name; |
| 11 | +use PHPStan\Analyser\Scope; |
| 12 | +use PHPStan\Rules\Rule; |
| 13 | +use PHPStan\Rules\RuleErrorBuilder; |
| 14 | + |
| 15 | +/** |
| 16 | + * @implements Rule<StaticCall> |
| 17 | + */ |
| 18 | +final class ForbidMultipleTableCreationsRule implements Rule |
| 19 | +{ |
| 20 | + private const string RULE_IDENTIFIER = 'laravel.schema.multipleTableCreationsForbidden'; |
| 21 | + |
| 22 | + /** |
| 23 | + * @var array<string, int> |
| 24 | + */ |
| 25 | + private array $createCallsPerFile = []; |
| 26 | + |
| 27 | + public function getNodeType(): string |
| 28 | + { |
| 29 | + return StaticCall::class; |
| 30 | + } |
| 31 | + |
| 32 | + public function processNode(Node $node, Scope $scope): array |
| 33 | + { |
| 34 | + $classReflection = $scope->getClassReflection(); |
| 35 | + if ($classReflection === null) { |
| 36 | + return []; |
| 37 | + } |
| 38 | + |
| 39 | + if (!$classReflection->isSubclassOf(\Illuminate\Database\Migrations\Migration::class)) { |
| 40 | + return []; |
| 41 | + } |
| 42 | + |
| 43 | + if (!$this->isSchemaCreateCall($node, $scope)) { |
| 44 | + return []; |
| 45 | + } |
| 46 | + |
| 47 | + $file = $scope->getFile(); |
| 48 | + $this->createCallsPerFile[$file] = ($this->createCallsPerFile[$file] ?? 0) + 1; |
| 49 | + |
| 50 | + if ($this->createCallsPerFile[$file] > 1) { |
| 51 | + return [ |
| 52 | + RuleErrorBuilder::message( |
| 53 | + 'Creating multiple tables in a single Laravel migration is forbidden. ' |
| 54 | + . 'Each migration should create exactly one table.' |
| 55 | + ) |
| 56 | + ->identifier(self::RULE_IDENTIFIER) |
| 57 | + ->build(), |
| 58 | + ]; |
| 59 | + } |
| 60 | + |
| 61 | + return []; |
| 62 | + } |
| 63 | + |
| 64 | + private function isSchemaCreateCall(StaticCall $node, Scope $scope): bool |
| 65 | + { |
| 66 | + if (!$node->name instanceof Identifier || $node->name->toString() !== 'create') { |
| 67 | + return false; |
| 68 | + } |
| 69 | + |
| 70 | + if (!$node->class instanceof Name) { |
| 71 | + return false; |
| 72 | + } |
| 73 | + |
| 74 | + $resolved = $scope->resolveName($node->class); |
| 75 | + |
| 76 | + return $resolved === \Illuminate\Support\Facades\Schema::class |
| 77 | + || $resolved === 'Illuminate\\Database\\Schema\\Schema'; // Rare case |
| 78 | + } |
| 79 | +} |
0 commit comments