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

TempDirectory   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 90.91%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 10
c 3
b 0
f 0
lcom 1
cbo 0
dl 0
loc 77
ccs 20
cts 22
cp 0.9091
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getTempDirForThisExecution() 0 9 1
B getTempBaseDir() 0 22 4
A mkdirIfNotExists() 0 12 4
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