Skip to content

Commit c3277ed

Browse files
authored
Merge pull request #46 from sunrise-php/release/v3.6.0
v3.6
2 parents 482b97e + 421a0e0 commit c3277ed

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

src/Stream/LineStream.php

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
}

tests/Stream/LineStreamTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Sunrise\Http\Message\Tests\Stream;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use Sunrise\Http\Message\Stream\LineStream;
9+
10+
use function fopen;
11+
use function implode;
12+
13+
use const PHP_EOL;
14+
15+
final class LineStreamTest extends TestCase
16+
{
17+
public function testIterator(): void
18+
{
19+
$stream = new LineStream(fopen('php://memory', 'r+'));
20+
$stream->write(implode(PHP_EOL, ['foo', 'bar', 'baz']));
21+
$stream->rewind();
22+
self::assertSame(['foo', 'bar', 'baz'], [...$stream]);
23+
}
24+
}

0 commit comments

Comments
 (0)