Completed
Push — master ( 072a4c...29b8f2 )
by Maarten
02:09
created

GenerateRelation::generate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Mtolhuys\LaravelSchematics\Actions;
4
5
use Illuminate\Support\Facades\File;
6
use Mtolhuys\LaravelSchematics\Services\ColumnParser;
7
use ReflectionClass;
8
9
class GenerateRelation
10
{
11
    /**
12
     * @param array $relation
13
     * @return bool
14
     * @throws \ReflectionException
15
     */
16
    public function generate($relation): bool
17
    {
18
        $source = $relation['source'];
19
        $file = (new ReflectionClass($source))->getFileName();
20
        $lines = file($file , FILE_IGNORE_NEW_LINES);
21
        $content = str_replace(
22
            ['$class$', '$method$', '$type$', '$target$', '$keys$'],
23
            [
24
                $relation['type'],
25
                $relation['method']['name'],
26
                lcfirst($relation['type']),
27
                $relation['target'],
28
                $relation['keys'] ?? '',
29
            ],
30
            File::get(__DIR__.'/../../resources/stubs/relation.stub')
31
        );
32
33
        $lines[$this->endOfClass($file) - 1] = PHP_EOL . $content. '}';
34
35
        return file_put_contents($file , implode( "\n", $lines));
36
    }
37
38
    private function endOfClass($file)
39
    {
40
        $lines = explode(PHP_EOL, file_get_contents($file));
41
        $lastOccurrence = null;
42
43
        foreach ($lines as $index => $line) {
44
            if (strpos(trim($line), '}') !== false) {
45
                $lastOccurrence = $index + 1;
46
            }
47
        }
48
49
        return $lastOccurrence;
50
    }
51
}
52