| 1 |
<?php |
| 2 |
|
| 3 |
namespace Aws\Api\Parser; |
| 4 |
|
| 5 |
use GuzzleHttp\Psr7; |
| 6 |
use Psr\Http\Message\StreamInterface; |
| 7 |
use Aws\Api\Parser\Exception\ParserException; |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
class NonSeekableStreamDecodingEventStreamIterator extends DecodingEventStreamIterator |
| 13 |
{ |
| 14 |
|
| 15 |
private $tempBuffer; |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
public function __construct(StreamInterface $stream) |
| 23 |
{ |
| 24 |
$this->stream = $stream; |
| 25 |
if ($this->stream->isSeekable()) { |
| 26 |
throw new \InvalidArgumentException('The stream provided must be not seekable.'); |
| 27 |
} |
| 28 |
|
| 29 |
$this->tempBuffer = []; |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
protected function parseEvent(): array |
| 38 |
{ |
| 39 |
$event = []; |
| 40 |
$this->hashContext = hash_init('crc32b'); |
| 41 |
$prelude = $this->parsePrelude()[0]; |
| 42 |
list( |
| 43 |
$event[self::HEADERS], |
| 44 |
$numBytes |
| 45 |
) = $this->parseHeaders($prelude[self::LENGTH_HEADERS]); |
| 46 |
$event[self::PAYLOAD] = Psr7\Utils::streamFor( |
| 47 |
$this->readAndHashBytes( |
| 48 |
$prelude[self::LENGTH_TOTAL] - self::BYTES_PRELUDE |
| 49 |
- $numBytes - self::BYTES_TRAILING |
| 50 |
) |
| 51 |
); |
| 52 |
$calculatedCrc = hash_final($this->hashContext, true); |
| 53 |
$messageCrc = $this->stream->read(4); |
| 54 |
if ($calculatedCrc !== $messageCrc) { |
| 55 |
throw new ParserException('Message checksum mismatch.'); |
| 56 |
} |
| 57 |
|
| 58 |
return $event; |
| 59 |
} |
| 60 |
|
| 61 |
protected function readAndHashBytes($num): string |
| 62 |
{ |
| 63 |
$bytes = ''; |
| 64 |
while (!empty($this->tempBuffer) && $num > 0) { |
| 65 |
$byte = array_shift($this->tempBuffer); |
| 66 |
$bytes .= $byte; |
| 67 |
$num -= 1; |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
while ($num > 0 && !$this->stream->eof()) { |
| 72 |
$chunk = $this->stream->read($num); |
| 73 |
$chunkLen = strlen($chunk); |
| 74 |
$bytes .= $chunk; |
| 75 |
$num -= $chunkLen; |
| 76 |
|
| 77 |
if ($chunkLen === 0) { |
| 78 |
break; |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
hash_update($this->hashContext, $bytes); |
| 83 |
|
| 84 |
return $bytes; |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
#[\ReturnTypeWillChange] |
| 90 |
public function rewind() |
| 91 |
{ |
| 92 |
$this->currentEvent = $this->parseEvent(); |
| 93 |
} |
| 94 |
|
| 95 |
public function next() |
| 96 |
{ |
| 97 |
$this->tempBuffer[] = $this->stream->read(1); |
| 98 |
if ($this->valid()) { |
| 99 |
$this->key++; |
| 100 |
$this->currentEvent = $this->parseEvent(); |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
#[\ReturnTypeWillChange] |
| 108 |
public function valid() |
| 109 |
{ |
| 110 |
return !$this->stream->eof(); |
| 111 |
} |
| 112 |
} |