|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpList\Core\Domain\Common\Service; |
| 6 | + |
| 7 | +use RuntimeException; |
| 8 | + |
| 9 | +class DirectoryListingService |
| 10 | +{ |
| 11 | + /** |
| 12 | + * @return array<int, array{ |
| 13 | + * name: string, |
| 14 | + * path: string, |
| 15 | + * size: int, |
| 16 | + * type: string, |
| 17 | + * modified: int |
| 18 | + * }> |
| 19 | + */ |
| 20 | + public function list(string $directory, string $realPath): array |
| 21 | + { |
| 22 | + $items = $this->readDirectory($realPath, $directory); |
| 23 | + |
| 24 | + $files = []; |
| 25 | + |
| 26 | + foreach ($items as $item) { |
| 27 | + $entry = $this->createEntry($directory, $realPath, $item); |
| 28 | + |
| 29 | + if ($entry !== null) { |
| 30 | + $files[] = $entry; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + $this->sortFiles($files); |
| 35 | + |
| 36 | + return $files; |
| 37 | + } |
| 38 | + |
| 39 | + private function readDirectory(string $realPath, string $directory): array |
| 40 | + { |
| 41 | + $items = scandir($realPath); |
| 42 | + |
| 43 | + if ($items === false) { |
| 44 | + throw new RuntimeException( |
| 45 | + sprintf('Unable to read directory "%s".', $directory) |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + return $items; |
| 50 | + } |
| 51 | + |
| 52 | + private function sortFiles(array &$files): void |
| 53 | + { |
| 54 | + usort( |
| 55 | + $files, |
| 56 | + static function (array $file1, array $file2): int { |
| 57 | + if ($file1['type'] !== $file2['type']) { |
| 58 | + return $file1['type'] === 'directory' ? -1 : 1; |
| 59 | + } |
| 60 | + |
| 61 | + return strcmp($file1['name'], $file2['name']); |
| 62 | + } |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * @return array{ |
| 68 | + * name:string, |
| 69 | + * path:string, |
| 70 | + * size:int, |
| 71 | + * type:string, |
| 72 | + * modified:int |
| 73 | + * }|null |
| 74 | + */ |
| 75 | + private function createEntry(string $directory, string $realPath, string $item,): ?array |
| 76 | + { |
| 77 | + if ($item === '.' || $item === '..') { |
| 78 | + return null; |
| 79 | + } |
| 80 | + |
| 81 | + $fullPath = $realPath . DIRECTORY_SEPARATOR . $item; |
| 82 | + |
| 83 | + if (!is_file($fullPath) && !is_dir($fullPath)) { |
| 84 | + return null; |
| 85 | + } |
| 86 | + |
| 87 | + $isDirectory = is_dir($fullPath); |
| 88 | + |
| 89 | + return [ |
| 90 | + 'name' => $item, |
| 91 | + 'path' => '/' . trim($directory, '/') . '/' . $item, |
| 92 | + 'size' => $isDirectory ? 0 : (filesize($fullPath) ?: 0), |
| 93 | + 'type' => $isDirectory ? 'directory' : 'file', |
| 94 | + 'modified' => filemtime($fullPath) ?: 0, |
| 95 | + ]; |
| 96 | + } |
| 97 | +} |
0 commit comments