|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +/** |
| 4 | + * It's free open-source software released under the MIT License. |
| 5 | + * |
| 6 | + * @author Anatoly Nekhay <afenric@gmail.com> |
| 7 | + * @copyright Copyright (c) 2018, Anatoly Nekhay |
| 8 | + * @license https://github.com/sunrise-php/http-message/blob/master/LICENSE |
| 9 | + * @link https://github.com/sunrise-php/http-message |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Sunrise\Http\Message\Stream; |
| 13 | + |
| 14 | +use IteratorAggregate; |
| 15 | +use Sunrise\Http\Message\Exception\InvalidArgumentException; |
| 16 | +use Sunrise\Http\Message\Exception\RuntimeException; |
| 17 | +use Sunrise\Http\Message\Stream; |
| 18 | +use Traversable; |
| 19 | + |
| 20 | +use function fgets; |
| 21 | +use function is_resource; |
| 22 | +use function rtrim; |
| 23 | + |
| 24 | +/** |
| 25 | + * @implements IteratorAggregate<int, string> |
| 26 | + * |
| 27 | + * @since 3.6.0 |
| 28 | + */ |
| 29 | +final class LineStream extends Stream implements IteratorAggregate |
| 30 | +{ |
| 31 | + /** |
| 32 | + * @var mixed |
| 33 | + */ |
| 34 | + private $resource; |
| 35 | + |
| 36 | + /** |
| 37 | + * @param mixed $resource |
| 38 | + * |
| 39 | + * @throws InvalidArgumentException |
| 40 | + */ |
| 41 | + public function __construct($resource, bool $autoClose = true) |
| 42 | + { |
| 43 | + parent::__construct($resource, $autoClose); |
| 44 | + |
| 45 | + $this->resource = $resource; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * @inheritDoc |
| 50 | + */ |
| 51 | + public function getIterator(): Traversable |
| 52 | + { |
| 53 | + if (!is_resource($this->resource)) { |
| 54 | + throw new RuntimeException('Stream has no resource'); |
| 55 | + } |
| 56 | + |
| 57 | + if (!$this->isReadable()) { |
| 58 | + throw new RuntimeException('Stream is not readable'); |
| 59 | + } |
| 60 | + |
| 61 | + while (($line = fgets($this->resource)) !== false) { |
| 62 | + yield rtrim($line); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments