1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Hyde\Testing; |
6
|
|
|
|
7
|
|
|
use Hyde\Facades\Filesystem; |
8
|
|
|
use Hyde\Framework\Actions\ConvertsArrayToFrontMatter; |
9
|
|
|
use function in_array; |
10
|
|
|
|
11
|
|
|
trait CreatesTemporaryFiles |
12
|
|
|
{ |
13
|
|
|
protected array $fileMemory = []; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Create a temporary file in the project directory. |
17
|
|
|
* The TestCase will automatically remove the file when the test is completed. |
18
|
|
|
*/ |
19
|
|
|
protected function file(string $path, ?string $contents = null): void |
20
|
|
|
{ |
21
|
|
|
if ($contents) { |
22
|
|
|
Filesystem::put($path, $contents); |
23
|
|
|
} else { |
24
|
|
|
Filesystem::touch($path); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
$this->cleanUpWhenDone($path); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Create a temporary directory in the project directory. |
32
|
|
|
* The TestCase will automatically remove the entire directory when the test is completed. |
33
|
|
|
*/ |
34
|
|
|
protected function directory(string $path): void |
35
|
|
|
{ |
36
|
|
|
Filesystem::makeDirectory($path, recursive: true, force: true); |
37
|
|
|
|
38
|
|
|
$this->cleanUpWhenDone($path); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Create a temporary Markdown+FrontMatter file in the project directory. |
43
|
|
|
*/ |
44
|
|
|
protected function markdown(string $path, string $contents = '', array $matter = []): void |
45
|
|
|
{ |
46
|
|
|
$this->file($path, (new ConvertsArrayToFrontMatter())->execute($matter).$contents); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function cleanUpFilesystem(): void |
50
|
|
|
{ |
51
|
|
|
if (sizeof($this->fileMemory) > 0) { |
52
|
|
|
foreach ($this->fileMemory as $file) { |
53
|
|
|
if (Filesystem::isDirectory($file)) { |
54
|
|
|
if (! in_array($file, ['_site', '_media', '_pages', '_posts', '_docs', 'app', 'config', 'storage', 'vendor', 'node_modules'])) { |
55
|
|
|
Filesystem::deleteDirectory($file); |
56
|
|
|
} |
57
|
|
|
} else { |
58
|
|
|
Filesystem::unlinkIfExists($file); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$this->fileMemory = []; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Mark a path to be deleted when the test is completed. |
68
|
|
|
*/ |
69
|
|
|
protected function cleanUpWhenDone(string $path): void |
70
|
|
|
{ |
71
|
|
|
$this->fileMemory[] = $path; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|