Completed
Push — master ( e00a73...ad4a30 )
by Arnaud
10:05 queued 07:12
created

Locator::locate()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.0061

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 28
ccs 15
cts 16
cp 0.9375
rs 8.439
cc 5
eloc 17
nc 7
nop 1
crap 5.0061
1
<?php
2
3
namespace JK\Sam\File;
4
5
use Exception;
6
use SplFileInfo;
7
use Symfony\Component\Finder\Finder;
8
9
class Locator
10
{
11
    /**
12
     * @var Normalizer
13
     */
14
    protected $normalizer;
15
16
    /**
17
     * Locator constructor.
18
     *
19
     * @param Normalizer $normalizer
20
     */
21 1
    public function __construct(Normalizer $normalizer)
22
    {
23 1
        $this->normalizer = $normalizer;
24 1
    }
25
26
    /**
27
     * Locate a source either if it a file or a directory and normalize it. Return an array of SplFileInfo.
28
     *
29
     * @param $source
30
     * @return SplFileInfo[]
31
     * @throws Exception
32
     */
33 1
    public function locate($source)
34
    {
35 1
        $sources = [];
36 1
        $normalizedSources = [];
37
38 1
        if (is_dir($source)) {
39 1
            $finder = new Finder();
40 1
            $finder->in($source);
41
42 1
            foreach ($finder as $file) {
43 1
                $sources[] = $file;
44
            }
45 1
        } else if (strstr($source, '*') !== false) {
46
            // if the source contains a wildcard, we use it with the finder component
47
            $sources = $this->getSourcesFromFinder($source);
48
        } else {
49 1
            $sources[] = $source;
50
        }
51
52
        // each found sources should be normalized
53 1
        foreach ($sources as $source) {
54 1
            $normalizedSources[] = $this
55 1
                ->normalizer
56 1
                ->normalize($source);
57
        }
58
59 1
        return $normalizedSources;
60
    }
61
62
    /**
63
     * @return Normalizer
64
     */
65 1
    public function getNormalizer()
66
    {
67 1
        return $this->normalizer;
68
    }
69
70
    /**
71
     * @param $source
72
     * @return SplFileInfo[]
73
     */
74
    protected function getSourcesFromFinder($source)
75
    {
76
        $array = explode(DIRECTORY_SEPARATOR, $source);
77
        $filename = array_pop($array);
78
        $directory = $source;
79
        $pattern = '*';
80
81
        // if a dot is present, the last part is the filename pattern
82
        if (strstr($filename, '.') !== false) {
83
            $pattern = $filename;
84
            $directory = implode('/', $array);
85
        }
86
        $finder = new Finder();
87
        $finder
88
            ->name($pattern)
89
            ->in($directory);
90
91
        $sources = [];
92
93
        foreach ($finder as $source) {
94
            $sources[] = $source;
95
        }
96
97
        return $sources;
98
    }
99
}
100