Completed
Pull Request — master (#94)
by Alessandro
04:33
created

Cleaner::cleanUpDir()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 19
ccs 9
cts 10
cp 0.9
rs 9.2
cc 4
eloc 11
nc 4
nop 1
crap 4.016
1
<?php
2
declare(strict_types=1);
3
4
namespace Paraunit\File;
5
6
use Paraunit\Lifecycle\EngineEvent;
7
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8
9
/**
10
 * Class Cleaner
11
 * @package Paraunit\File
12
 */
13
class Cleaner implements EventSubscriberInterface
14
{
15
    /** @var  TempDirectory */
16
    private $tempDirectory;
17
18
    /**
19
     * Cleaner constructor.
20
     * @param TempDirectory $tempDirectory
21
     */
22 15
    public function __construct(TempDirectory $tempDirectory)
23
    {
24 15
        $this->tempDirectory = $tempDirectory;
25
    }
26
27 56
    public static function getSubscribedEvents(): array
28
    {
29
        return [
30 56
            EngineEvent::BEFORE_START => 'purgeCurrentTempDir',
31 56
            EngineEvent::END => 'purgeCurrentTempDir',
32
        ];
33
    }
34
35 15
    public function purgeCurrentTempDir()
36
    {
37 15
        self::cleanUpDir($this->tempDirectory->getTempDirForThisExecution());
38
    }
39
40
    /**
41
     * @param string $dir
42
     * @return bool True if the directory existed and it has been deleted
43
     */
44 56
    public static function cleanUpDir(string $dir): bool
45
    {
46 56
        if (! file_exists($dir)) {
47
            return false;
48
        }
49
50 56
        $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
51 56
        $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
52
53 56
        foreach ($files as $file) {
54 56
            if ($file->isDir()) {
55 48
                rmdir($file->getRealPath());
56
            } else {
57 56
                unlink($file->getRealPath());
58
            }
59
        }
60
61 56
        return rmdir($dir);
62
    }
63
}
64