-
Notifications
You must be signed in to change notification settings - Fork 1
/
FixtureTrait.php
82 lines (69 loc) · 1.83 KB
/
FixtureTrait.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
<?php
declare(strict_types=1);
namespace YourNamespace\App\Tests\Traits;
use Symfony\Component\Filesystem\Filesystem;
/**
* Trait FixtureTrait.
*
* Helpers to work with fixture files.
*
* @phpstan-ignore trait.unused
*/
trait FixtureTrait {
/**
* Fixture directory.
*/
protected string $fixtureDir;
/**
* Initialize fixture directory.
*
* @param string|null $name
* Optional fixture name.
* @param string|null $root
* Optional root directory.
*/
public function fixtureInit(?string $name, ?string $root = NULL): void {
$name = $name ?? get_class($this);
$root = $root ?? sys_get_temp_dir();
$this->fixtureDir = $root . DIRECTORY_SEPARATOR . date('U') . DIRECTORY_SEPARATOR . $name;
}
/**
* Create fixture file at provided path.
*
* @param string $path
* File path.
* @param string $name
* Optional file name.
* @param string|array<string> $content
* Optional file content.
*
* @return string
* Created file name.
*/
protected function fixtureCreateFile(string $path, string $name = '', string|array $content = ''): string {
$fs = new Filesystem();
$name = $name !== '' && $name !== '0' ? $name : 'tmp' . rand(1000, 100000);
$path = $path . DIRECTORY_SEPARATOR . $name;
$dir = dirname($path);
if (!empty($dir)) {
$fs->mkdir($dir);
}
$fs->touch($path);
if (!empty($content)) {
$content = is_array($content) ? implode(PHP_EOL, $content) : $content;
$fs->dumpFile($path, $content);
}
return $path;
}
/**
* Remove fixture file at provided path.
*
* @param string $path
* File path.
* @param string $name
* File name.
*/
protected function fixtureRemoveFile(string $path, string $name): void {
(new Filesystem())->remove($path . DIRECTORY_SEPARATOR . $name);
}
}