|
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
|
6 |
|
public function __construct($applicationPath = '') |
|
24
|
|
|
{ |
|
25
|
6 |
|
$this->applicationPath = realpath($applicationPath); |
|
26
|
6 |
|
} |
|
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
|
6 |
|
public function normalize($source) |
|
36
|
|
|
{ |
|
37
|
6 |
|
$fileSystem = new Filesystem(); |
|
38
|
|
|
|
|
39
|
|
|
// if the source is a file info, it must exists and be readable |
|
40
|
6 |
|
if ($source instanceof SplFileInfo) { |
|
41
|
|
|
|
|
42
|
5 |
|
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
|
5 |
|
return $source; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
// if the source is not an instance of SplInfo, it should be a string |
|
51
|
3 |
|
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
|
|
|
); |
|
55
|
|
|
} |
|
56
|
3 |
|
$path = $source; |
|
57
|
|
|
|
|
58
|
|
|
// if the file does not exists, try to add the application path before |
|
59
|
3 |
|
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
|
|
|
); |
|
66
|
|
|
} |
|
67
|
1 |
|
$path = $this->applicationPath.'/'.$source; |
|
68
|
|
|
} |
|
69
|
|
|
// normalize source using SplInfo |
|
70
|
3 |
|
$source = new SplFileInfo($path); |
|
71
|
|
|
|
|
72
|
3 |
|
return $source; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|