Skip to content

Commit 3534d37

Browse files
committed
Merge branch '2.x' into 3.x
* 2.x: Add stream utility
2 parents 837a05a + f214f24 commit 3534d37

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

src/HttpMessage/Utility/Stream.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
/**
4+
* This file is part of HttpMessage
5+
*
6+
* @package bdk/http-message
7+
* @author Brad Kent <bkfake-github@yahoo.com>
8+
* @license http://opensource.org/licenses/MIT MIT
9+
* @copyright 2014-2024 Brad Kent
10+
* @since x.3.3
11+
*/
12+
13+
namespace bdk\HttpMessage\Utility;
14+
15+
use Exception;
16+
use Psr\Http\Message\StreamInterface;
17+
18+
/**
19+
* Stream Utilities
20+
*
21+
* @psalm-api
22+
*/
23+
class Stream
24+
{
25+
/**
26+
* Get stream contents without affecting pointer
27+
*
28+
* @param StreamInterface $stream StreamInterface
29+
*
30+
* @return string
31+
*/
32+
public static function getContents(StreamInterface $stream)
33+
{
34+
try {
35+
$pos = $stream->tell();
36+
$body = (string) $stream; // __toString() is like getContents(), but without throwing exceptions
37+
$stream->seek($pos);
38+
return $body;
39+
// @codeCoverageIgnoreStart
40+
} catch (Exception $e) {
41+
return '';
42+
// @codeCoverageIgnoreEnd
43+
}
44+
}
45+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace bdk\Test\HttpMessage\Utility;
4+
5+
use bdk\HttpMessage\Stream;
6+
use bdk\HttpMessage\Utility\Stream as StreamUtility;
7+
use PHPUnit\Framework\TestCase;
8+
9+
/**
10+
* @covers bdk\HttpMessage\Utility\Response
11+
*
12+
* @phpcs:disable SlevomatCodingStandard.Arrays.AlphabeticallySortedByKeys.IncorrectKeyOrder
13+
*/
14+
class UtilityTest extends TestCase
15+
{
16+
public function testGetStreamContents()
17+
{
18+
$stream = new Stream('this is a test');
19+
$stream->seek(8);
20+
self::assertSame('this is a test', StreamUtility::getContents($stream));
21+
self::assertSame('a test', $stream->getContents());
22+
}
23+
}

0 commit comments

Comments
 (0)