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

RemoveRelation::startOfMethod()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace Mtolhuys\LaravelSchematics\Actions;
4
5
use ReflectionException;
6
7
class RemoveRelation
8
{
9
    /**
10
     * @param $method
11
     * @return false|int
12
     */
13
    public function execute($method)
14
    {
15
        $file = $method['file'];
16
        $lines = file($file, FILE_IGNORE_NEW_LINES);
17
        $index = $method['line'] - 1;
18
19
        $removeLines = $this->removeLeading($lines, $index - 1);
20
        $removeLines = array_merge($removeLines, $this->removeTrailing($lines, $index));
21
22
        foreach ($removeLines as $removeLine) {
23
            unset($lines[$removeLine]);
24
        }
25
26
        return file_put_contents($file, implode("\n", $lines));
27
    }
28
29
    /**
30
     * @param $lines
31
     * @param $index
32
     * @return array
33
     */
34
    private function removeLeading($lines, $index): array
35
    {
36
        $line = '';
37
        $remove = [];
38
39
        while(! $this->startOfMethod($line)) {
40
            $line = $lines[$index];
41
42
            $remove[] = $index;
43
44
            $index--;
45
        }
46
47
        return $remove;
48
    }
49
50
    /**
51
     * @param $lines
52
     * @param $index
53
     * @return array
54
     */
55
    private function removeTrailing($lines, $index): array
56
    {
57
        $line = '';
58
        $remove = [];
59
60
        while(! $this->endOfMethod($line)) {
61
            $line = $lines[$index];
62
63
            $remove[] = $index;
64
65
            $index++;
66
        }
67
68
        if (trim($lines[$index]) === '') {
69
            $remove[] = $index;
70
        }
71
72
        return $remove;
73
    }
74
75
    /**
76
     * @param $line
77
     * @return bool
78
     */
79
    private function endOfMethod($line): bool
80
    {
81
        return str_replace(' ', '', $line) === '}';
82
    }
83
84
    /**
85
     * @param $line
86
     * @return bool
87
     */
88
    private function startOfMethod($line): bool
89
    {
90
        $line = str_replace(' ', '', $line);
91
92
        return $line === '/**'
93
            || $line === '//'
94
            || $line === '}';
95
    }
96
}
97