Skip to content

Commit

Permalink
Add StreamTransformer
Browse files Browse the repository at this point in the history
  • Loading branch information
rybakit committed Feb 4, 2020
1 parent 249a47a commit efb9bd9
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/TypeTransformer/StreamTransformer.php
@@ -0,0 +1,24 @@
<?php

/**
* This file is part of the rybakit/msgpack.php package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace MessagePack\TypeTransformer;

use MessagePack\Packer;

class StreamTransformer implements CanPack
{
public function pack(Packer $packer, $value) : ?string
{
return \is_resource($value) && 'stream' === \get_resource_type($value)
? $packer->packBin(\stream_get_contents($value))
: null;
}
}
58 changes: 58 additions & 0 deletions tests/Unit/TypeTransformer/StreamTransformerTest.php
@@ -0,0 +1,58 @@
<?php

/**
* This file is part of the rybakit/msgpack.php package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace MessagePack\Tests\Unit\TypeTransformer;

use MessagePack\Packer;
use MessagePack\TypeTransformer\StreamTransformer;
use PHPUnit\Framework\TestCase;

final class StreamTransformerTest extends TestCase
{
public function testPackStream() : void
{
$raw = "\x80";
$packed = "\xc4\x01\x80";

$packer = $this->createMock(Packer::class);
$packer->expects(self::once())->method('packBin')
->with($raw)
->willReturn($packed);

$transformer = new StreamTransformer();

$stream = fopen('php://memory', 'r+');
fwrite($stream, $raw);
rewind($stream);

self::assertSame($packed, $transformer->pack($packer, $stream));
}

public function testPackNonResource() : void
{
$packer = $this->createMock(Packer::class);
$packer->expects(self::never())->method('packBin');

$transformer = new StreamTransformer();

self::assertNull($transformer->pack($packer, 'str'));
}

public function testPackNonStreamResource() : void
{
$packer = $this->createMock(Packer::class);
$packer->expects(self::never())->method('packBin');

$transformer = new StreamTransformer();

self::assertNull($transformer->pack($packer, stream_context_create()));
}
}

0 comments on commit efb9bd9

Please sign in to comment.