Completed
Push — master ( 14d2ba...4131a3 )
by
unknown
03:32
created

TemporaryDirectory::create()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 8
nop 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A TemporaryDirectory::path() 0 11 2
1
<?php
2
3
namespace Spatie\TemporaryDirectory;
4
5
class TemporaryDirectory
6
{
7
    /** @var string The path to the temporary directory */
8
    protected $path;
9
10
    public function __construct(string $path, bool $overwriteExistingDirectory = true)
11
    {
12
        if (empty($path)) {
13
            throw new \InvalidArgumentException('The path argument is missing.');
14
        }
15
16
        $this->path = rtrim($path).DIRECTORY_SEPARATOR;
17
18
        if ($overwriteExistingDirectory && file_exists($this->path())) {
19
            $this->deleteDirectory($this->path);
20
        }
21
22
        if (! file_exists($this->path)) {
23
            mkdir($this->path, 0777, true);
24
        }
25
    }
26
27
    public function path(string $pathOrFilename = ''): string
28
    {
29
        $path = $this->path.trim($pathOrFilename, '/');
30
        $directoryPath = $this->removeFilenameFromPath($path);
31
32
        if (! file_exists($directoryPath)) {
33
            mkdir($directoryPath, 0777, true);
34
        }
35
36
        return $path;
37
    }
38
39
    public function delete()
40
    {
41
        if (! file_exists($this->path)) {
42
            return;
43
        }
44
45
        $this->deleteDirectory($this->path);
46
    }
47
48
    protected function removeFilenameFromPath(string $path): string
49
    {
50
        if (! $this->isFilePath($path)) {
51
            return $path;
52
        }
53
54
        return substr($path, 0, strrpos($path, DIRECTORY_SEPARATOR));
55
    }
56
57
    protected function isFilePath(string $path):bool
58
    {
59
        return strpos($path, '.') !== false;
60
    }
61
62
    protected function deleteDirectory(string $path): bool
63
    {
64
        if (! file_exists($path)) {
65
            return true;
66
        }
67
68
        if (! is_dir($path)) {
69
            return unlink($path);
70
        }
71
72
        foreach (scandir($path) as $item) {
73
            if ($item == '.' || $item == '..') {
74
                continue;
75
            }
76
77
            if (! $this->deleteDirectory($path.DIRECTORY_SEPARATOR.$item)) {
78
                return false;
79
            }
80
        }
81
82
        return rmdir($path);
83
    }
84
}
85