StreamFactory::createStreamFromFile()   A
last analyzed

Complexity

Conditions 6
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 6
eloc 5
c 2
b 1
f 0
nc 3
nop 2
dl 0
loc 11
rs 9.2222
1
<?php
2
/**
3
 * Class StreamFactory
4
 *
5
 * @created      27.08.2018
6
 * @author       smiley <[email protected]>
7
 * @copyright    2018 smiley
8
 * @license      MIT
9
 */
10
11
namespace chillerlan\HTTP\Psr17;
12
13
use chillerlan\HTTP\Psr7\Stream;
14
use Psr\Http\Message\{StreamFactoryInterface, StreamInterface};
15
use InvalidArgumentException, RuntimeException;
16
17
use function fopen, in_array, is_file, is_readable;
18
19
class StreamFactory implements StreamFactoryInterface{
20
21
	/**
22
	 * @inheritDoc
23
	 */
24
	public function createStream(string $content = ''):StreamInterface{
25
		$stream = new Stream(fopen('php://temp', 'r+'));
26
27
		if($content !== ''){
28
			$stream->write($content);
29
		}
30
31
		return $stream;
32
	}
33
34
	/**
35
	 * @inheritDoc
36
	 */
37
	public function createStreamFromFile(string $filename, string $mode = 'r'):StreamInterface{
38
39
		if(empty($filename) || !is_file($filename) || !is_readable($filename)){
40
			throw new RuntimeException('invalid file');
41
		}
42
43
		if(!in_array($mode, FactoryHelpers::STREAM_MODES_WRITE) && !in_array($mode, FactoryHelpers::STREAM_MODES_READ)){
44
			throw new InvalidArgumentException('invalid mode');
45
		}
46
47
		return new Stream(fopen($filename, $mode));
48
	}
49
50
	/**
51
	 * @inheritDoc
52
	 */
53
	public function createStreamFromResource($resource):StreamInterface{
54
		return new Stream($resource);
55
	}
56
57
}
58