-
Notifications
You must be signed in to change notification settings - Fork 1
/
VfsTrait.php
105 lines (87 loc) · 2.28 KB
/
VfsTrait.php
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
<?php
declare(strict_types=1);
namespace YourNamespace\App\Tests\Traits;
use org\bovigo\vfs\vfsStream;
/**
* Trait VfsTrait.
*
* Provides methods for working with the virtual file system.
*
* @phpstan-ignore trait.unused
*/
trait VfsTrait {
/**
* The root directory for the virtual file system.
*
* @var \org\bovigo\vfs\vfsStreamDirectory
*/
protected static $vfsRootDirectory;
/**
* Set up the root directory for the virtual file system.
*
* @param string $name
* The name of the root directory.
*/
public static function vfsSetRoot(string $name = 'root'): void {
self::$vfsRootDirectory = vfsStream::setup($name);
}
/**
* Create a directory.
*
* @param string $path
* The path to the directory.
*
* @return string
* The path to the created directory.
*/
public static function vfsCreateDirectory(string $path): string {
$path = static::vfsNormalizePath($path);
if (!static::$vfsRootDirectory) {
static::vfsSetRoot();
}
return vfsStream::newDirectory($path)->at(static::$vfsRootDirectory)->url();
}
/**
* Create a file.
*
* @param string $path
* The path to the file.
* @param string|null $contents
* The contents of the file.
* @param int|null $permissions
* The permissions of the file.
*
* @return string
* The path to the created file.
*/
public static function vfsCreateFile($path, $contents = NULL, $permissions = NULL) {
$path = static::vfsNormalizePath($path);
if (!static::$vfsRootDirectory) {
static::vfsSetRoot();
}
$file = vfsStream::newFile($path, $permissions)->at(static::$vfsRootDirectory);
if ($contents) {
$file->withContent($contents);
}
return $file->url();
}
/**
* Normalize a path to be used with the virtual file system.
*
* @param string $path
* The path to normalize.
*
* @return string
* The normalized path.
*
* @throws \Exception
* If the path does not start with 'vfs://root/'.
*/
protected static function vfsNormalizePath(string $path): string {
$prefix = 'vfs://root/';
if (!str_starts_with($path, $prefix)) {
throw new \Exception('Fixture path must start with ' . $prefix);
}
return substr($path, strlen($prefix));
}
}