From 48c5e81c546413bc150ee30317a2b0ad95d60cc7 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 18 Nov 2024 20:57:53 +0100 Subject: [PATCH] Ruleset::setSniffProperty(): add test for edge case / unused sniff I haven't been able to come up with a _real_ situation in which [this condition](https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/15db7232015d4fc1e023ef1eff0e65777a906f2c/src/Ruleset.php#L1476-L1479) could result in an early return - either via reading an XML ruleset or via inline `phpcs:set` annotation. Having said that, the method is `public` and is regularly used in test frameworks for external standards, so this code should remain in place. This commit now safeguards the behaviour via a test. --- tests/Core/Ruleset/SetSniffPropertyTest.php | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/Core/Ruleset/SetSniffPropertyTest.php b/tests/Core/Ruleset/SetSniffPropertyTest.php index ed902b9084..b974844c0c 100644 --- a/tests/Core/Ruleset/SetSniffPropertyTest.php +++ b/tests/Core/Ruleset/SetSniffPropertyTest.php @@ -202,6 +202,39 @@ public function testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCateg }//end testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategory() + /** + * Test that attempting to set a property for a sniff which isn't registered will be ignored. + * + * @return void + */ + public function testDirectCallIgnoredPropertyForUnusedSniff() + { + $sniffCode = 'Generic.Formatting.SpaceAfterCast'; + $sniffClass = 'PHP_CodeSniffer\\Standards\\Generic\\Sniffs\\Formatting\\SpaceAfterCastSniff'; + + // Set up the ruleset. + $config = new ConfigDouble(['--standard=PSR1']); + $ruleset = new Ruleset($config); + + $ruleset->setSniffProperty( + $sniffClass, + 'ignoreNewlines', + [ + 'scope' => 'sniff', + 'value' => true, + ] + ); + + // Verify that there are sniffs registered. + $this->assertGreaterThan(0, count($ruleset->sniffCodes), 'No sniff codes registered'); + + // Verify that our target sniff has NOT been registered after attempting to set the property. + $this->assertArrayNotHasKey($sniffCode, $ruleset->sniffCodes, 'Unused sniff was registered in sniffCodes, but shouldn\'t have been'); + $this->assertArrayNotHasKey($sniffClass, $ruleset->sniffs, 'Unused sniff was registered in sniffs, but shouldn\'t have been'); + + }//end testDirectCallIgnoredPropertyForUnusedSniff() + + /** * Test that setting a property via a direct call to the Ruleset::setSniffProperty() method * sets the property correctly when using the new $settings array format.