1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Modelarium\Laravel\Console\Commands; |
4
|
|
|
|
5
|
|
|
use Modelarium\Exception\Exception; |
6
|
|
|
use Modelarium\GeneratedCollection; |
7
|
|
|
use Modelarium\GeneratedItem; |
8
|
|
|
|
9
|
|
|
trait WriterTrait |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Write a GeneractedCollection to the filesystem |
13
|
|
|
* |
14
|
|
|
* @param GeneratedCollection $collection |
15
|
|
|
* @param string $basepath |
16
|
|
|
* @param boolean|callable $overwrite. If a callable expects (GeneratedItem $item): bool |
17
|
|
|
* @return array The written files with their full path. |
18
|
|
|
*/ |
19
|
|
|
public function writeFiles(GeneratedCollection $collection, string $basepath, $overwrite = true): array |
20
|
|
|
{ |
21
|
|
|
$writtenFiles = []; |
22
|
|
|
foreach ($collection as $element) { |
23
|
|
|
/** |
24
|
|
|
* @var GeneratedItem $element |
25
|
|
|
*/ |
26
|
|
|
|
27
|
|
|
$path = $basepath . '/' . $element->filename; |
28
|
|
|
$o = false; |
29
|
|
|
if ($element->onlyIfNewFile) { |
30
|
|
|
$o = false; |
31
|
|
|
} elseif (is_bool($overwrite)) { |
32
|
|
|
$o = $overwrite; |
33
|
|
|
} elseif (is_callable($overwrite)) { |
34
|
|
|
$o = $overwrite($element); |
35
|
|
|
} else { |
36
|
|
|
throw new Exception("Invalid overwrite value on writeFiles"); |
37
|
|
|
} |
38
|
|
|
$contents = $element->contents; |
39
|
|
|
if (is_callable($contents)) { |
40
|
|
|
$contents = $contents($basepath, $element); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$this->writeFile( |
44
|
|
|
$path, |
45
|
|
|
$o, |
46
|
|
|
$contents |
47
|
|
|
); |
48
|
|
|
$writtenFiles[] = $path; |
49
|
|
|
} |
50
|
|
|
return $writtenFiles; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Takes a stub file and generates the target file with replacements. |
55
|
|
|
* |
56
|
|
|
* @param string $targetPath The path for the stub file. |
57
|
|
|
* @param boolean $overwrite |
58
|
|
|
* @param string $data The data to write |
59
|
|
|
* @return void |
60
|
|
|
*/ |
61
|
|
|
protected function writeFile(string $targetPath, bool $overwrite, string $data) |
62
|
|
|
{ |
63
|
|
|
if (file_exists($targetPath) && !$overwrite) { |
64
|
|
|
$this->comment("File $targetPath already exists, not overwriting."); |
|
|
|
|
65
|
|
|
return; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$dir = dirname($targetPath); |
69
|
|
|
if (!is_dir($dir)) { |
70
|
|
|
\Safe\mkdir($dir, 0777, true); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$ret = \Safe\file_put_contents($targetPath, $data); |
74
|
|
|
if (!$ret) { |
75
|
|
|
$this->error("Cannot write to $targetPath"); |
|
|
|
|
76
|
|
|
return; |
77
|
|
|
} |
78
|
|
|
$this->line("Wrote $targetPath"); |
|
|
|
|
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|