Test Failed
Pull Request — master (#34)
by Anatoly
04:34
created

TempFileStream::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
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
use Sunrise\Http\Message\Exception\RuntimeException;
15
use Sunrise\Http\Message\Stream;
16
17
use function fopen;
18
use function is_resource;
19
use function is_writable;
20
use function sys_get_temp_dir;
21
use function tempnam;
22
23
final class TempFileStream extends Stream
24
{
25
    /**
26
     * @throws RuntimeException
27
     */
28
    public function __construct(string $prefix = '')
29
    {
30
        parent::__construct(self::createFile($prefix));
31
    }
32
33
    /**
34
     * @return resource
35
     *
36
     * @throws RuntimeException
37
     */
38
    private static function createFile(string $prefix)
39
    {
40
        $dirname = sys_get_temp_dir();
41
        if (!is_writable($dirname)) {
42 1
            throw new RuntimeException('Temporary files directory is not writable');
43
        }
44 1
45 1
        $filename = tempnam($dirname, $prefix);
46
        if ($filename === false) {
47
            throw new RuntimeException('Temporary file cannot be created');
48
        }
49 1
50 1
        $resource = fopen($filename, 'r+b');
51
        if (!is_resource($resource)) {
52
            throw new RuntimeException('Temporary file cannot be opened');
53
        }
54 1
55 1
        return $resource;
56
    }
57
}
58