CleanDir::emptyDir()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.6186
c 0
b 0
f 0
cc 7
nc 5
nop 1
1
<?php
2
3
namespace Robo\Task\Filesystem;
4
5
use Robo\Common\ResourceExistenceChecker;
6
use Robo\Result;
7
8
/**
9
 * Deletes all files from specified dir, ignoring git files.
10
 *
11
 * ``` php
12
 * <?php
13
 * $this->taskCleanDir(['tmp','logs'])->run();
14
 * // as shortcut
15
 * $this->_cleanDir('app/cache');
16
 * ?>
17
 * ```
18
 */
19
class CleanDir extends BaseDir
20
{
21
    use ResourceExistenceChecker;
22
23
    /**
24
     * {@inheritdoc}
25
     */
26 View Code Duplication
    public function run()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
27
    {
28
        if (!$this->checkResources($this->dirs, 'dir')) {
29
            return Result::error($this, 'Source directories are missing!');
30
        }
31
        foreach ($this->dirs as $dir) {
32
            $this->emptyDir($dir);
33
            $this->printTaskInfo("Cleaned {dir}", ['dir' => $dir]);
34
        }
35
        return Result::success($this);
36
    }
37
38
    /**
39
     * @param string $path
40
     */
41
    protected function emptyDir($path)
42
    {
43
        $iterator = new \RecursiveIteratorIterator(
44
            new \RecursiveDirectoryIterator($path),
45
            \RecursiveIteratorIterator::CHILD_FIRST
46
        );
47
48
        foreach ($iterator as $path) {
49
            if ($path->isDir()) {
50
                $dir = (string)$path;
51
                if (basename($dir) === '.' || basename($dir) === '..') {
52
                    continue;
53
                }
54
                $this->fs->remove($dir);
55
            } else {
56
                $file = (string)$path;
57
                if (basename($file) === '.gitignore' || basename($file) === '.gitkeep') {
58
                    continue;
59
                }
60
                $this->fs->remove($file);
61
            }
62
        }
63
    }
64
}
65