VersionPress\Utils\ReferenceUtils::getMatchingPaths PHP Method

getMatchingPaths() public static method

The pattern comes from a schema file. For example line some_option[/\d+/]["key"] contains pattern [/\d+/]["key"]. It can contain regular expressions to match multiple / dynamic keys. Examples: For $value = [0 => [key => value], 1 => [key => value]] And $pathInStructure = [0]["key"] Returns [[0, key]] For the same $value nad $pathInStructure = [/\d+/]["key"] Returns [[0, key], [1, key]]
public static getMatchingPaths ( array | object $value, string $pathInStructure ) : array
$value array | object
$pathInStructure string
return array
    public static function getMatchingPaths($value, $pathInStructure)
    {
        // https://regex101.com/r/vR8yK3/2
        $re = "/(?:\\[(?<number>\\d+)|\"(?<string>(?:[^\"\\\\]|\\\\.)*)\"|\\/(?<regex>(?:[^\\/\\\\]|\\\\.)*)\\/)\\]+/";
        preg_match_all($re, $pathInStructure, $matches, PREG_SET_ORDER);
        $pathParts = array_map(function ($match) {
            if (strlen($match['number']) > 0) {
                return ['type' => 'exact-value', 'value' => intval($match['number'])];
            } else {
                if (strlen($match['string']) > 0) {
                    return ['type' => 'exact-value', 'value' => $match['string']];
                } else {
                    $regex = "/^{$match['regex']}\$/";
                    return ['type' => 'regex', 'value' => $regex];
                }
            }
        }, $matches);
        $paths = self::getMatchingPathsFromSubtree($value, $pathParts);
        return $paths;
    }

Usage Example

コード例 #1
0
 /**
  * @test
  */
 public function morePatternsWithNotMatchingData()
 {
     $pathInStructure = '[/\\d+/][/some-.*/][/[0-9]+/]';
     $value = [0 => ['some-key' => [1 => 'value']], 'string-key' => 'value', 1 => ['some-other-key' => [1 => 'value']], 2 => ['some-key' => 'value']];
     $paths = ReferenceUtils::getMatchingPaths($value, $pathInStructure);
     $this->assertEquals([[0, 'some-key', 1], [1, 'some-other-key', 1]], $paths);
 }
All Usage Examples Of VersionPress\Utils\ReferenceUtils::getMatchingPaths