diff --git a/src/WP_CLI/JsonManipulator.php b/src/WP_CLI/JsonManipulator.php index 76dca330..4ae27853 100644 --- a/src/WP_CLI/JsonManipulator.php +++ b/src/WP_CLI/JsonManipulator.php @@ -345,7 +345,7 @@ public function removeSubNode($mainNode, $name, $caseInsensitive = false) // WP_ if (preg_match_all($regex, $value, $nameMatches)) { // Just zap them all individually in a case sensitive manner. foreach ( $nameMatches['name'] as $nameMatch ) { - $this->removeSubNode($mainNode, $nameMatch); + $this->removeSubNode($mainNode, str_replace('\\/', '/', $nameMatch)); // Unescape JSON slashes so the key matches the decoded data. } } @@ -386,9 +386,10 @@ public function removeSubNode($mainNode, $name, $caseInsensitive = false) // WP_ // try and find a match for the subkey $childrenClean = $children; - if ($this->pregMatch('{"'.preg_quote($name).'"\s*:}i', $children)) { + $nameRegex = str_replace('/', '\\\\?/', preg_quote($name)); // WP_CLI: Also match a JSON-escaped slash (`\/`) in the key. + if ($this->pregMatch('{"'.$nameRegex.'"\s*:}i', $children)) { // find best match for the value of "name" - if (preg_match_all('{'.self::$DEFINES.'"'.preg_quote($name).'"\s*:\s*(?:(?&json))}x', $children, $matches)) { + if (preg_match_all('{'.self::$DEFINES.'"'.$nameRegex.'"\s*:\s*(?:(?&json))}x', $children, $matches)) { $bestMatch = ''; foreach ($matches[0] as $match) { if (strlen($bestMatch) < strlen($match)) { diff --git a/tests/phpunit/JsonManipulatorTest.php b/tests/phpunit/JsonManipulatorTest.php index 579e6867..fd9965c3 100644 --- a/tests/phpunit/JsonManipulatorTest.php +++ b/tests/phpunit/JsonManipulatorTest.php @@ -1701,6 +1701,36 @@ public function testRemoveSubNodeFromRequire() ', $manipulator->getContents()); } + /** + * @dataProvider removeSubNodeEscapedKeyProvider + */ + #[DataProvider( 'removeSubNodeEscapedKeyProvider' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound + public function testRemoveSubNodeCaseInsensitiveWithEscapedSlash($name) + { + $manipulator = new JsonManipulator('{ + "require": { + "wp-cli\/foo": "^1.0", + "wp-cli/bar": "^1.0" + } +}'); + + $this->assertTrue($manipulator->removeSubNode('require', $name, true)); + $this->assertEquals('{ + "require": { + "wp-cli/bar": "^1.0" + } +} +', $manipulator->getContents()); + } + + public static function removeSubNodeEscapedKeyProvider() + { + return array( + 'same case' => array('wp-cli/foo'), + 'different case' => array('WP-CLI/Foo'), + ); + } + public function testAddSubNodeInRequire() { $manipulator = new JsonManipulator('{