1 | <?php |
||
5 | class Filesystem |
||
6 | { |
||
7 | private string $basePath; |
||
|
|||
8 | |||
9 | public function __construct(string $basePath) |
||
10 | { |
||
11 | $this->basePath = $basePath; |
||
12 | } |
||
13 | |||
14 | public static function inDirectory(string $path): self |
||
15 | { |
||
16 | return new self($path); |
||
17 | } |
||
18 | |||
19 | public function path(string $filename): string |
||
20 | { |
||
21 | return $this->basePath.DIRECTORY_SEPARATOR.$filename; |
||
22 | } |
||
23 | |||
24 | public function has(string $filename): bool |
||
25 | { |
||
26 | return file_exists($this->path($filename)); |
||
27 | } |
||
28 | |||
29 | /* |
||
30 | * Get all file names in this directory that have the same name |
||
31 | * as $fileName, but have a different file extension. |
||
32 | */ |
||
33 | public function getNamesWithDifferentExtension(string $fileName): array |
||
34 | { |
||
35 | if (! file_exists($this->basePath)) { |
||
36 | return []; |
||
37 | } |
||
38 | |||
39 | $extension = pathinfo($fileName, PATHINFO_EXTENSION); |
||
40 | |||
41 | $baseName = substr($fileName, 0, strlen($fileName) - strlen($extension) - 1); |
||
42 | |||
43 | $allNames = scandir($this->basePath); |
||
44 | |||
45 | $namesWithDifferentExtension = array_filter($allNames, function ($existingName) use ($baseName, $extension) { |
||
46 | $existingExtension = pathinfo($existingName, PATHINFO_EXTENSION); |
||
47 | |||
48 | $existingBaseName = substr($existingName, 0, strlen($existingName) - strlen($existingExtension) - 1); |
||
49 | |||
50 | return $existingBaseName === $baseName && $existingExtension !== $extension; |
||
51 | }); |
||
52 | |||
53 | return array_values($namesWithDifferentExtension); |
||
54 | } |
||
55 | |||
56 | public function read(string $filename): string |
||
57 | { |
||
58 | return file_get_contents($this->path($filename)); |
||
59 | } |
||
60 | |||
61 | public function put(string $filename, string $contents): void |
||
62 | { |
||
63 | if (! file_exists($this->basePath)) { |
||
64 | mkdir($this->basePath, 0777, true); |
||
65 | } |
||
66 | |||
67 | file_put_contents($this->path($filename), $contents); |
||
68 | } |
||
69 | |||
70 | public function delete(string $fileName): bool |
||
71 | { |
||
72 | return unlink($this->path($fileName)); |
||
73 | } |
||
74 | |||
75 | public function copy(string $filePath, string $fileName): void |
||
76 | { |
||
77 | if (! file_exists($this->basePath)) { |
||
78 | mkdir($this->basePath, 0777, true); |
||
79 | } |
||
80 | |||
81 | copy($filePath, $this->path($fileName)); |
||
82 | } |
||
83 | |||
84 | public function fileEquals(string $filePath, string $fileName): bool |
||
85 | { |
||
86 | return sha1_file($filePath) === sha1_file($this->path($fileName)); |
||
87 | } |
||
88 | } |
||
89 |