Passed
Pull Request — master (#31)
by Anatoly
39:30
created

TempFileStream   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 30
ccs 9
cts 12
cp 0.75
rs 10
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 4
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Nekhay <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Nekhay
8
 * @license https://github.com/sunrise-php/http-message/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-message
10
 */
11
12
namespace Sunrise\Http\Message\Stream;
13
14
/**
15
 * Import classes
16
 */
17
use Sunrise\Http\Message\Exception\RuntimeException;
18
use Sunrise\Http\Message\Stream;
19
20
/**
21
 * Import functions
22
 */
23
use function fopen;
24
use function is_resource;
25
use function is_writable;
26
use function sys_get_temp_dir;
27
use function tempnam;
28
29
/**
30
 * TempFileStream
31
 */
32
final class TempFileStream extends Stream
33
{
34
35
    /**
36
     * Constructor of the class
37
     *
38
     * @param string|null $prefix
39
     *
40
     * @throws RuntimeException
41
     */
42 1
    public function __construct(?string $prefix = null)
43
    {
44 1
        $prefix ??= 'sunrisephp';
45
46 1
        $dirname = sys_get_temp_dir();
47 1
        if (!is_writable($dirname)) {
48
            throw new RuntimeException('Temporary files directory is not writable');
49
        }
50
51 1
        $filename = tempnam($dirname, $prefix);
52 1
        if ($filename === false) {
53
            throw new RuntimeException('Temporary file name cannot be generated');
54
        }
55
56 1
        $resource = fopen($filename, 'w+b');
57 1
        if (!is_resource($resource)) {
58
            throw new RuntimeException('Temporary file cannot be created or opened');
59
        }
60
61 1
        parent::__construct($resource);
62
    }
63
}
64