|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Cakasim\Payone\Sdk\Http\Factory; |
|
6
|
|
|
|
|
7
|
|
|
use Cakasim\Payone\Sdk\Http\Message\Stream; |
|
8
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
|
9
|
|
|
use Psr\Http\Message\StreamInterface; |
|
10
|
|
|
use RuntimeException; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Implements the PSR-17 stream factory interface. |
|
14
|
|
|
* |
|
15
|
|
|
* @author Fabian Böttcher <[email protected]> |
|
16
|
|
|
* @since 0.1.0 |
|
17
|
|
|
*/ |
|
18
|
|
|
class StreamFactory implements StreamFactoryInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @inheritDoc |
|
22
|
|
|
*/ |
|
23
|
|
|
public function createStream(string $content = ''): StreamInterface |
|
24
|
|
|
{ |
|
25
|
|
|
// Open PHP temp stream resource. |
|
26
|
|
|
$resource = fopen('php://temp', 'w+'); |
|
27
|
|
|
|
|
28
|
|
|
if (!is_resource($resource)) { |
|
29
|
|
|
throw new RuntimeException('Unable to create temp file stream.'); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
// Write provided content to stream and rewind the pointer. |
|
33
|
|
|
fwrite($resource, $content); |
|
34
|
|
|
rewind($resource); |
|
35
|
|
|
|
|
36
|
|
|
// Create Stream with the resource. |
|
37
|
|
|
return new Stream($resource); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @inheritDoc |
|
42
|
|
|
*/ |
|
43
|
|
|
public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface |
|
44
|
|
|
{ |
|
45
|
|
|
// Register temporary error handler to catch fopen warnings. |
|
46
|
|
|
$err = []; |
|
47
|
|
|
set_error_handler(function (int $code, string $message) use (&$err): bool { |
|
48
|
|
|
$err['code'] = $code; |
|
49
|
|
|
$err['message'] = $message; |
|
50
|
|
|
return true; |
|
51
|
|
|
}); |
|
52
|
|
|
|
|
53
|
|
|
// Open the file and restore the error handler. |
|
54
|
|
|
$resource = fopen($filename, $mode); |
|
55
|
|
|
restore_error_handler(); |
|
56
|
|
|
|
|
57
|
|
|
// Throw if an error occurred while opening the file. |
|
58
|
|
|
if (!empty($err)) { |
|
59
|
|
|
throw new RuntimeException("Unable to open file '{$filename}': [{$err['code']}] {$err['message']}"); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
if (!is_resource($resource)) { |
|
63
|
|
|
throw new RuntimeException("Unable to create resource from file '{$filename}'."); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return new Stream($resource); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @inheritDoc |
|
71
|
|
|
*/ |
|
72
|
|
|
public function createStreamFromResource($resource): StreamInterface |
|
73
|
|
|
{ |
|
74
|
|
|
if (!is_resource($resource)) { |
|
75
|
|
|
throw new RuntimeException("Unable to create stream from existing resource."); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return new Stream($resource); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|