. */ namespace SP\Infrastructure\File; use Directory; use SP\Domain\Core\Exceptions\CheckException; use SP\Domain\File\Ports\DirectoryHandlerService; use function SP\__u; /** * Class DirectoryHandler */ final class DirectoryHandler implements DirectoryHandlerService { public function __construct(private readonly string $path) { } /** * @throws CheckException */ public function checkOrCreate(): void { if (!$this->isDir() && !$this->create()) { throw CheckException::error(sprintf(__u('Unable to create directory ("%s")'), $this->path)); } if (!$this->isWritable()) { throw CheckException::error(__u('Please, check the directory permissions')); } } public function isDir(): bool { return @is_dir($this->path); } public function create(int $permissions = 0750): bool { return @mkdir($this->path, $permissions, true); } public function isWritable(): bool { return @is_writable($this->path); } /** * @throws CheckException */ public function getDir(): Directory { $dir = dir($this->path); if (!$dir) { throw CheckException::error(sprintf(__u('Unable to open directory ("%s")'), $this->path)); } return $dir; } public function getPath(): string { return $this->path; } }