-
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathWorkspace.php
More file actions
121 lines (93 loc) · 2.66 KB
/
Workspace.php
File metadata and controls
121 lines (93 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
namespace PhpBench\Tests\Util;
use InvalidArgumentException;
use Symfony\Component\Filesystem\Path;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use SplFileInfo;
class Workspace
{
public function __construct(private readonly string $path)
{
}
public static function create(string $path): self
{
if (empty($path)) {
throw new RuntimeException(
'Workspace path cannot be empty'
);
}
return new self($path);
}
public function exists(string $path): bool
{
return file_exists($this->path($path));
}
public function path(?string $path = null): string
{
if (null === $path) {
return $this->path;
}
return Path::join($this->path, $path);
}
public function getContents(string $path): string
{
if (false === $this->exists($path)) {
throw new InvalidArgumentException(sprintf(
'File "%s" does not exist',
$path
));
}
$contents = file_get_contents($this->path($path));
if (false === $contents) {
throw new RuntimeException('file_get_contents returned false');
}
return $contents;
}
public function reset(): void
{
if (file_exists($this->path)) {
$this->remove($this->path);
}
mkdir($this->path);
}
public function put(string $path, string $contents): Workspace
{
if (!$this->exists(dirname($path))) {
$this->mkdir(dirname($path));
}
file_put_contents($this->path($path), $contents);
return $this;
}
public function mkdir(string $path): Workspace
{
$path = $this->path($path);
if (file_exists($path)) {
throw new InvalidArgumentException(sprintf(
'Node "%s" already exists, cannot create directory',
$path
));
}
mkdir($path, 0777, true);
return $this;
}
private function remove(string $path = ''): void
{
if ($path) {
$splFileInfo = new SplFileInfo($path);
if (in_array($splFileInfo->getType(), ['socket', 'file', 'link'])) {
unlink($path);
return;
}
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
$this->remove($file->getPathName());
}
rmdir($path);
}
}