Completed
Push — master ( 1a3a48...6e0e69 )
by Alessandro
09:39 queued 07:07
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 20
    public function __construct(TempDirectory $tempDirectory)
24
    {
25 20
        $this->tempDirectory = $tempDirectory;
26
    }
27
28 64
    public static function getSubscribedEvents(): array
29
    {
30
        return [
31 64
            EngineEvent::BEFORE_START => 'purgeCurrentTempDir',
32 64
            EngineEvent::END => 'purgeCurrentTempDir',
33
        ];
34
    }
35
36 19
    public function purgeCurrentTempDir()
37
    {
38 19
        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 60
    public static function cleanUpDir(string $dir): bool
46
    {
47 60
        if (! file_exists($dir)) {
48
            return false;
49
        }
50
51 60
        $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
52 60
        $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
53
54 60
        foreach ($files as $file) {
55 60
            if ($file->isDir()) {
56 52
                rmdir($file->getRealPath());
57
            } else {
58 60
                unlink($file->getRealPath());
59
            }
60
        }
61
62 60
        return rmdir($dir);
63
    }
64
}
65