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

TempDirectory   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 75.86%

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 22
cts 29
cp 0.7586
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
     * @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