|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ahc\Phint\Util; |
|
4
|
|
|
|
|
5
|
|
|
use Ahc\Json\Comment; |
|
6
|
|
|
|
|
7
|
|
|
class Path |
|
8
|
|
|
{ |
|
9
|
|
|
/** @var string */ |
|
10
|
|
|
protected $phintPath; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Platform agnostic absolute path detection. |
|
14
|
|
|
* |
|
15
|
|
|
* @param string $path |
|
16
|
|
|
* |
|
17
|
|
|
* @return bool |
|
18
|
|
|
*/ |
|
19
|
|
|
public function isAbsolute(string $path): bool |
|
20
|
|
|
{ |
|
21
|
|
|
if (DIRECTORY_SEPARATOR === '\\') { |
|
22
|
|
|
return strpos($path, ':') === 1; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
return isset($path[0]) && $path[0] === '/'; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function getRelativePath($fullPath, $basePath): string |
|
29
|
|
|
{ |
|
30
|
|
|
if (strpos($fullPath, $basePath) === 0) { |
|
31
|
|
|
return substr($fullPath, strlen($basePath)); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
// Hmm! |
|
35
|
|
|
return $fullPath; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function ensureDir(string $dir): bool |
|
39
|
|
|
{ |
|
40
|
|
|
if (!\is_dir($dir)) { |
|
41
|
|
|
return \mkdir($dir, 0777, true); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return true; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function getExtension(string $filePath): string |
|
48
|
|
|
{ |
|
49
|
|
|
return \pathinfo($filePath, \PATHINFO_EXTENSION); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function readAsJson(string $filePath, bool $asArray = true) |
|
53
|
|
|
{ |
|
54
|
|
|
return (new Comment)->decode(\file_get_contents($filePath), $asArray); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function writeFile(string $file, $content, int $mode = null): bool |
|
58
|
|
|
{ |
|
59
|
|
|
$this->ensureDir(\dirname($file)); |
|
60
|
|
|
|
|
61
|
|
|
if (!\is_string($content)) { |
|
62
|
|
|
$content = \json_encode($content, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return \file_put_contents($file, $content, $mode) > 0; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function getPhintPath(string $subpath = ''): string |
|
69
|
|
|
{ |
|
70
|
|
|
$this->initPhintPath(); |
|
71
|
|
|
|
|
72
|
|
|
if ($subpath && $this->phintPath) { |
|
73
|
|
|
return $this->phintPath . '/' . \ltrim($subpath, '/'); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
return $this->phintPath; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
protected function initPhintPath() |
|
80
|
|
|
{ |
|
81
|
|
|
if (null !== $this->phintPath) { |
|
82
|
|
|
return; |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
$this->phintPath = ''; |
|
86
|
|
|
|
|
87
|
|
|
if (false !== $home = ($_SERVER['HOME'] ?? \getenv('HOME'))) { |
|
88
|
|
|
$path = \rtrim($home, '/') . '/.phint'; |
|
89
|
|
|
|
|
90
|
|
|
if ($this->ensureDir($path)) { |
|
91
|
|
|
$this->phintPath = $path; |
|
92
|
|
|
} |
|
93
|
|
|
} |
|
94
|
|
|
} |
|
95
|
|
|
} |
|
96
|
|
|
|