| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws; |
| 4 |
|
| 5 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Psr7\StreamDecoratorTrait; |
| 6 |
use Dudlewebs\WPMCS\s3\Psr\Http\Message\StreamInterface; |
| 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 |
/** @var HashInterface */ |
| 14 |
private $hash; |
| 15 |
/** @var callable|null */ |
| 16 |
private $callback; |
| 17 |
/** |
| 18 |
* @param StreamInterface $stream Stream that is being read. |
| 19 |
* @param HashInterface $hash Hash used to calculate checksum. |
| 20 |
* @param callable $onComplete Optional function invoked when the |
| 21 |
* hash calculation is completed. |
| 22 |
*/ |
| 23 |
public function __construct(StreamInterface $stream, HashInterface $hash, callable $onComplete = null) |
| 24 |
{ |
| 25 |
$this->stream = $stream; |
| 26 |
$this->hash = $hash; |
| 27 |
$this->callback = $onComplete; |
| 28 |
} |
| 29 |
public function read($length) |
| 30 |
{ |
| 31 |
$data = $this->stream->read($length); |
| 32 |
$this->hash->update($data); |
| 33 |
if ($this->eof()) { |
| 34 |
$result = $this->hash->complete(); |
| 35 |
if ($this->callback) { |
| 36 |
\call_user_func($this->callback, $result); |
| 37 |
} |
| 38 |
} |
| 39 |
return $data; |
| 40 |
} |
| 41 |
public function seek($offset, $whence = \SEEK_SET) |
| 42 |
{ |
| 43 |
if ($offset === 0) { |
| 44 |
$this->hash->reset(); |
| 45 |
return $this->stream->seek($offset); |
| 46 |
} |
| 47 |
// Seeking arbitrarily is not supported. |
| 48 |
return \false; |
| 49 |
} |
| 50 |
} |
| 51 |
|