Completed
Pull Request — master (#53)
by Francesco
06:31
created

TempDirectory::getTempBaseDir()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.5923

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 22
ccs 8
cts 12
cp 0.6667
rs 8.9197
cc 4
eloc 11
nc 4
nop 0
crap 4.5923
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
     * @throws \RuntimeException
44
     */
45 40
    public static function getTempBaseDir()
46
    {
47 40
        $dirs = self::$tempDirs;
48
        // Fallback to sys temp dir
49 40
        $dirs[] = sys_get_temp_dir();
50
51 40
        foreach ($dirs as $directory) {
52 40
            if (file_exists($directory)) {
53 40
                $baseDir = $directory . DIRECTORY_SEPARATOR . 'paraunit';
54
55
                try {
56 40
                    self::mkdirIfNotExists($baseDir);
57
58 40
                    return $baseDir;
59
                } catch (\RuntimeException $e) {
60
                    // ignore and try next dir
61
                }
62
            }
63
        }
64
65
        throw new \RuntimeException('Unable to create a temporary directory');
66
    }
67
68
    /**
69
     * @param string $path
70
     *
71
     * @throws \RuntimeException
72
     */
73 40
    private static function mkdirIfNotExists($path)
74
    {
75 40
        if (file_exists($path)) {
76 40
            return;
77
        }
78
79 40
        if (!mkdir($path) && !is_dir($path)) {
80
            throw new \RuntimeException(
81
                sprintf('Unable to create temporary directory \'%s\'.', $path)
82
            );
83
        }
84 40
    }
85
}
86