Total Complexity | 11 |
Total Lines | 65 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
8 | final class CommonPathDeterminator |
||
9 | { |
||
10 | /** |
||
11 | * @param string[] $paths |
||
12 | * @return string |
||
13 | */ |
||
14 | public function determineCommonPath(array $paths) |
||
15 | { |
||
16 | if (count($paths) === 0) { |
||
17 | return ''; |
||
18 | } |
||
19 | |||
20 | $commonCharacters = $this->determineCommonCharacters($paths); |
||
21 | $commonPath = $this->getPathFromCommonCharacters($commonCharacters); |
||
22 | |||
23 | return $commonPath; |
||
24 | } |
||
25 | |||
26 | /** |
||
27 | * @param string[] $paths |
||
28 | * @return string |
||
29 | */ |
||
30 | private function determineCommonCharacters(array $paths) |
||
31 | { |
||
32 | $commonCharacters = $paths[0]; |
||
33 | |||
34 | foreach ($paths as $path) { |
||
35 | if ($this->stringBeginsWith($path, $commonCharacters)) { |
||
36 | continue; |
||
37 | } |
||
38 | |||
39 | do { |
||
40 | $commonCharacters = substr($commonCharacters, 0, -1); |
||
41 | } while (!$this->stringBeginsWith($path, $commonCharacters)); |
||
42 | } |
||
43 | |||
44 | return $commonCharacters; |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * @param string $hay |
||
49 | * @param string $needle |
||
50 | * @return bool |
||
51 | */ |
||
52 | private function stringBeginsWith($hay, $needle) |
||
53 | { |
||
54 | if ($needle === '') { |
||
55 | return true; |
||
56 | } |
||
57 | |||
58 | return strpos($hay, $needle) === 0; |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * @param string $commonCharacters |
||
63 | * @return string |
||
64 | */ |
||
65 | private function getPathFromCommonCharacters($commonCharacters) |
||
73 | } |
||
74 | } |
||
75 |