Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 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
 * @inheritDoc
11
 */
12
class NonSeekableStreamDecodingEventStreamIterator extends DecodingEventStreamIterator
13
{
14
    /** @var array $tempBuffer */
15
    private $tempBuffer;
16
 
17
    /**
18
     * NonSeekableStreamDecodingEventStreamIterator constructor.
19
     *
20
     * @param StreamInterface $stream
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
     * @inheritDoc
34
     *
35
     * @return array
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 = $num - 1;
68
        }
69
 
70
        $bytes = $bytes . $this->stream->read($num);
71
        hash_update($this->hashContext, $bytes);
72
 
73
        return $bytes;
74
    }
75
 
76
    // Iterator Functionality
77
 
78
    #[\ReturnTypeWillChange]
79
    public function rewind()
80
    {
81
        $this->currentEvent = $this->parseEvent();
82
    }
83
 
84
    public function next()
85
    {
86
        $this->tempBuffer[] = $this->stream->read(1);
87
        if ($this->valid()) {
88
            $this->key++;
89
            $this->currentEvent = $this->parseEvent();
90
        }
91
    }
92
 
93
    /**
94
     * @return bool
95
     */
96
    #[\ReturnTypeWillChange]
97
    public function valid()
98
    {
99
        return !$this->stream->eof();
100
    }
101
}