Completed
Push — master ( e834bf...05c340 )
by Alessandro
15s
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
3
declare(strict_types=1);
4
5
namespace Paraunit\File;
6
7
use Paraunit\Lifecycle\EngineEvent;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
10
/**
11
 * Class Cleaner
12
 * @package Paraunit\File
13
 */
14
class Cleaner implements EventSubscriberInterface
15
{
16
    /** @var TempDirectory */
17
    private $tempDirectory;
18
19
    /**
20
     * Cleaner constructor.
21
     * @param TempDirectory $tempDirectory
22
     */
23 19
    public function __construct(TempDirectory $tempDirectory)
24
    {
25 19
        $this->tempDirectory = $tempDirectory;
26
    }
27
28 63
    public static function getSubscribedEvents(): array
29
    {
30
        return [
31 63
            EngineEvent::BEFORE_START => 'purgeCurrentTempDir',
32 63
            EngineEvent::END => 'purgeCurrentTempDir',
33
        ];
34
    }
35
36 18
    public function purgeCurrentTempDir()
37
    {
38 18
        self::cleanUpDir($this->tempDirectory->getTempDirForThisExecution());
39
    }
40
41
    /**
42
     * @param string $dir
43
     * @return bool True if the directory existed and it has been deleted
44
     */
45 59
    public static function cleanUpDir(string $dir): bool
46
    {
47 59
        if (! file_exists($dir)) {
48
            return false;
49
        }
50
51 59
        $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
52 59
        $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
53
54 59
        foreach ($files as $file) {
55 59
            if ($file->isDir()) {
56 51
                rmdir($file->getRealPath());
57
            } else {
58 59
                unlink($file->getRealPath());
59
            }
60
        }
61
62 59
        return rmdir($dir);
63
    }
64
}
65