Completed
Push — master ( 2507fc...48d67e )
by Maarten
01:18
created

GenerateRelation   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 1
dl 0
loc 65
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 17 1
A generateMethod() 0 16 1
A endOfClass() 0 13 3
1
<?php
2
3
namespace Mtolhuys\LaravelSchematics\Actions;
4
5
use Illuminate\Support\Facades\File;
6
use ReflectionException;
7
use ReflectionClass;
8
9
class GenerateRelation
10
{
11
    /**
12
     * @param array $relation
13
     * @return object
14
     * @throws ReflectionException
15
     */
16
    public function execute($relation)
17
    {
18
        $source = $relation['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($relation, $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(array $relation, string $stub)
40
    {
41
        return str_replace([
42
            '$class$',
43
            '$method$',
44
            '$type$',
45
            '$target$',
46
            '$keys$'
47
        ], [
48
            $relation['type'],
49
            $relation['method']['name'],
50
            lcfirst($relation['type']),
51
            $relation['target'],
52
            $relation['keys'] ?? '',
53
        ], File::get($stub));
54
    }
55
56
    /**
57
     * @param $file
58
     * @return int|string|null
59
     */
60
    private function endOfClass($file)
61
    {
62
        $lines = explode(PHP_EOL, file_get_contents($file));
63
        $lastOccurrence = null;
64
65
        foreach ($lines as $index => $line) {
66
            if (strpos(trim($line), '}') !== false) {
67
                $lastOccurrence = $index + 1;
68
            }
69
        }
70
71
        return $lastOccurrence;
72
    }
73
}
74