Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
namespace Aws;
3
 
4
use GuzzleHttp\Psr7\StreamDecoratorTrait;
5
use Psr\Http\Message\StreamInterface;
6
 
7
/**
8
 * Stream decorator that calculates a rolling hash of the stream as it is read.
9
 */
10
class HashingStream implements StreamInterface
11
{
12
    use StreamDecoratorTrait;
13
 
14
    /** @var StreamInterface */
15
    private $stream;
16
 
17
    /** @var HashInterface */
18
    private $hash;
19
 
20
    /** @var callable|null */
21
    private $callback;
22
 
23
    /**
24
     * @param StreamInterface $stream     Stream that is being read.
25
     * @param HashInterface   $hash       Hash used to calculate checksum.
26
     * @param callable        $onComplete Optional function invoked when the
27
     *                                    hash calculation is completed.
28
     */
29
    public function __construct(
30
        StreamInterface $stream,
31
        HashInterface $hash,
1441 ariadna 32
        ?callable $onComplete = null
1 efrain 33
    ) {
34
        $this->stream = $stream;
35
        $this->hash = $hash;
36
        $this->callback = $onComplete;
37
    }
38
 
1441 ariadna 39
    public function read($length): string
1 efrain 40
    {
41
        $data = $this->stream->read($length);
42
        $this->hash->update($data);
43
        if ($this->eof()) {
44
            $result = $this->hash->complete();
45
            if ($this->callback) {
46
                call_user_func($this->callback, $result);
47
            }
48
        }
49
 
50
        return $data;
51
    }
52
 
1441 ariadna 53
    public function seek($offset, $whence = SEEK_SET): void
1 efrain 54
    {
1441 ariadna 55
        // Seeking arbitrarily is not supported.
56
        if ($offset !== 0) {
57
            return;
1 efrain 58
        }
59
 
1441 ariadna 60
        $this->hash->reset();
61
        $this->stream->seek($offset);
1 efrain 62
    }
63
}