|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace a9f\Fractor\FileSystem; |
| 6 | + |
| 7 | +use a9f\Fractor\Contract\FilesystemInterface; |
| 8 | +use League\Flysystem\DirectoryListing; |
| 9 | +use League\Flysystem\FilesystemOperator; |
| 10 | +use League\Flysystem\FilesystemReader; |
| 11 | +use League\Flysystem\UnableToDeleteFile; |
| 12 | +use League\Flysystem\UnableToReadFile; |
| 13 | +use League\Flysystem\UnableToWriteFile; |
| 14 | + |
| 15 | +final readonly class FlysystemFilesystem implements FilesystemInterface |
| 16 | +{ |
| 17 | + public function __construct( |
| 18 | + private FilesystemOperator $filesystemOperator |
| 19 | + ) { |
| 20 | + } |
| 21 | + |
| 22 | + public function write(string $location, string $contents, array $config = []): void |
| 23 | + { |
| 24 | + try { |
| 25 | + $this->filesystemOperator->write($location, $contents, $config); |
| 26 | + } catch (UnableToWriteFile $e) { |
| 27 | + throw new \RuntimeException(sprintf('Failed to write file "%s": %s', $location, $e->getMessage()), 0, $e); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + public function fileExists(string $location): bool |
| 32 | + { |
| 33 | + return $this->filesystemOperator->fileExists($location); |
| 34 | + } |
| 35 | + |
| 36 | + public function read(string $location): string |
| 37 | + { |
| 38 | + try { |
| 39 | + return $this->filesystemOperator->read($location); |
| 40 | + } catch (UnableToReadFile $e) { |
| 41 | + throw new \RuntimeException(sprintf('Failed to read file "%s": %s', $location, $e->getMessage()), 0, $e); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public function move(string $source, string $destination, array $config = []): void |
| 46 | + { |
| 47 | + $this->filesystemOperator->move($source, $destination, $config); |
| 48 | + } |
| 49 | + |
| 50 | + public function listContents(string $location, bool $deep = FilesystemReader::LIST_SHALLOW): DirectoryListing |
| 51 | + { |
| 52 | + return $this->filesystemOperator->listContents($location, $deep); |
| 53 | + } |
| 54 | + |
| 55 | + public function appendToFile(string $location, string $content): void |
| 56 | + { |
| 57 | + $existingContent = $this->read($location); |
| 58 | + |
| 59 | + $existingContent .= PHP_EOL . $content; |
| 60 | + |
| 61 | + $this->write($location, $existingContent); |
| 62 | + } |
| 63 | + |
| 64 | + public function delete(string $location): void |
| 65 | + { |
| 66 | + try { |
| 67 | + $this->filesystemOperator->delete($location); |
| 68 | + } catch (UnableToDeleteFile $e) { |
| 69 | + throw new \RuntimeException(sprintf('Failed to delete file "%s": %s', $location, $e->getMessage()), 0, $e); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments