Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
25 / 25 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
| Workspace | |
100.00% |
25 / 25 |
|
100.00% |
5 / 5 |
9 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| __destruct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| create | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| remove | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
4 | |||
| getPath | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * @license MIT |
| 5 | * @author hazuki3417<hazuki3417@gmail.com> |
| 6 | * @copyright 2023 hazuki3417 all rights reserved. |
| 7 | */ |
| 8 | |
| 9 | namespace Selen\Dir; |
| 10 | |
| 11 | use RecursiveDirectoryIterator; |
| 12 | use RecursiveIteratorIterator; |
| 13 | use RuntimeException; |
| 14 | |
| 15 | /** |
| 16 | * 作業ディレクトリの作成・削除を提供するクラス |
| 17 | */ |
| 18 | class Workspace |
| 19 | { |
| 20 | /** @var string 作業パス */ |
| 21 | private string $path; |
| 22 | |
| 23 | /** |
| 24 | * 新しいオブジェクトを作成します |
| 25 | * |
| 26 | * @param string $path 作業ディレクトリパスを指定します |
| 27 | * |
| 28 | * @return Workspace 新しいオブジェクトを返します |
| 29 | */ |
| 30 | public function __construct(string $path) |
| 31 | { |
| 32 | $this->path = $path; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * 作業ディレクトリを削除します |
| 37 | */ |
| 38 | public function __destruct() |
| 39 | { |
| 40 | $this->remove(); |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * 作業ディレクトリを作成します |
| 45 | * |
| 46 | * @param int $permissions 権限を指定します |
| 47 | */ |
| 48 | public function create(int $permissions = 0777): void |
| 49 | { |
| 50 | if (\file_exists($this->path)) { |
| 51 | $mes = \sprintf( |
| 52 | 'Failed to create workspace. %s directory already exists.', |
| 53 | $this->path |
| 54 | ); |
| 55 | throw new RuntimeException($mes); |
| 56 | } |
| 57 | |
| 58 | \mkdir($this->path, $permissions, true); |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * 作業ディレクトリを削除します |
| 63 | */ |
| 64 | public function remove(): void |
| 65 | { |
| 66 | if (!\is_dir($this->path)) { |
| 67 | return; |
| 68 | } |
| 69 | |
| 70 | $iterator = new RecursiveDirectoryIterator( |
| 71 | $this->path, |
| 72 | RecursiveDirectoryIterator::SKIP_DOTS |
| 73 | ); |
| 74 | $files = new RecursiveIteratorIterator( |
| 75 | $iterator, |
| 76 | RecursiveIteratorIterator::CHILD_FIRST |
| 77 | ); |
| 78 | |
| 79 | /** @var \SplFileInfo $file */ |
| 80 | foreach ($files as $file) { |
| 81 | $file->isDir() ? |
| 82 | rmdir($file->getRealPath()) : |
| 83 | unlink($file->getRealPath()); |
| 84 | } |
| 85 | rmdir($this->path); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * 作業ディレクトリパスを取得します |
| 90 | * |
| 91 | * @return string 作業ディレクトリパスを返します |
| 92 | */ |
| 93 | public function getPath(): string |
| 94 | { |
| 95 | return $this->path; |
| 96 | } |
| 97 | } |