Completed
Pull Request — master (#94)
by Alessandro
05:58
created

Cleaner::purgeCurrentTempDir()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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 14
    public function __construct(TempDirectory $tempDirectory)
23
    {
24 14
        $this->tempDirectory = $tempDirectory;
25
    }
26
27 55
    public static function getSubscribedEvents(): array
28
    {
29
        return [
30 55
            EngineEvent::BEFORE_START => 'purgeCurrentTempDir',
31 55
            EngineEvent::END => 'purgeCurrentTempDir',
32
        ];
33
    }
34
35 14
    public function purgeCurrentTempDir()
36
    {
37 14
        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 55
    public static function cleanUpDir(string $dir): bool
45
    {
46 55
        if (! file_exists($dir)) {
47
            return false;
48
        }
49
50 55
        $it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
51 55
        $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST);
52
53 55
        foreach ($files as $file) {
54 55
            if ($file->isDir()) {
55 47
                rmdir($file->getRealPath());
56
            } else {
57 55
                unlink($file->getRealPath());
58
            }
59
        }
60
61 55
        return rmdir($dir);
62
    }
63
}
64