Completed
Pull Request — master (#9)
by ANTHONIUS
03:17
created

Filesystem::removeDir()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 12
nc 5
nop 2
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
    public function removeDir($dir, callable $onRemoveCallback = null): void
43
    {
44
        if (is_dir($dir)) {
45
            $objects = scandir($dir);
46
            foreach ($objects as $object) {
47
                if ('.' != $object && '..' != $object) {
48
                    if ('dir' == filetype($dir.DIRECTORY_SEPARATOR.$object)) {
49
                        $this->removeDir($dir.DIRECTORY_SEPARATOR.$object, $onRemoveCallback);
50
                    } else {
51
                        unlink($pathName = $dir.DIRECTORY_SEPARATOR.$object);
52
                        call_user_func($onRemoveCallback, $pathName);
53
                    }
54
                }
55
            }
56
            reset($objects);
57
            rmdir($dir);
58
            call_user_func($onRemoveCallback, $dir);
59
        }
60
    }
61
}
62