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
|
1 |
|
public function __construct(string $prefix = '') |
29
|
|
|
{ |
30
|
1 |
|
parent::__construct(self::createFile($prefix)); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @return resource |
35
|
|
|
* |
36
|
|
|
* @throws RuntimeException |
37
|
|
|
*/ |
38
|
1 |
|
private static function createFile(string $prefix) |
39
|
|
|
{ |
40
|
1 |
|
$dirname = sys_get_temp_dir(); |
41
|
1 |
|
if (!is_writable($dirname)) { |
42
|
|
|
throw new RuntimeException('Temporary files directory is not writable'); |
43
|
|
|
} |
44
|
|
|
|
45
|
1 |
|
$filename = tempnam($dirname, $prefix); |
46
|
1 |
|
if ($filename === false) { |
47
|
|
|
throw new RuntimeException('Temporary file cannot be created'); |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
$resource = fopen($filename, 'r+b'); |
51
|
1 |
|
if (!is_resource($resource)) { |
52
|
|
|
throw new RuntimeException('Temporary file cannot be opened'); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
return $resource; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|