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