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 Psr\Http\Message\StreamInterface; |
18
|
|
|
use Sunrise\Http\Message\Exception\RuntimeException; |
19
|
|
|
use Sunrise\Http\Message\Stream; |
20
|
|
|
use Throwable; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Import functions |
24
|
|
|
*/ |
25
|
|
|
use function fopen; |
26
|
|
|
use function is_resource; |
27
|
|
|
use function sprintf; |
28
|
|
|
use function sys_get_temp_dir; |
29
|
|
|
use function tempnam; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* FileStream |
33
|
|
|
*/ |
34
|
|
|
class FileStream extends Stream |
35
|
|
|
{ |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Constructor of the class |
39
|
|
|
* |
40
|
|
|
* @param string $filename |
41
|
|
|
* @param string $mode |
42
|
|
|
* |
43
|
|
|
* @throws RuntimeException |
44
|
|
|
*/ |
45
|
13 |
|
public function __construct(string $filename, string $mode) |
46
|
|
|
{ |
47
|
|
|
try { |
48
|
13 |
|
$resource = fopen($filename, $mode); |
49
|
1 |
|
} catch (Throwable $e) { |
50
|
1 |
|
$resource = false; |
51
|
|
|
} |
52
|
|
|
|
53
|
13 |
|
if (!is_resource($resource)) { |
54
|
1 |
|
throw new RuntimeException(sprintf( |
55
|
1 |
|
'Unable to open the file "%s" in the mode "%s"', |
56
|
1 |
|
$filename, |
57
|
1 |
|
$mode |
58
|
1 |
|
)); |
59
|
|
|
} |
60
|
|
|
|
61
|
12 |
|
parent::__construct($resource); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Creates a new temporary file in the temporary directory |
66
|
|
|
* |
67
|
|
|
* @return StreamInterface |
68
|
|
|
* |
69
|
|
|
* @throws RuntimeException |
70
|
|
|
*/ |
71
|
1 |
|
public static function tempFile(): StreamInterface |
72
|
|
|
{ |
73
|
1 |
|
$filename = tempnam(sys_get_temp_dir(), 'sunrisephp'); |
74
|
|
|
|
75
|
1 |
|
return new self($filename, 'w+b'); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|