summaryrefslogtreecommitdiffstats
path: root/library/Icinga/File/Storage/TemporaryLocalFileStorage.php
blob: faf91f55f759ecd1044017d93776c6381104724c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
/* Icinga Web 2 | (c) 2017 Icinga Development Team | GPLv2+ */

namespace Icinga\File\Storage;

use ErrorException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

/**
 * Stores files in a temporary directory
 */
class TemporaryLocalFileStorage extends LocalFileStorage
{
    /**
     * Constructor
     */
    public function __construct()
    {
        $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid();
        mkdir($path, 0700);

        parent::__construct($path);
    }

    /**
     * Destructor
     */
    public function __destruct()
    {
        // Some classes may have cleaned up the tmp file, so we need to check this
        // beforehand to prevent an unexpected crash.
        if (! @realpath($this->baseDir)) {
            return;
        }

        $directoryIterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator(
                $this->baseDir,
                RecursiveDirectoryIterator::CURRENT_AS_FILEINFO
                    | RecursiveDirectoryIterator::KEY_AS_PATHNAME
                    | RecursiveDirectoryIterator::SKIP_DOTS
            ),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($directoryIterator as $path => $entry) {
            /** @var \SplFileInfo $entry */

            if ($entry->isDir() && ! $entry->isLink()) {
                rmdir($path);
            } else {
                unlink($path);
            }
        }

        rmdir($this->baseDir);
    }
}