-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathStreamChunks.php
45 lines (38 loc) · 1008 Bytes
/
StreamChunks.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
declare(strict_types=1);
namespace JsonMachine;
use JsonMachine\Exception\InvalidArgumentException;
/**
* @implements \IteratorAggregate<int, string>
*/
class StreamChunks implements \IteratorAggregate
{
/** @var resource */
private $stream;
/** @var int */
private $chunkSize;
/**
* @param resource $stream
* @param int $chunkSize
*
* @throws InvalidArgumentException
*/
public function __construct($stream, $chunkSize = 1024 * 8)
{
if ( ! is_resource($stream) || get_resource_type($stream) !== 'stream') {
throw new InvalidArgumentException('Argument $stream must be a valid stream resource.');
}
$this->stream = $stream;
$this->chunkSize = $chunkSize;
}
/**
* @return \Generator
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
while ('' !== ($chunk = fread($this->stream, $this->chunkSize))) {
yield $chunk;
}
}
}