Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"require-dev": {
"nikic/php-parser": "^5.9",
"phpunit/phpunit": "^13.4",
"symfony/console": "^6.4",
"symfony/framework-bundle": "^6.4",
"illuminate/container": "^11.51",
"symplify/easy-coding-standard": "^13.3",
Expand Down
46 changes: 46 additions & 0 deletions src/Rules/Symfony/CommandMustHaveAsCommandAttributeRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,18 @@ final class CommandMustHaveAsCommandAttributeRule implements Rule
*/
private const LARAVEL_COMMAND_CLASS = 'Illuminate\Console\Command';

/**
* @var string
*/
private const SYMFONY_CONSOLE_PACKAGE = 'symfony/console';

/**
* @var string
*/
public const ERROR_MESSAGE = 'Class "%s" extends Command but is missing the #[AsCommand] attribute';

private ?bool $hasSymfonyConsolePackage = null;

public function __construct(ReflectionProvider $reflectionProvider)
{
$this->reflectionProvider = $reflectionProvider;
Expand All @@ -59,6 +66,11 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

// only projects that depend on symfony/console in composer.json
if (! $this->hasSymfonyConsolePackage()) {
return [];
}

// Laravel commands use $signature instead of the #[AsCommand] attribute
if ($this->reflectionProvider->hasClass(self::LARAVEL_COMMAND_CLASS)) {
return [];
Expand Down Expand Up @@ -97,4 +109,38 @@ public function processNode(Node $node, Scope $scope): array

return [$identifierRuleError];
}

private function hasSymfonyConsolePackage(): bool
{
if ($this->hasSymfonyConsolePackage !== null) {
return $this->hasSymfonyConsolePackage;
}

$composerJsonFilePath = getcwd() . '/composer.json';
if (! is_file($composerJsonFilePath)) {
return $this->hasSymfonyConsolePackage = false;
}

$composerJsonContents = file_get_contents($composerJsonFilePath);
if ($composerJsonContents === false) {
return $this->hasSymfonyConsolePackage = false;
}

$composerJson = json_decode($composerJsonContents, true);
if (! is_array($composerJson)) {
return $this->hasSymfonyConsolePackage = false;
}

$requirePackages = $composerJson['require'] ?? [];
if (is_array($requirePackages) && isset($requirePackages[self::SYMFONY_CONSOLE_PACKAGE])) {
return $this->hasSymfonyConsolePackage = true;
}

$requireDevPackages = $composerJson['require-dev'] ?? [];
if (is_array($requireDevPackages) && isset($requireDevPackages[self::SYMFONY_CONSOLE_PACKAGE])) {
return $this->hasSymfonyConsolePackage = true;
}

return $this->hasSymfonyConsolePackage = false;
}
}
Loading