|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the dotfiles project. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) Anthonius Munthi <[email protected]> |
|
9
|
|
|
* |
|
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
11
|
|
|
* file that was distributed with this source code. |
|
12
|
|
|
*/ |
|
13
|
|
|
|
|
14
|
|
|
namespace Dotfiles\Core\Util; |
|
15
|
|
|
|
|
16
|
|
|
use Symfony\Component\Filesystem\Filesystem as BaseFileSystem; |
|
17
|
|
|
|
|
18
|
|
|
class Filesystem extends BaseFileSystem |
|
19
|
|
|
{ |
|
20
|
|
|
public function patch($file, $patch): void |
|
21
|
|
|
{ |
|
22
|
|
|
if (!is_dir($dir = dirname($file))) { |
|
23
|
|
|
mkdir($dir, 0755, true); |
|
24
|
|
|
} |
|
25
|
|
|
if (!is_file($file)) { |
|
26
|
|
|
touch($file); |
|
27
|
|
|
} |
|
28
|
|
|
$prefix = '### > dotfiles-patch ###'; |
|
29
|
|
|
$suffix = '### < dotfiles-patch ###'; |
|
30
|
|
|
$patch = "\n${prefix}\n${patch}\n${suffix}\n"; |
|
31
|
|
|
$regex = '/\\n'.$prefix.'.*'.$suffix.'\\n/is'; |
|
32
|
|
|
|
|
33
|
|
|
$contents = file_get_contents($file); |
|
34
|
|
|
if (preg_match($regex, $contents, $matches)) { |
|
35
|
|
|
$contents = str_replace($matches[0], $patch, $contents); |
|
36
|
|
|
$this->dumpFile($file, $contents); |
|
37
|
|
|
} else { |
|
38
|
|
|
$this->appendToFile($file, $patch); |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Remove directory recursively. |
|
44
|
|
|
* |
|
45
|
|
|
* @param $dir |
|
46
|
|
|
* @param callable|null $onRemoveCallback |
|
47
|
|
|
*/ |
|
48
|
|
|
public function removeDir($dir, ?callable $onRemoveCallback = null): void |
|
49
|
|
|
{ |
|
50
|
|
|
if (is_dir($dir)) { |
|
51
|
|
|
$objects = scandir($dir); |
|
52
|
|
|
foreach ($objects as $object) { |
|
53
|
|
|
if ('.' != $object && '..' != $object) { |
|
54
|
|
|
if ('dir' == filetype($dir.DIRECTORY_SEPARATOR.$object)) { |
|
55
|
|
|
$this->removeDir($dir.DIRECTORY_SEPARATOR.$object, $onRemoveCallback); |
|
56
|
|
|
} else { |
|
57
|
|
|
unlink($pathName = $dir.DIRECTORY_SEPARATOR.$object); |
|
58
|
|
|
if (null !== $onRemoveCallback) { |
|
59
|
|
|
call_user_func($onRemoveCallback, $pathName); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
reset($objects); |
|
65
|
|
|
rmdir($dir); |
|
66
|
|
|
if (null !== $onRemoveCallback) { |
|
67
|
|
|
call_user_func($onRemoveCallback, $dir); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|