Passed
Push — master ( 90d55d...0e16d5 )
by Carlos C
03:42 queued 10s
created

TemporaryFile   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Test Coverage

Coverage 97.06%

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 70
ccs 33
cts 34
cp 0.9706
rs 10
c 0
b 0
f 0
wmc 13

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A create() 0 24 5
A getPath() 0 3 1
A remove() 0 5 2
A __toString() 0 3 1
A storeContents() 0 3 1
A retriveContents() 0 3 1
A runAndRemove() 0 6 1
1
<?php
2
namespace CfdiUtils\Utils\Internal;
3
4
/**
5
 * Utility to work with temporary the creation of files.
6
 * Use it instead of \tempnam PHP function
7
 *
8
 * NOTE: Changes on this file will not be considering a BC since this utility class is for internal usage only
9
 *
10
 * @internal
11
 */
12
final class TemporaryFile
13
{
14
    /** @var string */
15
    private $filename;
16
17 54
    private function __construct(string $filename)
18
    {
19 54
        $this->filename = $filename;
20 54
    }
21
22 56
    public static function create(string $directory = ''): self
23
    {
24 56
        if ('' === $directory) {
25 53
            $directory = sys_get_temp_dir();
26 53
            if (in_array($directory, ['', '.'], true)) {
27
                throw new \RuntimeException('System has an invalid default temp dir');
28
            }
29
        }
30
31 56
        $previousErrorLevel = error_reporting(0);
32 56
        $filename = strval(tempnam($directory, ''));
33 56
        error_reporting($previousErrorLevel);
34
35
        // must check realpath since windows can return different paths for same location
36 56
        if (realpath(dirname($filename)) !== realpath($directory)) {
37 2
            unlink($filename);
38 2
            $filename = '';
39
        }
40
41 56
        if ('' === $filename) {
42 2
            throw new \RuntimeException(sprintf('Unable to create a temporary file'));
43
        }
44
45 54
        return new static($filename);
46
    }
47
48 54
    public function getPath(): string
49
    {
50 54
        return $this->filename;
51
    }
52
53 9
    public function retriveContents(): string
54
    {
55 9
        return strval(file_get_contents($this->filename));
56
    }
57
58 12
    public function storeContents(string $contents)
59
    {
60 12
        file_put_contents($this->filename, $contents);
61 12
    }
62
63 54
    public function remove()
64
    {
65 54
        $filename = $this->getPath();
66 54
        if (file_exists($filename)) {
67 54
            unlink($filename);
68
        }
69 54
    }
70
71 14
    public function __toString(): string
72
    {
73 14
        return $this->getPath();
74
    }
75
76 17
    public function runAndRemove(\Closure $fn)
77
    {
78
        try {
79 17
            return $fn();
80
        } finally {
81 17
            $this->remove();
82
        }
83
    }
84
}
85