Debian Codegraph @

lib/3rdParty/composer/spomky-labs/cbor-php/src/StringStream.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace CBOR;
6
7 use InvalidArgumentException;
8 use RuntimeException;
9 use function sprintf;
10 use function strlen;
11
12 final class StringStream implements Stream
13 {
14 /**
15 * @var resource
16 */
17 private $resource;
18
19 public function __construct(string $data)
20 {
21 $resource = fopen('php://memory', 'rb+');
22 if ($resource === false) {
23 throw new RuntimeException('Unable to open the memory');
24 }
25 $result = fwrite($resource, $data);
26 if ($result === false) {
27 throw new RuntimeException('Unable to write the memory');
28 }
29 $result = rewind($resource);
30 if ($result === false) {
31 throw new RuntimeException('Unable to rewind the memory');
32 }
33 $this->resource = $resource;
34 }
35
36 public static function create(string $data): self
37 {
38 return new self($data);
39 }
40
41 public function read(int $length): string
42 {
43 if ($length === 0) {
44 return '';
45 }
46
47 $alreadyRead = 0;
48 $data = '';
49 while ($alreadyRead < $length) {
50 $left = $length - $alreadyRead;
51 $sizeToRead = $left < 1024 && $left > 0 ? $left : 1024;
52 $newData = fread($this->resource, $sizeToRead);
53 $alreadyRead += $sizeToRead;
54
55 if ($newData === false) {
56 throw new RuntimeException('Unable to read the memory');
57 }
58 if (strlen($newData) < $sizeToRead) {
59 throw new InvalidArgumentException(sprintf(
60 'Out of range. Expected: %d, read: %d.',
61 $length,
62 strlen($data)
63 ));
64 }
65 $data .= $newData;
66 }
67
68 if (strlen($data) !== $length) {
69 throw new InvalidArgumentException(sprintf(
70 'Out of range. Expected: %d, read: %d.',
71 $length,
72 strlen($data)
73 ));
74 }
75
76 return $data;
77 }
78 }