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 $line |
16
|
|
|
* @return self |
17
|
|
|
*/ |
18
|
|
|
public function addLineAfterLast(string $search, $line): self |
19
|
|
|
{ |
20
|
|
|
$newline = PHP_EOL; |
21
|
|
|
$regex = "/([ \t]*).*{$search}.*{$newline}(?!.*{$search})/"; |
22
|
|
|
|
23
|
|
|
return $this->addLineAfterRegex($regex, $line); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Add the given line after the provided regular expression |
28
|
|
|
* |
29
|
|
|
* @param string $regex |
30
|
|
|
* @param mixed $line |
31
|
|
|
* @return self |
32
|
|
|
*/ |
33
|
|
|
public function addLineAfterRegex(string $regex, $line): self |
34
|
|
|
{ |
35
|
|
|
return $this->addLineByRegex($regex, $line, function ($line, $matches) { |
36
|
|
|
return $matches[0] . $matches[1] . $line . PHP_EOL; |
37
|
|
|
}); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Add the given line based on the provided regular expression |
42
|
|
|
* |
43
|
|
|
* @param string $regex |
44
|
|
|
* @param mixed $line |
45
|
|
|
* @param callable $callable |
46
|
|
|
* @return self |
47
|
|
|
*/ |
48
|
|
|
public function addLineByRegex(string $regex, $line, callable $callable): self |
49
|
|
|
{ |
50
|
|
|
$callback = function (array $matches) use ($line, $callable) { |
51
|
|
|
$value = is_callable($line) ? $line($matches) : $line; |
52
|
|
|
return $callable($value, $matches); |
53
|
|
|
}; |
54
|
|
|
|
55
|
|
|
$content = preg_replace_callback($regex, $callback, file_get_contents($this->getPath())); |
|
|
|
|
56
|
|
|
|
57
|
|
|
file_put_contents($this->getPath(), $content); |
58
|
|
|
|
59
|
|
|
return $this; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Add the given line after the last occurrence of the provided docblock comment |
64
|
|
|
* |
65
|
|
|
* @param string $search |
66
|
|
|
* @param mixed $line |
67
|
|
|
* @return self |
68
|
|
|
*/ |
69
|
|
|
public function addLineAfterLastDocblockComment(string $search, $line): self |
70
|
|
|
{ |
71
|
|
|
$newline = PHP_EOL; |
72
|
|
|
$regex = "/([ \t\*]*).*{$search}.*{$newline}(?!.*{$search})/"; |
73
|
|
|
|
74
|
|
|
return $this->addLineAfterRegex($regex, $line); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|