1 | <?php |
||
16 | class ResourceStream implements StreamInterface |
||
17 | { |
||
18 | protected $stream; |
||
19 | |||
20 | /** |
||
21 | * ResourceStream constructor. |
||
22 | * |
||
23 | * @param $stream |
||
24 | */ |
||
25 | public function __construct($stream) |
||
26 | { |
||
27 | if (!is_resource($stream)) { |
||
28 | throw new \InvalidArgumentException( |
||
29 | sprintf( |
||
30 | 'Argument must be a valid resource type. %s given.', |
||
31 | gettype($stream) |
||
32 | ) |
||
33 | ); |
||
34 | } |
||
35 | |||
36 | // TODO: Should we verify the resource type? |
||
37 | $this->stream = $stream; |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * @inheritDoc |
||
42 | * |
||
43 | * @throws \RouterOS\Exceptions\StreamException when length parameter is invalid |
||
44 | * @throws \InvalidArgumentException when the stream have been totally read and read method is called again |
||
45 | */ |
||
46 | public function read(int $length): string |
||
47 | { |
||
48 | if ($length <= 0) { |
||
49 | throw new \InvalidArgumentException('Cannot read zero ot negative count of bytes from a stream'); |
||
50 | } |
||
51 | |||
52 | // TODO: Ignore errors here, but why? |
||
53 | $result = @fread($this->stream, $length); |
||
54 | |||
55 | if (false === $result) { |
||
56 | throw new StreamException("Error reading $length bytes"); |
||
57 | } |
||
58 | |||
59 | return $result; |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * @inheritDoc |
||
64 | * |
||
65 | * @throws \RouterOS\Exceptions\StreamException when not possible to write bytes |
||
66 | */ |
||
67 | public function write(string $string, int $length = null): int |
||
68 | { |
||
69 | if (null === $length) { |
||
70 | $length = strlen($string); |
||
71 | } |
||
72 | |||
73 | // TODO: Ignore errors here, but why? |
||
74 | $result = @fwrite($this->stream, $string, $length); |
||
75 | |||
76 | if (false === $result) { |
||
77 | throw new StreamException("Error writing $length bytes"); |
||
78 | } |
||
79 | |||
80 | return $result; |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * @inheritDoc |
||
85 | * |
||
86 | * @throws \RouterOS\Exceptions\StreamException when not possible to close the stream |
||
87 | */ |
||
88 | public function close(): void |
||
101 | } |
||
102 |