|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Junty |
|
4
|
|
|
* |
|
5
|
|
|
* @author Gabriel Jacinto aka. GabrielJMJ <[email protected]> |
|
6
|
|
|
* @license MIT License |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Junty\Stream; |
|
10
|
|
|
|
|
11
|
|
|
use GuzzleHttp\Psr7\Stream as GuzzleStream; |
|
12
|
|
|
use Psr\Http\Message\StreamInterface; |
|
13
|
|
|
|
|
14
|
|
|
class Stream extends GuzzleStream |
|
15
|
|
|
{ |
|
16
|
|
|
private $contents; |
|
17
|
|
|
|
|
18
|
|
|
private $resource; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct($stream, $options = []) |
|
21
|
|
|
{ |
|
22
|
|
|
parent::__construct($stream, $options); |
|
23
|
|
|
|
|
24
|
|
|
$this->resource = $stream; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Returns the stream resource |
|
29
|
|
|
* |
|
30
|
|
|
* @return resource |
|
31
|
|
|
*/ |
|
32
|
|
|
public function getResource() |
|
33
|
|
|
{ |
|
34
|
|
|
return $this->resource; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Sets stream contents |
|
39
|
|
|
* |
|
40
|
|
|
* @param string $contents |
|
41
|
|
|
*/ |
|
42
|
|
|
public function setContents($contents) |
|
43
|
|
|
{ |
|
44
|
|
|
$this->contents = $contents; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Updates the stream contents |
|
49
|
|
|
*/ |
|
50
|
|
|
public function save() |
|
51
|
|
|
{ |
|
52
|
|
|
$stream = new self(fopen($this->getMetaData('uri'), 'w')); |
|
53
|
|
|
$stream->write($this->contents); |
|
54
|
|
|
$stream->close(); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* If the contents is setted, return it |
|
59
|
|
|
* |
|
60
|
|
|
* @return string |
|
61
|
|
|
*/ |
|
62
|
|
|
public function getContents() |
|
63
|
|
|
{ |
|
64
|
|
|
if (null !== $this->contents) { |
|
65
|
|
|
return $this->contents; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return parent::getContents(); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function __toString() |
|
72
|
|
|
{ |
|
73
|
|
|
if (null !== $this->contents) { |
|
74
|
|
|
return $this->contents; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
return parent::__toString(); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* Copies a stream to another |
|
82
|
|
|
* |
|
83
|
|
|
* @param self|resource $stream |
|
84
|
|
|
* |
|
85
|
|
|
* @return integer |
|
86
|
|
|
*/ |
|
87
|
|
|
public function pipe($stream) |
|
88
|
|
|
{ |
|
89
|
|
|
if (!(is_resource($stream) && get_resource_type($stream) === 'stream') && !$stream instanceof StreamInterface) { |
|
90
|
|
|
throw new \Exception('Invalid stream type passed. You must pass an instance of \'Junty\Stream\Stream\' or a PHP stream resouce.'); |
|
91
|
|
|
} |
|
92
|
|
|
|
|
93
|
|
|
$stream = $stream instanceof StreamInterface ? $stream->getResource() : $stream; |
|
94
|
|
|
|
|
95
|
|
|
return stream_copy_to_stream($this->getResource(), $stream); |
|
96
|
|
|
} |
|
97
|
|
|
} |