CommonPathDeterminator   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 21
c 2
b 0
f 0
dl 0
loc 65
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getPathFromCommonCharacters() 0 8 3
A determineCommonPath() 0 10 2
A stringBeginsWith() 0 7 2
A determineCommonCharacters() 0 15 4
1
<?php
2
3
namespace AppBundle\ShowUnusedPhpFiles;
4
5
/**
6
 * Determines the (parent) path common to an array of paths.
7
 */
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)
66
    {
67
        if ($commonCharacters === '') {
68
            return '';
69
        }
70
71
        $path = (substr($commonCharacters, -1) === '/') ? $commonCharacters : dirname($commonCharacters);
72
        return realpath($path);
73
    }
74
}
75