1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mtolhuys\LaravelSchematics\Actions\Relation; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\File; |
6
|
|
|
use ReflectionException; |
7
|
|
|
use ReflectionClass; |
8
|
|
|
|
9
|
|
|
class CreateRelationAction |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @param array $request |
13
|
|
|
* @return object |
14
|
|
|
* @throws ReflectionException |
15
|
|
|
*/ |
16
|
|
|
public function execute($request) |
17
|
|
|
{ |
18
|
|
|
$source = $request['source']; |
19
|
|
|
$stub = __DIR__ . '/../../../resources/stubs/relation.stub'; |
20
|
|
|
$file = (new ReflectionClass($source))->getFileName(); |
21
|
|
|
$lines = file($file, FILE_IGNORE_NEW_LINES); |
22
|
|
|
$injectionLine = $this->endOfClass($file) - 1; |
23
|
|
|
|
24
|
|
|
$lines[$injectionLine] = PHP_EOL . $this->generateMethod($request, $stub) . '}'; |
25
|
|
|
|
26
|
|
|
file_put_contents($file, implode("\n", $lines)); |
27
|
|
|
|
28
|
|
|
return (object) [ |
29
|
|
|
'file' => $file, |
30
|
|
|
'line' => ($injectionLine + count(file($stub)) - 2), |
31
|
|
|
]; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param array $relation |
36
|
|
|
* @param string $stub |
37
|
|
|
* @return string|string[] |
38
|
|
|
*/ |
39
|
|
|
private function generateMethod($relation, string $stub) |
40
|
|
|
{ |
41
|
|
|
$relationGeneratorMethod = config('schematics.relation-generator-method', 'string'); |
42
|
|
|
if ($relationGeneratorMethod === 'class') { |
43
|
|
|
$relationTarget = '\\' . $relation['target'] . '::class'; |
44
|
|
|
} else { |
45
|
|
|
$relationTarget = '\'' . $relation['target'] . '\''; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return str_replace([ |
49
|
|
|
'$class$', |
50
|
|
|
'$method$', |
51
|
|
|
'$type$', |
52
|
|
|
'$target$', |
53
|
|
|
'$keys$' |
54
|
|
|
], [ |
55
|
|
|
$relation['type'], |
56
|
|
|
$relation['method']['name'], |
57
|
|
|
lcfirst($relation['type']), |
58
|
|
|
$relationTarget, |
59
|
|
|
$relation['keys'] ?? '', |
60
|
|
|
], File::get($stub)); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param $file |
65
|
|
|
* @return int|string|null |
66
|
|
|
*/ |
67
|
|
|
private function endOfClass($file) |
68
|
|
|
{ |
69
|
|
|
$lines = explode(PHP_EOL, file_get_contents($file)); |
70
|
|
|
$lastOccurrence = null; |
71
|
|
|
|
72
|
|
|
foreach ($lines as $index => $line) { |
73
|
|
|
if (strpos(trim($line), '}') !== false) { |
74
|
|
|
$lastOccurrence = $index + 1; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $lastOccurrence; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|