Passed
Push — master ( 32dee0...5d2de3 )
by Andrea Marco
13:08 queued 11s
created

AddsLines::addLineAfterRegex()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 12
ccs 0
cts 7
cp 0
crap 6
rs 10
1
<?php
2
3
namespace Cerbero\ConsoleTasker\Traits;
4
5
/**
6
 * The trait to manipulate files by adding new lines.
7
 *
8
 */
9
trait AddsLines
10
{
11
    /**
12
     * Add the given line after the last occurrence of the searched line
13
     *
14
     * @param string $search
15
     * @param mixed $lineToAdd
16
     * @return self
17
     */
18
    public function addLineAfterLast(string $search, $lineToAdd): self
19
    {
20
        $newline = PHP_EOL;
21
        $regex = "/([ \t]*).*{$search}.*{$newline}(?!.*{$search})/";
22
23
        return $this->addLineAfterRegex($regex, $lineToAdd);
24
    }
25
26
    /**
27
     * Add the given line after the provided regular expression
28
     *
29
     * @param string $regex
30
     * @param mixed $lineToAdd
31
     * @return self
32
     */
33
    public function addLineAfterRegex(string $regex, $lineToAdd): self
34
    {
35
        $callback = function (array $matches) use ($lineToAdd) {
36
            $value = is_callable($lineToAdd) ? $lineToAdd($matches) : $lineToAdd;
37
            return $matches[0] . $matches[1] . $value . PHP_EOL;
38
        };
39
40
        $content = preg_replace_callback($regex, $callback, file_get_contents($this->getPath()));
0 ignored issues
show
Bug introduced by
It seems like getPath() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

40
        $content = preg_replace_callback($regex, $callback, file_get_contents($this->/** @scrutinizer ignore-call */ getPath()));
Loading history...
41
42
        file_put_contents($this->getPath(), $content);
43
44
        return $this;
45
    }
46
47
    /**
48
     * Add the given line after the last occurrence of the provided docblock comment
49
     *
50
     * @param string $search
51
     * @param mixed $lineToAdd
52
     * @return self
53
     */
54
    public function addLineAfterLastDocblockComment(string $search, $lineToAdd): self
55
    {
56
        $newline = PHP_EOL;
57
        $regex = "/([ \t\*]*).*{$search}.*{$newline}(?!.*{$search})/";
58
59
        return $this->addLineAfterRegex($regex, $lineToAdd);
60
    }
61
}
62