ReplaceByPatternTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 26
c 1
b 0
f 0
dl 0
loc 82
ccs 27
cts 27
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A replaceByRegex() 0 18 3
A getPatternRegex() 0 18 1
A replaceByPattern() 0 12 2
1
<?php
2
3
/**
4
 * Copyright MediaCT. All rights reserved.
5
 * https://www.mediact.nl
6
 */
7
8
namespace Mediact\DataContainer;
9
10
trait ReplaceByPatternTrait
11
{
12
    /**
13
     * Get a replacement path for a matched path.
14
     *
15
     * @param string $pattern
16
     * @param string $match
17
     * @param string $replacement
18
     * @param string $separator
19
     *
20
     * @return string
21
     */
22 10
    protected function replaceByPattern(
23
        string $pattern,
24
        string $match,
25
        string $replacement,
26
        string $separator = DataContainerInterface::SEPARATOR
27
    ): string {
28 10
        return $replacement === '$0'
29 1
            ? $match
30 9
            : $this->replaceByRegex(
31 9
                $this->getPatternRegex($pattern, $separator),
32 9
                $match,
33 10
                $replacement
34
            );
35
    }
36
37
    /**
38
     * Get a replacement path for a matched path by regex.
39
     *
40
     * @param string $regex
41
     * @param string $match
42
     * @param string $replacement
43
     *
44
     * @return string
45
     */
46 9
    private function replaceByRegex(
47
        string $regex,
48
        string $match,
49
        string $replacement
50
    ): string {
51 9
        if (preg_match($regex, $match, $matches)) {
52 9
            $replacement = preg_replace_callback(
53 9
                '/\$([\d]+)/',
54
                function (array $match) use ($matches) {
55 9
                    return array_key_exists($match[1], $matches)
56 9
                        ? $matches[$match[1]]
57 9
                        : $match[0];
58 9
                },
59 9
                $replacement
60
            );
61
        }
62
63 9
        return $replacement;
64
    }
65
66
    /**
67
     * Translate a fnmatch pattern to a regex.
68
     *
69
     * @param string $pattern
70
     * @param string $separator
71
     *
72
     * @return string
73
     */
74 9
    private function getPatternRegex(
75
        string $pattern,
76
        string $separator = DataContainerInterface::SEPARATOR
77
    ): string {
78
        $transforms = [
79 9
            '\*'  => sprintf('([^%s]*)', preg_quote($separator, '#')),
80 9
            '\?'  => '(.)',
81 9
            '\[\!' => '([^',
82 9
            '\['  => '([',
83 9
            '\]'  => '])'
84
        ];
85
86 9
        $result = sprintf(
87 9
            '#^%s$#',
88 9
            strtr(preg_quote($pattern, '#'), $transforms)
89
        );
90
91 9
        return $result;
92
    }
93
}
94