Completed
Push — master ( 9f2dac...cab9cb )
by Arnaud
07:03 queued 01:55
created

Normalizer::normalize()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 39
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 39
ccs 21
cts 21
cp 1
rs 8.439
cc 6
eloc 18
nc 6
nop 1
crap 6
1
<?php
2
3
namespace JK\Sam\File;
4
5
use Exception;
6
use SplFileInfo;
7
use Symfony\Component\Filesystem\Filesystem;
8
9
class Normalizer
10
{
11
    /**
12
     * Current application root absolute path, used to resolve relative path.
13
     *
14
     * @var string
15
     */
16
    protected $applicationPath;
17
18
    /**
19
     * Locator constructor.
20
     *
21
     * @param string $applicationPath
22
     */
23 2
    public function __construct($applicationPath = '')
24
    {
25 2
        $this->applicationPath = realpath($applicationPath);
26 2
    }
27
28
    /**
29
     * Normalize a source (string or SplInfo) into an instance of SplInfo.
30
     *
31
     * @param mixed $source
32
     * @return SplFileInfo
33
     * @throws Exception
34
     */
35 2
    public function normalize($source)
36
    {
37 2
        $fileSystem = new Filesystem();
38
39
        // if the source is a file info, it must exists and be readable
40 2
        if ($source instanceof SplFileInfo) {
41
42 2
            if (!$fileSystem->exists($source->getRealPath())) {
43 1
                throw new Exception('Unable to find '.$source.' during normalization process');
44
            }
45
46
            // the source is already normalized
47 2
            return $source;
48
        }
49
50
        // if the source is not an instance of SplInfo, it should be a string
51 2
        if (!is_string($source)) {
52 1
            throw new Exception(
53 1
                'The source should be a string if it is not an instance of SplInfo (instead of '.gettype($source).')'
54 1
            );
55
        }
56 2
        $path = $source;
57
58
        // if the file does not exists, try to add the application path before
59 2
        if (!$fileSystem->exists($source)) {
60
61 1
            if (!$fileSystem->exists($this->applicationPath.'/'.$source)) {
62 1
                throw new Exception(
63 1
                    'File '.$source.' not found, searched in '
64 1
                    .implode(', ', [$source, $this->applicationPath.'/'.$source])
65 1
                );
66
            }
67 1
            $path = $this->applicationPath.'/'.$source;
68 1
        }
69
        // normalize source using SplInfo
70 2
        $source = new SplFileInfo($path);
71
72 2
        return $source;
73
    }
74
}
75