|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace tests\Http\Client\Common; |
| 6 | + |
| 7 | +use Http\Client\Common\Plugin; |
| 8 | +use Http\Client\Common\Plugin\HeaderAppendPlugin; |
| 9 | +use Http\Client\Common\Plugin\RedirectPlugin; |
| 10 | +use Http\Client\Common\PluginClient; |
| 11 | +use Http\Client\HttpAsyncClient; |
| 12 | +use Http\Client\Promise\HttpFulfilledPromise; |
| 13 | +use Http\Promise\Promise; |
| 14 | +use Nyholm\Psr7\Request; |
| 15 | +use Nyholm\Psr7\Response; |
| 16 | +use PHPUnit\Framework\TestCase; |
| 17 | +use Psr\Http\Client\ClientInterface; |
| 18 | +use Psr\Http\Message\RequestInterface; |
| 19 | +use Psr\Http\Message\ResponseInterface; |
| 20 | + |
| 21 | +class PluginClientTest extends TestCase |
| 22 | +{ |
| 23 | + /** |
| 24 | + * @dataProvider clientAndMethodProvider |
| 25 | + */ |
| 26 | + public function testRestartChain(PluginClient $client, string $method, string $returnType) |
| 27 | + { |
| 28 | + $request = new Request('GET', 'https://example.com'); |
| 29 | + $result = call_user_func([$client, $method], $request); |
| 30 | + |
| 31 | + $this->assertInstanceOf($returnType, $result); |
| 32 | + } |
| 33 | + |
| 34 | + public function clientAndMethodProvider() |
| 35 | + { |
| 36 | + $syncClient = new class() implements ClientInterface { |
| 37 | + public function sendRequest(RequestInterface $request): ResponseInterface |
| 38 | + { |
| 39 | + return new Response(); |
| 40 | + } |
| 41 | + }; |
| 42 | + |
| 43 | + $asyncClient = new class() implements HttpAsyncClient { |
| 44 | + public function sendAsyncRequest(RequestInterface $request) |
| 45 | + { |
| 46 | + return new HttpFulfilledPromise(new Response()); |
| 47 | + } |
| 48 | + }; |
| 49 | + |
| 50 | + $headerAppendPlugin = new HeaderAppendPlugin(['Content-Type' => 'text/html']); |
| 51 | + $redirectPlugin = new RedirectPlugin(); |
| 52 | + $restartOncePlugin = new class() implements Plugin { |
| 53 | + private $firstRun = true; |
| 54 | + |
| 55 | + public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise |
| 56 | + { |
| 57 | + if ($this->firstRun) { |
| 58 | + $this->firstRun = false; |
| 59 | + |
| 60 | + return $first($request); |
| 61 | + } |
| 62 | + $this->firstRun = true; |
| 63 | + |
| 64 | + return $next($request); |
| 65 | + } |
| 66 | + }; |
| 67 | + |
| 68 | + $plugins = [$headerAppendPlugin, $restartOncePlugin, $redirectPlugin]; |
| 69 | + |
| 70 | + $pluginClient = new PluginClient($syncClient, $plugins); |
| 71 | + yield [$pluginClient, 'sendRequest', ResponseInterface::class]; |
| 72 | + yield [$pluginClient, 'sendAsyncRequest', Promise::class]; |
| 73 | + |
| 74 | + // Async |
| 75 | + $pluginClient = new PluginClient($asyncClient, $plugins); |
| 76 | + yield [$pluginClient, 'sendRequest', ResponseInterface::class]; |
| 77 | + yield [$pluginClient, 'sendAsyncRequest', Promise::class]; |
| 78 | + } |
| 79 | +} |
0 commit comments