diff --git a/composer.json b/composer.json index bdfbafb..b6ccff2 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ "php-http/httplug": "^1.0", "php-http/message-factory": "^1.0.2", "php-http/client-common": "^1.0", - "php-http/message": "^1.0", + "php-http/message": "^1.1", "symfony/options-resolver": "^2.6|^3.0" }, "require-dev": { diff --git a/spec/RequestConditionalPluginSpec.php b/spec/RequestConditionalPluginSpec.php new file mode 100644 index 0000000..33aa4c7 --- /dev/null +++ b/spec/RequestConditionalPluginSpec.php @@ -0,0 +1,55 @@ +beConstructedWith($requestMatcher, $plugin); + } + + function it_is_initializable() + { + $this->shouldHaveType('Http\Client\Plugin\RequestConditionalPlugin'); + } + + function it_is_a_plugin() + { + $this->shouldImplement('Http\Client\Plugin\Plugin'); + } + + function it_matches_a_request_and_delegates_to_plugin( + RequestInterface $request, + RequestMatcher $requestMatcher, + Plugin $plugin + ) { + $requestMatcher->matches($request)->willReturn(true); + $plugin->handleRequest($request, Argument::type('callable'), Argument::type('callable'))->shouldBeCalled(); + + $this->handleRequest($request, function () {}, function () {}); + } + + function it_does_not_match_a_request( + RequestInterface $request, + RequestMatcher $requestMatcher, + Plugin $plugin, + Promise $promise + ) { + $requestMatcher->matches($request)->willReturn(false); + $plugin->handleRequest($request, Argument::type('callable'), Argument::type('callable'))->shouldNotBeCalled(); + + $next = function (RequestInterface $request) use($promise) { + return $promise->getWrappedObject(); + }; + + $this->handleRequest($request, $next, function () {})->shouldReturn($promise); + } +} diff --git a/src/RequestConditionalPlugin.php b/src/RequestConditionalPlugin.php new file mode 100644 index 0000000..1599d25 --- /dev/null +++ b/src/RequestConditionalPlugin.php @@ -0,0 +1,46 @@ + + */ +final class RequestConditionalPlugin implements Plugin +{ + /** + * @var RequestMatcher + */ + private $requestMatcher; + + /** + * @var Plugin + */ + private $delegatedPlugin; + + /** + * @param RequestMatcher $requestMatcher + * @param Plugin $delegatedPlugin + */ + public function __construct(RequestMatcher $requestMatcher, Plugin $delegatedPlugin) + { + $this->requestMatcher = $requestMatcher; + $this->delegatedPlugin = $delegatedPlugin; + } + + /** + * {@inheritdoc} + */ + public function handleRequest(RequestInterface $request, callable $next, callable $first) + { + if ($this->requestMatcher->matches($request)) { + return $this->delegatedPlugin->handleRequest($request, $next, $first); + } + + return $next($request); + } +}