3
declare(strict_types=1);
5
namespace Upside\Std\Fs;
7
final class Dir implements \Stringable
11
public function __construct(string $dir)
16
public function __toString(): string
21
public static function from(string $dir): self
23
return new self($dir);
26
public function remove(): self
28
return $this->clean()->rmdir($this->dir);
34
public function clean(): self
36
/** @var iterable<\SplFileInfo> $iterator */
37
$iterator = new \RecursiveIteratorIterator(
38
new \RecursiveDirectoryIterator($this->dir, \FilesystemIterator::SKIP_DOTS),
39
\RecursiveIteratorIterator::CHILD_FIRST
42
foreach ($iterator as $file) {
44
$this->rmdir($file->getPathname());
46
File::from($file->getPathname())->remove();
53
public function exists(): bool
55
return \is_dir($this->dir);
58
public function not_exists(): bool
60
return !$this->exists();
63
public function make(int $permissions = 0777): self
65
if ($this->not_exists()) {
66
return $this->mkdir($this->dir, $permissions);
72
public function rename(string $to): Dir
74
$to_dir = self::from($to);
75
if ($to_dir->exists()) {
76
throw new \RuntimeException(\sprintf('Cannot rename dir "%s" to "%s". Dir "%s" already exists.', $this->dir, $to, $to));
79
if (!\rename($this->dir, $to)) {
80
throw new \RuntimeException(\sprintf('Directory "%s" was not renamed to "%s"', $this->dir, $to));
86
private function rmdir(string $directory): self
88
if (!\rmdir($directory)) {
89
throw new \RuntimeException(\sprintf('Directory "%s" was not removed', $directory));
95
private function mkdir(string $directory, int $permissions = 0777, bool $recursive = true): self
97
if (!\mkdir($directory, $permissions, $recursive) && !\is_dir($directory)) {
98
throw new \RuntimeException(\sprintf('Directory "%s" was not created', $this->dir));