Completed
Pull Request — master (#52)
by Thomas Mauro
04:28
created

TempDirectory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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