From 0cfb1ec3e64c32c2b4ebdec0e43030f2fe807096 Mon Sep 17 00:00:00 2001 From: Mark Scherer Date: Sun, 25 Oct 2026 14:47:52 +0100 Subject: [PATCH] Skip the Psr4 sniff instead of aborting when composer.json is missing The sniff already marked itself as failed before calling the factory and returned early on that state, but the factory's InvalidArgumentException was never caught, so running phpcs from a directory without composer.json killed the whole run with a fatal error. Only the missing/unreadable case is caught. A composer.json with invalid JSON still throws, so a broken config stays visible. --- PhpCollective/Sniffs/Classes/Psr4Sniff.php | 16 ++++++++---- .../Sniffs/Classes/Psr4SniffTest.php | 25 +++++++++++++++++++ tests/_data/Psr4/before.php | 7 ++++++ 3 files changed, 43 insertions(+), 5 deletions(-) create mode 100644 tests/PhpCollective/Sniffs/Classes/Psr4SniffTest.php create mode 100644 tests/_data/Psr4/before.php diff --git a/PhpCollective/Sniffs/Classes/Psr4Sniff.php b/PhpCollective/Sniffs/Classes/Psr4Sniff.php index 45c0564..64ad216 100644 --- a/PhpCollective/Sniffs/Classes/Psr4Sniff.php +++ b/PhpCollective/Sniffs/Classes/Psr4Sniff.php @@ -9,6 +9,7 @@ namespace PhpCollective\Sniffs\Classes; +use InvalidArgumentException; use PHP_CodeSniffer\Config; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; @@ -100,11 +101,16 @@ protected function initializeThisSniffIfNotYet(Config $config): void { if ($this->initialization === static::UNINITIALIZED) { $this->initialization = static::INITIALIZATION_FAILURE; - $this->autoloadabilityInspectors = - AutoloadabilityInspectorsFactory::create( - $config->getSettings()['basepath'] ?: getcwd(), - $this->composerJsonPath, - ); + try { + $this->autoloadabilityInspectors = + AutoloadabilityInspectorsFactory::create( + $config->getSettings()['basepath'] ?: getcwd(), + $this->composerJsonPath, + ); + } catch (InvalidArgumentException) { + // Missing or unreadable composer.json: nothing to check against. Invalid JSON still throws. + return; + } $this->initialization = static::INITIALIZED; } } diff --git a/tests/PhpCollective/Sniffs/Classes/Psr4SniffTest.php b/tests/PhpCollective/Sniffs/Classes/Psr4SniffTest.php new file mode 100644 index 0000000..d46e617 --- /dev/null +++ b/tests/PhpCollective/Sniffs/Classes/Psr4SniffTest.php @@ -0,0 +1,25 @@ +composerJsonPath = 'does-not-exist/composer.json'; + + $this->assertSnifferFindsErrors($sniff, 0); + } +} diff --git a/tests/_data/Psr4/before.php b/tests/_data/Psr4/before.php new file mode 100644 index 0000000..d5f03cd --- /dev/null +++ b/tests/_data/Psr4/before.php @@ -0,0 +1,7 @@ +