Skip to content

Add support for PSR17 factories #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Aug 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
.puli/
build/
vendor/
composer.lock
phpspec.yml
phpunit.xml
.phpunit.result.cache
13 changes: 4 additions & 9 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
language: php

sudo: false

cache:
directories:
- $HOME/.composer/cache/files

php:
- 5.5
- 5.6
- 7.0
- 7.1
- hhvm
- 7.2
- 7.3

env:
global:
Expand All @@ -24,14 +21,12 @@ branches:
matrix:
fast_finish: true
include:
- php: 5.5
- php: 7.3
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" COVERAGE=true TEST_COMMAND="composer test-ci"

before_install:
- travis_retry composer self-update

install:
- travis_retry composer update ${COMPOSER_FLAGS} --prefer-source --no-interaction
- composer update ${COMPOSER_FLAGS} --prefer-dist --no-interaction

script:
- $TEST_COMMAND
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Change Log

## UNRELEASED

- Added support for PSR-17 factories.
- Dropped support for PHP < 7.2

## 1.0.0 - 2017-05-21

No changes from 0.2.0.
Expand Down
9 changes: 5 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@
}
],
"require": {
"php": "^5.5 || ^7.0",
"php": "^7.1",
"psr/http-message": "^1.0",
"psr/http-factory": "^1.0",
"php-http/message-factory": "^1.0.2",
"php-http/discovery": "^1.0"
"php-http/discovery": "^1.7"
},
"require-dev": {
"phpunit/phpunit": "^4.8 || ^5.4",
"phpunit/phpunit": "^7.5 || ^8.3",
"php-http/message": "^1.5",
"zendframework/zend-diactoros": "^1.3.5"
"nyholm/psr7": "^1.0"
},
"autoload": {
"psr-4": {
Expand Down
2 changes: 1 addition & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
syntaxCheck="true">
>
<testsuites>
<testsuite name="MultipartStream tests">
<directory suffix="Test.php">./tests</directory>
Expand Down
70 changes: 63 additions & 7 deletions src/MultipartStreamBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

namespace Http\Message\MultipartStream;

use Http\Discovery\Exception\NotFoundException;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\StreamFactoryDiscovery;
use Http\Message\StreamFactory;
use Http\Message\StreamFactory as HttplugStreamFactory;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;

/**
Expand All @@ -16,7 +19,7 @@
class MultipartStreamBuilder
{
/**
* @var StreamFactory
* @var StreamFactory|StreamFactoryInterface
*/
private $streamFactory;

Expand All @@ -36,11 +39,37 @@ class MultipartStreamBuilder
private $data = [];

/**
* @param StreamFactory|null $streamFactory
* @param StreamFactory|StreamFactoryInterface|null $streamFactory
*/
public function __construct(StreamFactory $streamFactory = null)
public function __construct($streamFactory = null)
{
$this->streamFactory = $streamFactory ?: StreamFactoryDiscovery::find();
if ($streamFactory instanceof StreamFactoryInterface || $streamFactory instanceof HttplugStreamFactory) {
$this->streamFactory = $streamFactory;

return;
}

if (null !== $streamFactory) {
throw new \LogicException(sprintf(
'First arguemnt to the constructor of "%s" must be of type "%s", "%s" or null. Got %s',
__CLASS__,
StreamFactoryInterface::class,
HttplugStreamFactory::class,
\is_object($streamFactory) ? \get_class($streamFactory) : \gettype($streamFactory)
));
}

// Try to find a stream factory.
try {
$this->streamFactory = Psr17FactoryDiscovery::findStreamFactory();
} catch (NotFoundException $psr17Exception) {
try {
$this->streamFactory = StreamFactoryDiscovery::find();
} catch (NotFoundException $httplugException) {
// we could not find any factory.
throw $psr17Exception;
}
}
}

/**
Expand All @@ -58,7 +87,7 @@ public function __construct(StreamFactory $streamFactory = null)
*/
public function addResource($name, $resource, array $options = [])
{
$stream = $this->streamFactory->createStream($resource);
$stream = $this->createStream($resource);

// validate options['headers'] exists
if (!isset($options['headers'])) {
Expand Down Expand Up @@ -108,7 +137,7 @@ public function build()
// Append end
$streams .= "--{$this->getBoundary()}--\r\n";

return $this->streamFactory->createStream($streams);
return $this->createStream($streams);
}

/**
Expand Down Expand Up @@ -275,4 +304,31 @@ private function basename($path)

return $filename;
}

/**
* @param string|resource|StreamInterface $resource
*
* @return StreamInterface
*/
private function createStream($resource)
{
if ($resource instanceof StreamInterface) {
return $resource;
}

if ($this->streamFactory instanceof HttplugStreamFactory) {
return $this->streamFactory->createStream($resource);
}

// Assert: We are using a PSR17 stream factory.
if (\is_string($resource)) {
return $this->streamFactory->createStream($resource);
}

if (\is_resource($resource)) {
return $this->streamFactory->createStreamFromResource($resource);
}

throw new \InvalidArgumentException(sprintf('First argument to "%s::createStream()" must be a string, resource or StreamInterface.', __CLASS__));
}
}
3 changes: 2 additions & 1 deletion tests/CustomMimetypeHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
namespace tests\Http\Message\MultipartStream;

use Http\Message\MultipartStream\CustomMimetypeHelper;
use PHPUnit\Framework\TestCase;

class CustomMimetypeHelperTest extends \PHPUnit_Framework_TestCase
class CustomMimetypeHelperTest extends TestCase
{
public function testGetMimetypeFromExtension()
{
Expand Down
53 changes: 46 additions & 7 deletions tests/FunctionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@

namespace tests\Http\Message\MultipartStream;

use Http\Message\MultipartStream\CustomMimetypeHelper;
use Http\Message\MultipartStream\MultipartStreamBuilder;
use Zend\Diactoros\Stream;
use Nyholm\Psr7\Factory\HttplugFactory;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7\Stream;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\StreamInterface;

/**
* @author Tobias Nyholm <[email protected]>
*/
class FunctionTest extends \PHPUnit_Framework_TestCase
class FunctionTest extends TestCase
{
public function testSupportStreams()
{
Expand Down Expand Up @@ -46,7 +51,7 @@ public function testSupportURIResources()
$this->assertTrue(false !== strpos($multipartStream, 'Content-Type: image/png'));

$urlContents = file_get_contents($url);
$this->assertContains($urlContents, $multipartStream);
$this->assertStringContainsString($urlContents, $multipartStream);
}

public function testResourceFilenameIsNotLocaleAware()
Expand Down Expand Up @@ -139,20 +144,54 @@ public function testReset()

$builder->reset();
$multipartStream = (string) $builder->build();
$this->assertNotContains('foobar', $multipartStream, 'Stream should not have any data after reset()');
$this->assertStringNotContainsString('foobar', $multipartStream, 'Stream should not have any data after reset()');
$this->assertNotEquals($boundary, $builder->getBoundary(), 'Stream should have a new boundary after reset()');
$this->assertNotEmpty($builder->getBoundary());
}

public function testThrowsExceptionIfNotStreamCompatible()
{
$builder = new MultipartStreamBuilder();
$this->expectException(\InvalidArgumentException::class);
$builder->addResource('foo', []);
}

public function testThrowsExceptionInConstructor()
{
$this->expectException(\LogicException::class);
new MultipartStreamBuilder(new CustomMimetypeHelper());
}

/**
* @dataProvider getStreamFactories
*/
public function testSupportDifferentFactories($factory)
{
$resource = fopen(__DIR__.'/Resources/httplug.png', 'r');

$builder = new MultipartStreamBuilder($factory);
$builder->addResource('image', $resource);

$multipartStream = (string) $builder->build();
$this->assertTrue(false !== strpos($multipartStream, 'Content-Disposition: form-data; name="image"; filename="httplug.png"'));
$this->assertTrue(false !== strpos($multipartStream, 'Content-Type: image/png'));
}

public function getStreamFactories()
{
yield 'Httplug Stream Factory' => [new HttplugFactory()];
yield 'PSR-17 Stream Factory' => [new Psr17Factory()];
yield 'Null Stream Factory' => [null];
}

/**
* @param string $body
*
* @return Stream
* @return StreamInterface
*/
private function createStream($body)
{
$stream = new Stream('php://memory', 'rw');
$stream->write($body);
$stream = Stream::create($body);
$stream->rewind();

return $stream;
Expand Down