AddsStubs::addStubBeforeRegex()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Cerbero\ConsoleTasker\Traits;
4
5
/**
6
 * The trait to manipulate files by adding new stubs.
7
 *
8
 */
9
trait AddsStubs
10
{
11
    /**
12
     * Add the given stub before the last occurrence of the searched text
13
     *
14
     * @param string $search
15
     * @param string $path
16
     * @param array $replacements
17
     * @return self
18
     */
19
    public function addStubBeforeLast(string $search, string $path, array $replacements = []): self
20
    {
21
        $regex = "/{$search}(?!.*{$search})/s";
22
23
        return $this->addStubBeforeRegex($regex, $path, $replacements);
24
    }
25
26
    /**
27
     * Add the given stub before the provided regular expression
28
     *
29
     * @param string $regex
30
     * @param string $path
31
     * @param array $replacements
32
     * @return self
33
     */
34
    public function addStubBeforeRegex(string $regex, string $path, array $replacements = []): self
35
    {
36
        return $this->addStubByRegex($regex, $path, $replacements, function ($stubContent, $matches) {
37
            return $stubContent . $matches[0];
38
        });
39
    }
40
41
    /**
42
     * Add the given stub based on the provided regular expression
43
     *
44
     * @param string $regex
45
     * @param string $path
46
     * @param array $replacements
47
     * @param callable $callable
48
     * @return self
49
     */
50
    public function addStubByRegex(string $regex, string $path, array $replacements, callable $callable): self
51
    {
52
        $stubContent = str_replace(array_keys($replacements), array_values($replacements), file_get_contents($path));
53
54
        $callback = function (array $matches) use ($callable, $stubContent) {
55
            return $callable($stubContent, $matches);
56
        };
57
58
        $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

58
        $content = preg_replace_callback($regex, $callback, file_get_contents($this->/** @scrutinizer ignore-call */ getPath()));
Loading history...
59
60
        file_put_contents($this->getPath(), $content);
61
62
        return $this;
63
    }
64
}
65