Completed
Branch master (f77557)
by Terry
03:17 queued 01:36
created

StreamFactory::assertResource()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
rs 10
cc 2
nc 2
nop 1
1
<?php
2
/*
3
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Shieldon\Psr17;
14
15
use Psr\Http\Message\StreamInterface;
16
use Psr\Http\Message\StreamFactoryInterface;
17
use Shieldon\Psr7\Stream;
18
use InvalidArgumentException;
19
use RuntimeException;
20
21
use function fopen;
22
use function fwrite;
23
use function is_resource;
24
use function preg_match;
25
use function rewind;
26
27
/**
28
 * PSR-17 Stream Factory
29
 */
30
class StreamFactory implements StreamFactoryInterface
31
{
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function createStream(string $content = ''): StreamInterface
36
    {
37
        $resource = @fopen('php://temp', 'r+');
38
39
        $this->assertResource($resource);
40
41
        fwrite($resource, $content);
42
        rewind($resource);
43
44
        return $this->createStreamFromResource($resource);
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
51
    {
52
        if ($mode === '' || ! preg_match('/^[rwaxce]{1}[bt]{0,1}[+]{0,1}+$/', $mode)) {
53
            throw new InvalidArgumentException(
54
                sprintf(
55
                    'Invalid file opening mode "%s"',
56
                    $mode
57
                )
58
            );
59
        }
60
61
        $resource = @fopen($filename, $mode);
62
63
        if (! is_resource($resource)) {
64
            throw new RuntimeException(
65
                sprintf(
66
                    'Unable to open file at "%s"',
67
                    $filename
68
                )
69
            );
70
        }
71
72
        return new Stream($resource);
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function createStreamFromResource($resource): StreamInterface
79
    {
80
        if (! is_resource($resource)) {
81
            $resource = @fopen('php://temp', 'r+');
82
        }
83
84
        $this->assertResource($resource);
85
86
        return new Stream($resource);
87
    }
88
89
    /**
90
     * Throw an exception if input is not a valid PHP resource.
91
     *
92
     * @param mixed $resource
93
     *
94
     * @return void
95
     */
96
    protected function assertResource($resource)
97
    {
98
        if (! is_resource($resource)) {
99
            throw new RuntimeException(
100
                'Unable to open "php://temp" resource.'
101
            );
102
        }
103
    }
104
}
105