Completed
Pull Request — master (#52)
by Thomas Mauro
09:16
created

TempDirectory::getTempBaseDir()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.074

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 22
ccs 10
cts 12
cp 0.8333
rs 8.9197
cc 4
eloc 11
nc 4
nop 0
crap 4.074
1
<?php
2
3
namespace Paraunit\File;
4
5
/**
6
 * Class TempDirectory
7
 * @package Paraunit\File
8
 */
9
class TempDirectory
10
{
11
    /** @var string[] */
12
    private static $tempDirs = array(
13
        '/dev/shm',
14
    );
15
16
    /** @var string */
17
    private $timestamp;
18
19
    /**
20
     * Paraunit constructor.
21
     */
22 40
    public function __construct()
23
    {
24 40
        $this->timestamp = uniqid(date('Ymd-His'));
25 40
    }
26
27
    /**
28
     * @return string
29
     */
30 40
    public function getTempDirForThisExecution()
31
    {
32 40
        $dir = self::getTempBaseDir() . DIRECTORY_SEPARATOR . $this->timestamp;
33 40
        self::mkdirIfNotExists($dir);
34 40
        self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'logs');
35 40
        self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'coverage');
36
37 40
        return $dir;
38
    }
39
40
    /**
41
     * @return string
42
     *
43 40
     * @throws \RuntimeException
44
     */
45 40
    public static function getTempBaseDir()
46 40
    {
47 40
        $dirs = self::$tempDirs;
48 40
        // Fallback to sys temp dir
49
        $dirs[] = sys_get_temp_dir();
50 40
51
        foreach ($dirs as $directory) {
52
            if (file_exists($directory)) {
53
                $baseDir = $directory . DIRECTORY_SEPARATOR . 'paraunit';
54
55
                try {
56
                    self::mkdirIfNotExists($baseDir);
57
58
                    return $baseDir;
59
                } catch (\RuntimeException $e) {
60 40
                    // ignore and try next dir
61
                }
62 40
            }
63 40
        }
64 40
65 40
        throw new \RuntimeException('Unable to create a temporary directory');
66
    }
67
68
    /**
69
     * @param string $path
70
     *
71
     * @throws \RuntimeException
72
     */
73
    private static function mkdirIfNotExists($path)
74
    {
75
        if (file_exists($path)) {
76
            return;
77
        }
78
79
        if (!mkdir($path) && !is_dir($path)) {
80
            throw new \RuntimeException(
81
                sprintf('Unable to create temporary directory \'%s\'.', $path)
82
            );
83
        }
84
    }
85
}
86