From 160e7920eaadb6127657784ce2b1d44ba01a81c5 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Tue, 9 Oct 2018 11:07:32 +0200 Subject: [PATCH 01/10] Update composer.json (#25) --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 2eabc37..1adf616 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "psr/http-server-middleware": "^1.0", "psr/container": "^1.0", "psr/http-message": "^1.0.1", - "zendframework/zend-diactoros": "^1.1.3" + "zendframework/zend-diactoros": "^1.1.3 || ^2.0" }, "require-dev": { "phpunit/phpunit": "^7.1.2", From daa1985872b2ee51711b4da71538ddde3f39cd3f Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Mon, 15 Oct 2018 11:16:15 +0200 Subject: [PATCH 02/10] psr-17 support (#27) * Add psr-17 support, require psr-11 container in factories, change config service key * php 7.3 not existig in travis yet :) * Readme improvements --- README.md | 56 +++++++++++----- composer.json | 6 +- config/dependency.config.php | 7 +- phpunit.xml | 2 +- src/ConfigCollectorFactory.php | 2 +- src/JavascriptRendererFactory.php | 21 ++---- src/PhpDebugBarMiddleware.php | 82 ++++++++++++++++++----- src/PhpDebugBarMiddlewareFactory.php | 15 +++-- src/StandardDebugBarFactory.php | 25 +++---- test/PhpDebugBarMiddlewareFactoryTest.php | 23 ------- test/PhpDebugBarMiddlewareTest.php | 6 +- test/Slim3Test.php | 21 ++++-- test/ZendExpressiveTest.php | 8 +++ 13 files changed, 171 insertions(+), 103 deletions(-) delete mode 100644 test/PhpDebugBarMiddlewareFactoryTest.php diff --git a/README.md b/README.md index 0e4cd82..bb16748 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,24 @@ # phpdebugbar middleware [![Build Status](https://travis-ci.org/php-middleware/phpdebugbar.svg?branch=master)](https://travis-ci.org/php-middleware/phpdebugbar) -PHP Debug bar [PSR-15](https://www.php-fig.org/psr/psr-15/) middleware with [PSR-7](https://www.php-fig.org/psr/psr-7/). Also supports [PSR-11](https://www.php-fig.org/psr/psr-11/) +[PHP Debug Bar](http://phpdebugbar.com/) as framework-agnostic [PSR-15 middleware](https://www.php-fig.org/psr/psr-15/) with [PSR-7 messages](https://www.php-fig.org/psr/psr-7/) created by [PSR-17 message factories](https://www.php-fig.org/psr/psr-17/). Also provides [PSR-11 container invokable factories](https://www.php-fig.org/psr/psr-11/). -This middleware provide framework-agnostic possibility to attach [PHP Debug Bar](http://phpdebugbar.com/) to your response (html on non-html!). +Framework-agnostic way to attach [PHP Debug Bar](http://phpdebugbar.com/) to your response (html or non-html!). ## Installation ``` -composer require php-middleware/php-debug-bar +composer require --dev php-middleware/php-debug-bar ``` -To build this middleware you need to injecting inside `PhpDebugBarMiddleware` instance `DebugBar\JavascriptRenderer` (you can get it from `DebugBar\StandardDebugBar`) and add middleware to your middleware runner. Or use default factory. +To build middleware you need to inject `DebugBar\JavascriptRenderer` (you can get it from `DebugBar\StandardDebugBar`) inside `PhpDebugBarMiddleware` and add it into your middleware runner: ```php $debugbar = new DebugBar\StandardDebugBar(); $debugbarRenderer = $debugbar->getJavascriptRenderer('/phpdebugbar'); -$middleware = new PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware($debugbarRenderer); - -// OR +$middleware = new PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware($debugbarRenderer, $psr17ResponseFactory, $psr17StreamFactory); +// or use provided factory $factory = new PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory(); -$middleware = $factory(); +$middleware = $factory($psr11Container); $app = new MiddlewareRunner(); $app->add($middleware); @@ -30,40 +29,57 @@ You don't need to copy any static assets from phpdebugbar vendor! ### How to force disable or enable PHP Debug Bar? -Sometimes you want to have control when enable (or not) PHP Debug Bar: +Sometimes you want to have control when enable or disable PHP Debug Bar: * custom content negotiation, * allow to debug redirects responses. We allow you to disable attaching phpdebugbar using `X-Enable-Debug-Bar: false` header, cookie or request attribute. To force enable just send request with `X-Enable-Debug-Bar` header, cookie or request attribute with `true` value. +### PSR-17 + +This package isn't require any PSR-7 implementation - you need to provide it by own. Middleware require ResponseFactory and StreamFactory interfaces. [List of existing interfaces](https://packagist.org/providers/psr/http-factory-implementation). + +#### ... and PSR-11 + +If you use provided PSR-11 factories, then you container must have services registered as PSR-17 interface's name. Example for [zend-diactoros](https://github.com/zendframework/zend-diactoros) implementation and [Pimple](https://pimple.symfony.com/): + +```php +$container[Psr\Http\Message\ResponseInterface::class] = new Zend\Diactoros\ResponseFactory(); +$container[Psr\Http\Message\StreamFactoryInterface] = new Zend\Diactoros\StreamFactory(); +``` + ### How to install on Zend Expressive? -You need to register ConfigProvider and pipe provided middleware: +You need to register `PhpMiddleware\PhpDebugBar\ConfigProvider` and pipe provided middleware: ```php -$app->pipe(PhpDebugBarMiddleware::class); +$app->pipe(\PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware::class); ``` -For more follow Zend Expressive [documentation](https://docs.zendframework.com/zend-expressive/v3/features/modular-applications/). +For more - follow Zend Expressive [documentation](https://docs.zendframework.com/zend-expressive/v3/features/modular-applications/). ### How to install on Slim 3? -Add existing factory to container: +Register factories in container: ```php -$container['debugbar_middleware'] = new PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory(); +foreach (ConfigProvider::getConfig()['dependencies']['factories'] as $key => $factory) { + $container[$key] = new $factory(); +} ``` and add middleware from container to app: ```php -$app->add($app->getContainer()->get('debugbar_middleware')); +$app->add( + $app->getContainer()->get(\PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware::class) +); ``` ### How to configure using existing factories? -Put array with configuration into `config` service in your container: +Put array with configuration into `PhpMiddleware\PhpDebugBar\ConfigProvider` service in your container: ```php return [ @@ -81,10 +97,16 @@ return [ ]; ``` +You can override existing configuration by merge default configuration with your own (example): + +```php +return array_merge(PhpMiddleware\PhpDebugBar\ConfigProvider::getConfig(), $myOverritenConfig); +``` + ## It's just works with any modern php framework! Middleware tested on: * [Zend Expressive](https://github.com/zendframework/zend-expressive) * [Slim 3.x](https://github.com/slimphp/Slim) -And any other modern framework [supported middlewares and PSR-7](https://mwop.net/blog/2015-01-08-on-http-middleware-and-psr-7.html). +And any other modern framework [supported PSR-17 middlewares and PSR-7](https://mwop.net/blog/2015-01-08-on-http-middleware-and-psr-7.html). diff --git a/composer.json b/composer.json index 1adf616..23ea4cc 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,8 @@ "psr/http-server-middleware": "^1.0", "psr/container": "^1.0", "psr/http-message": "^1.0.1", - "zendframework/zend-diactoros": "^1.1.3 || ^2.0" + "psr/http-factory": "^1.0", + "psr/http-factory-implementation": "^1.0" }, "require-dev": { "phpunit/phpunit": "^7.1.2", @@ -26,7 +27,8 @@ "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", "zendframework/zend-expressive-fastroute": "^3.0.1", - "zendframework/zend-servicemanager": "^3.3.2" + "zendframework/zend-servicemanager": "^3.3.2", + "zendframework/zend-diactoros": "^2.0" }, "autoload": { "psr-4": { diff --git a/config/dependency.config.php b/config/dependency.config.php index d9f21cf..1680268 100644 --- a/config/dependency.config.php +++ b/config/dependency.config.php @@ -2,7 +2,10 @@ return [ 'factories' => [ - PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware::class => PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory::class, - DebugBar\DataCollector\ConfigCollector::class => PhpMiddleware\PhpDebugBar\ConfigCollectorFactory::class, + \PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware::class => \PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory::class, + \DebugBar\DataCollector\ConfigCollector::class => \PhpMiddleware\PhpDebugBar\ConfigCollectorFactory::class, + \PhpMiddleware\PhpDebugBar\ConfigProvider::class => \PhpMiddleware\PhpDebugBar\ConfigProvider::class, + \DebugBar\DebugBar::class => \PhpMiddleware\PhpDebugBar\StandardDebugBarFactory::class, + \DebugBar\JavascriptRenderer::class => \PhpMiddleware\PhpDebugBar\JavascriptRendererFactory::class, ], ]; diff --git a/phpunit.xml b/phpunit.xml index 0344107..b0c7e5f 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -2,7 +2,7 @@ - + ./test diff --git a/src/ConfigCollectorFactory.php b/src/ConfigCollectorFactory.php index faed230..69e3ffa 100644 --- a/src/ConfigCollectorFactory.php +++ b/src/ConfigCollectorFactory.php @@ -10,7 +10,7 @@ final class ConfigCollectorFactory { public function __invoke(ContainerInterface $container): ConfigCollector { - $data = $container->get('config'); + $data = $container->get(ConfigProvider::class); return new ConfigCollector($data, 'Config'); } diff --git a/src/JavascriptRendererFactory.php b/src/JavascriptRendererFactory.php index 6fa7ec4..c47fef0 100644 --- a/src/JavascriptRendererFactory.php +++ b/src/JavascriptRendererFactory.php @@ -9,26 +9,13 @@ final class JavascriptRendererFactory { - public function __invoke(ContainerInterface $container = null): JavascriptRenderer + public function __invoke(ContainerInterface $container): JavascriptRenderer { - if ($container === null || !$container->has(DebugBar::class)) { - $debugbar = (new StandardDebugBarFactory())($container); - } else { - $debugbar = $container->get(DebugBar::class); - } + $debugbar = $container->get(DebugBar::class); + $config = $container->get(ConfigProvider::class); + $rendererOptions = $config['phpmiddleware']['phpdebugbar']['javascript_renderer']; $renderer = new JavascriptRenderer($debugbar); - - $config = $container !== null && $container->has('config') ? $container->get('config') : []; - - if (isset($config['phpmiddleware']['phpdebugbar']['javascript_renderer'])) { - $rendererOptions = $config['phpmiddleware']['phpdebugbar']['javascript_renderer']; - } else { - $rendererOptions = [ - 'base_url' => '/phpdebugbar', - ]; - } - $renderer->setOptions($rendererOptions); return $renderer; diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index 5331054..55cd28f 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -5,31 +5,34 @@ use DebugBar\JavascriptRenderer as DebugBarRenderer; use Psr\Http\Message\MessageInterface; +use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as ServerRequest; +use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\UriInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; use Slim\Http\Uri as SlimUri; -use Zend\Diactoros\Response as DiactorosResponse; -use Zend\Diactoros\Response\HtmlResponse; -use Zend\Diactoros\Response\Serializer; -use Zend\Diactoros\Stream; /** - * PhpDebugBarMiddleware - * * @author Witold Wasiczko */ final class PhpDebugBarMiddleware implements MiddlewareInterface { public const FORCE_KEY = 'X-Enable-Debug-Bar'; - protected $debugBarRenderer; + private $debugBarRenderer; + private $responseFactory; + private $streamFactory; - public function __construct(DebugBarRenderer $debugbarRenderer) - { + public function __construct( + DebugBarRenderer $debugbarRenderer, + ResponseFactoryInterface $responseFactory, + StreamFactoryInterface $streamFactory + ) { $this->debugBarRenderer = $debugbarRenderer; + $this->responseFactory = $responseFactory; + $this->streamFactory = $streamFactory; } /** @@ -79,16 +82,20 @@ public function handle(ServerRequest $request): Response return $this->process($request, $handler); } - private function prepareHtmlResponseWithDebugBar(Response $response): HtmlResponse + private function prepareHtmlResponseWithDebugBar(Response $response): Response { $head = $this->debugBarRenderer->renderHead(); $body = $this->debugBarRenderer->render(); - $outResponseBody = Serializer::toString($response); + $outResponseBody = $this->serializeResponse($response); $template = '%s

DebugBar

Response:

%s
%s'; $escapedOutResponseBody = htmlspecialchars($outResponseBody); $result = sprintf($template, $head, $escapedOutResponseBody, $body); - return new HtmlResponse($result); + $stream = $this->streamFactory->createStream($result); + + return $this->responseFactory->createResponse(200) + ->withBody($stream) + ->withAddedHeader('Content-type', 'text/html'); } private function attachDebugBarToResponse(Response $response): Response @@ -122,11 +129,11 @@ private function getStaticFile(UriInterface $uri): ?Response } $contentType = $this->getContentTypeByFileName($fullPathToFile); - $stream = new Stream($fullPathToFile, 'r'); + $stream = $this->streamFactory->createStreamFromResource(fopen($fullPathToFile, 'r')); - return new DiactorosResponse($stream, 200, [ - 'Content-type' => $contentType, - ]); + return $this->responseFactory->createResponse(200) + ->withBody($stream) + ->withAddedHeader('Content-type', $contentType); } private function extractPath(UriInterface $uri): string @@ -180,4 +187,47 @@ private function isRedirect(Response $response): bool return ($statusCode >= 300 || $statusCode < 400) && $response->getHeaderLine('Location') !== ''; } + + private function serializeResponse(Response $response) : string + { + $reasonPhrase = $response->getReasonPhrase(); + $headers = $this->serializeHeaders($response->getHeaders()); + $body = (string) $response->getBody(); + $format = 'HTTP/%s %d%s%s%s'; + + if (! empty($headers)) { + $headers = "\r\n" . $headers; + } + + $headers .= "\r\n\r\n"; + + return sprintf( + $format, + $response->getProtocolVersion(), + $response->getStatusCode(), + ($reasonPhrase ? ' ' . $reasonPhrase : ''), + $headers, + $body + ); + } + + private function serializeHeaders(array $headers) : string + { + $lines = []; + foreach ($headers as $header => $values) { + $normalized = $this->filterHeader($header); + foreach ($values as $value) { + $lines[] = sprintf('%s: %s', $normalized, $value); + } + } + + return implode("\r\n", $lines); + } + + private function filterHeader(string $header) : string + { + $filtered = str_replace('-', ' ', $header); + $filtered = ucwords($filtered); + return str_replace(' ', '-', $filtered); + } } diff --git a/src/PhpDebugBarMiddlewareFactory.php b/src/PhpDebugBarMiddlewareFactory.php index 27dfea3..0e0cabc 100644 --- a/src/PhpDebugBarMiddlewareFactory.php +++ b/src/PhpDebugBarMiddlewareFactory.php @@ -5,16 +5,17 @@ use DebugBar\JavascriptRenderer; use Psr\Container\ContainerInterface; +use Psr\Http\Message\ResponseFactoryInterface; +use Psr\Http\Message\StreamFactoryInterface; final class PhpDebugBarMiddlewareFactory { - public function __invoke(ContainerInterface $container = null): PhpDebugBarMiddleware + public function __invoke(ContainerInterface $container): PhpDebugBarMiddleware { - if ($container === null || !$container->has(JavascriptRenderer::class)) { - $renderer = (new JavascriptRendererFactory())($container); - } else { - $renderer = $container->get(JavascriptRenderer::class); - } - return new PhpDebugBarMiddleware($renderer); + $renderer = $container->get(JavascriptRenderer::class); + $responseFactory = $container->get(ResponseFactoryInterface::class); + $streamFactory = $container->get(StreamFactoryInterface::class); + + return new PhpDebugBarMiddleware($renderer, $responseFactory, $streamFactory); } } diff --git a/src/StandardDebugBarFactory.php b/src/StandardDebugBarFactory.php index b21ac63..21f331f 100644 --- a/src/StandardDebugBarFactory.php +++ b/src/StandardDebugBarFactory.php @@ -8,24 +8,25 @@ final class StandardDebugBarFactory { - public function __invoke(ContainerInterface $container = null): StandardDebugBar + public function __invoke(ContainerInterface $container): StandardDebugBar { $debugBar = new StandardDebugBar(); - if ($container !== null) { - $config = $container->has('config') ? $container->get('config') : []; + $config = $container->get(ConfigProvider::class); - $collectors = $config['phpmiddleware']['phpdebugbar']['collectors'] ?: []; + $collectors = $config['phpmiddleware']['phpdebugbar']['collectors']; - foreach ($collectors as $collectorName) { - $collector = $container->get($collectorName); - $debugBar->addCollector($collector); - } + foreach ($collectors as $collectorName) { + $collector = $container->get($collectorName); + $debugBar->addCollector($collector); + } + + $storage = $config['phpmiddleware']['phpdebugbar']['storage']; - if (isset($config['phpmiddleware']['phpdebugbar']['storage']) && is_string($config['phpmiddleware']['phpdebugbar']['storage'])) { - $storage = $container->get($config['phpmiddleware']['phpdebugbar']['storage']); - $debugBar->setStorage($config['phpmiddleware']['phpdebugbar']['storage']); - } + if (is_string($storage)) { + $debugBar->setStorage( + $container->get($storage) + ); } return $debugBar; diff --git a/test/PhpDebugBarMiddlewareFactoryTest.php b/test/PhpDebugBarMiddlewareFactoryTest.php deleted file mode 100644 index 0082589..0000000 --- a/test/PhpDebugBarMiddlewareFactoryTest.php +++ /dev/null @@ -1,23 +0,0 @@ - - */ -class PhpDebugBarMiddlewareFactoryTest extends TestCase -{ - public function testFactory(): void - { - $factory = new PhpDebugBarMiddlewareFactory(); - - $result = $factory(); - - $this->assertInstanceOf(PhpDebugBarMiddleware::class, $result); - } -} diff --git a/test/PhpDebugBarMiddlewareTest.php b/test/PhpDebugBarMiddlewareTest.php index 9f912c7..f4bde3d 100644 --- a/test/PhpDebugBarMiddlewareTest.php +++ b/test/PhpDebugBarMiddlewareTest.php @@ -8,7 +8,9 @@ use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware; use PHPUnit\Framework\TestCase; use Zend\Diactoros\Response; +use Zend\Diactoros\ResponseFactory; use Zend\Diactoros\ServerRequest; +use Zend\Diactoros\StreamFactory; use Zend\Diactoros\Uri; /** @@ -26,8 +28,10 @@ protected function setUp() $this->debugbarRenderer = $this->getMockBuilder(JavascriptRenderer::class)->disableOriginalConstructor()->getMock(); $this->debugbarRenderer->method('renderHead')->willReturn('RenderHead'); $this->debugbarRenderer->method('render')->willReturn('RenderBody'); + $responseFactory = new ResponseFactory(); + $streamFactory = new StreamFactory(); - $this->middleware = new PhpDebugBarMiddleware($this->debugbarRenderer); + $this->middleware = new PhpDebugBarMiddleware($this->debugbarRenderer, $responseFactory, $streamFactory); } public function testTwoPassCallingForCompatibility(): void diff --git a/test/Slim3Test.php b/test/Slim3Test.php index 26959b0..31fea8e 100644 --- a/test/Slim3Test.php +++ b/test/Slim3Test.php @@ -3,22 +3,35 @@ namespace PhpMiddlewareTest\PhpDebugBar; -use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory; +use PhpMiddleware\PhpDebugBar\ConfigProvider; +use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware; +use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\StreamFactoryInterface; use Slim\App; use Slim\Http\Environment; +use Zend\Diactoros\ResponseFactory; +use Zend\Diactoros\StreamFactory; final class Slim3Test extends AbstractMiddlewareRunnerTest { protected function dispatchApplication(array $server, array $pipe = []): ResponseInterface { $app = new App(); - $app->getContainer()['environment'] = function() use ($server) { + $container = $app->getContainer(); + $container[ResponseFactoryInterface::class] = new ResponseFactory(); + $container[StreamFactoryInterface::class] = new StreamFactory(); + $container['environment'] = function() use ($server) { return new Environment($server); }; - $middlewareFactory = new PhpDebugBarMiddlewareFactory(); - $middleware = $middlewareFactory(); + $config = ConfigProvider::getConfig(); + + foreach ($config['dependencies']['factories'] as $key => $factory) { + $container[$key] = new $factory(); + } + + $middleware = $container->get(PhpDebugBarMiddleware::class); $app->add($middleware); diff --git a/test/ZendExpressiveTest.php b/test/ZendExpressiveTest.php index 52bdaea..e5e99bd 100644 --- a/test/ZendExpressiveTest.php +++ b/test/ZendExpressiveTest.php @@ -6,10 +6,14 @@ use PhpMiddleware\PhpDebugBar\ConfigProvider; use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware; use Psr\Container\ContainerInterface; +use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\StreamFactoryInterface; use Zend\Diactoros\Response; +use Zend\Diactoros\ResponseFactory; use Zend\Diactoros\ServerRequestFactory; +use Zend\Diactoros\StreamFactory; use Zend\Expressive\Container\ApplicationFactory; use Zend\Expressive\Container\MiddlewareContainerFactory; use Zend\Expressive\Container\MiddlewareFactoryFactory; @@ -98,8 +102,12 @@ private function createContainer(array $server): ContainerInterface $serviceManagerConfig['factories'][ResponseInterface::class] = ResponseFactoryFactory::class; $serviceManagerConfig['factories'][RouteMiddleware::class] = RouteMiddlewareFactory::class; $serviceManagerConfig['factories'][DispatchMiddleware::class] = DispatchMiddlewareFactory::class; + $serviceManagerConfig['factories'][ResponseFactory::class] = InvokableFactory::class; + $serviceManagerConfig['factories'][StreamFactory::class] = InvokableFactory::class; $serviceManagerConfig['aliases'][RouterInterface::class] = FastRouteRouter::class; $serviceManagerConfig['aliases'][\Zend\Expressive\ApplicationPipeline::class] = MiddlewarePipe::class; + $serviceManagerConfig['aliases'][ResponseFactoryInterface::class] = ResponseFactory::class; + $serviceManagerConfig['aliases'][StreamFactoryInterface::class] = StreamFactory::class; return new ServiceManager($serviceManagerConfig); } From 25cec6e59c20942be2efd4d1ad8baf555eafe7b2 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 2 May 2019 19:32:46 +0200 Subject: [PATCH 03/10] Add php 7.3 support (#29) * Add php 7.3 support * Fix tests --- .travis.yml | 1 + test/PhpDebugBarMiddlewareTest.php | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index f2ad2f7..562bfb7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,7 @@ language: php php: - 7.1 - 7.2 + - 7.3 env: - DEPS=lowest diff --git a/test/PhpDebugBarMiddlewareTest.php b/test/PhpDebugBarMiddlewareTest.php index f4bde3d..3ccac22 100644 --- a/test/PhpDebugBarMiddlewareTest.php +++ b/test/PhpDebugBarMiddlewareTest.php @@ -27,6 +27,7 @@ protected function setUp() { $this->debugbarRenderer = $this->getMockBuilder(JavascriptRenderer::class)->disableOriginalConstructor()->getMock(); $this->debugbarRenderer->method('renderHead')->willReturn('RenderHead'); + $this->debugbarRenderer->method('getBaseUrl')->willReturn('/phpdebugbar'); $this->debugbarRenderer->method('render')->willReturn('RenderBody'); $responseFactory = new ResponseFactory(); $streamFactory = new StreamFactory(); @@ -234,8 +235,6 @@ public function testAppendsToEndOfHtmlResponse(): void public function testTryToHandleNotExistingStaticFile(): void { - $this->debugbarRenderer->expects($this->any())->method('getBaseUrl')->willReturn('/phpdebugbar'); - $uri = new Uri('http://example.com/phpdebugbar/boo.css'); $request = new ServerRequest([], [], $uri, null, 'php://memory'); $response = new Response\HtmlResponse(''); @@ -254,7 +253,6 @@ public function testHandleStaticFile(string $extension, string $contentType): vo { $root = vfsStream::setup('boo'); - $this->debugbarRenderer->expects($this->any())->method('getBaseUrl')->willReturn('/phpdebugbar'); $this->debugbarRenderer->expects($this->any())->method('getBasePath')->willReturn(vfsStream::url('boo')); $uri = new Uri(sprintf('http://example.com/phpdebugbar/debugbar.%s', $extension)); From 3120159051c4f2b39917bb958b3a44c9b6d4e43d Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Mon, 1 Jul 2019 19:17:08 +0200 Subject: [PATCH 04/10] Improve test suite (#30) --- .gitignore | 3 ++- composer.json | 5 +++-- infection.json.dist | 14 ++++++++++++ src/PhpDebugBarMiddleware.php | 35 +++++++++++++++++------------- test/PhpDebugBarMiddlewareTest.php | 34 +++++++++++++++++++++++++---- 5 files changed, 69 insertions(+), 22 deletions(-) create mode 100644 infection.json.dist diff --git a/.gitignore b/.gitignore index 55940e5..04af9af 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /vendor/ -composer.lock \ No newline at end of file +composer.lock +infection.log \ No newline at end of file diff --git a/composer.json b/composer.json index 23ea4cc..c370330 100644 --- a/composer.json +++ b/composer.json @@ -22,13 +22,14 @@ "psr/http-factory-implementation": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^7.1.2", + "phpunit/phpunit": "^7.5.13", "mikey179/vfsStream": "^1.6.4", "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", "zendframework/zend-expressive-fastroute": "^3.0.1", "zendframework/zend-servicemanager": "^3.3.2", - "zendframework/zend-diactoros": "^2.0" + "zendframework/zend-diactoros": "^2.0", + "infection/infection": "^0.13.3" }, "autoload": { "psr-4": { diff --git a/infection.json.dist b/infection.json.dist new file mode 100644 index 0000000..60a2a84 --- /dev/null +++ b/infection.json.dist @@ -0,0 +1,14 @@ +{ + "timeout": 10, + "source": { + "directories": [ + "src" + ] + }, + "logs": { + "text": "infection.log" + }, + "mutators": { + "@default": true + } +} \ No newline at end of file diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index 55cd28f..6bdc2f6 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -46,19 +46,14 @@ public function process(ServerRequest $request, RequestHandler $handler): Respon $response = $handler->handle($request); - $forceHeaderValue = $request->getHeaderLine(self::FORCE_KEY); - $forceCookieValue = $request->getCookieParams()[self::FORCE_KEY] ?? ''; - $forceAttibuteValue = $request->getAttribute(self::FORCE_KEY, ''); - $isForceEnable = in_array('true', [$forceHeaderValue, $forceCookieValue, $forceAttibuteValue], true); - $isForceDisable = in_array('false', [$forceHeaderValue, $forceCookieValue, $forceAttibuteValue], true); - - if ($isForceDisable || (!$isForceEnable && ($this->isRedirect($response) || !$this->isHtmlAccepted($request)))) { + if ($this->shouldReturnResponse($request, $response)) { return $response; } if ($this->isHtmlResponse($response)) { - return $this->attachDebugBarToResponse($response); + return $this->attachDebugBarToHtmlResponse($response); } + return $this->prepareHtmlResponseWithDebugBar($response); } @@ -82,6 +77,17 @@ public function handle(ServerRequest $request): Response return $this->process($request, $handler); } + private function shouldReturnResponse(ServerRequest $request, Response $response): bool + { + $forceHeaderValue = $request->getHeaderLine(self::FORCE_KEY); + $forceCookieValue = $request->getCookieParams()[self::FORCE_KEY] ?? ''; + $forceAttibuteValue = $request->getAttribute(self::FORCE_KEY, ''); + $isForceEnable = in_array('true', [$forceHeaderValue, $forceCookieValue, $forceAttibuteValue], true); + $isForceDisable = in_array('false', [$forceHeaderValue, $forceCookieValue, $forceAttibuteValue], true); + + return $isForceDisable || (!$isForceEnable && ($this->isRedirect($response) || !$this->isHtmlAccepted($request))); + } + private function prepareHtmlResponseWithDebugBar(Response $response): Response { $head = $this->debugBarRenderer->renderHead(); @@ -93,12 +99,12 @@ private function prepareHtmlResponseWithDebugBar(Response $response): Response $stream = $this->streamFactory->createStream($result); - return $this->responseFactory->createResponse(200) + return $this->responseFactory->createResponse() ->withBody($stream) ->withAddedHeader('Content-type', 'text/html'); } - private function attachDebugBarToResponse(Response $response): Response + private function attachDebugBarToHtmlResponse(Response $response): Response { $head = $this->debugBarRenderer->renderHead(); $body = $this->debugBarRenderer->render(); @@ -129,9 +135,9 @@ private function getStaticFile(UriInterface $uri): ?Response } $contentType = $this->getContentTypeByFileName($fullPathToFile); - $stream = $this->streamFactory->createStreamFromResource(fopen($fullPathToFile, 'r')); + $stream = $this->streamFactory->createStreamFromResource(fopen($fullPathToFile, 'rb')); - return $this->responseFactory->createResponse(200) + return $this->responseFactory->createResponse() ->withBody($stream) ->withAddedHeader('Content-type', $contentType); } @@ -185,14 +191,13 @@ private function isRedirect(Response $response): bool { $statusCode = $response->getStatusCode(); - return ($statusCode >= 300 || $statusCode < 400) && $response->getHeaderLine('Location') !== ''; + return $statusCode >= 300 && $statusCode < 400 && $response->getHeaderLine('Location') !== ''; } private function serializeResponse(Response $response) : string { $reasonPhrase = $response->getReasonPhrase(); $headers = $this->serializeHeaders($response->getHeaders()); - $body = (string) $response->getBody(); $format = 'HTTP/%s %d%s%s%s'; if (! empty($headers)) { @@ -207,7 +212,7 @@ private function serializeResponse(Response $response) : string $response->getStatusCode(), ($reasonPhrase ? ' ' . $reasonPhrase : ''), $headers, - $body + $response->getBody() ); } diff --git a/test/PhpDebugBarMiddlewareTest.php b/test/PhpDebugBarMiddlewareTest.php index 3ccac22..62f3297 100644 --- a/test/PhpDebugBarMiddlewareTest.php +++ b/test/PhpDebugBarMiddlewareTest.php @@ -21,6 +21,7 @@ class PhpDebugBarMiddlewareTest extends TestCase { protected $debugbarRenderer; + /** @var PhpDebugBarMiddleware */ protected $middleware; protected function setUp() @@ -76,6 +77,7 @@ public function testForceAttachDebugbarIfHeaderPresents(): void $result = $this->middleware->process($request, $requestHandler); + $this->assertSame(200, $result->getStatusCode()); $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 200 OK\r\n\r\nResponseBody
RenderBody", (string) $result->getBody()); } @@ -108,7 +110,7 @@ public function testForceAttachDebugbarIfAttributePresents(): void public function testAttachToNoneHtmlResponse(): void { $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); - $response = new Response(); + $response = (new Response())->withHeader('test-header', 'value'); $response->getBody()->write('ResponseBody'); $requestHandler = new RequestHandlerStub($response); @@ -117,22 +119,45 @@ public function testAttachToNoneHtmlResponse(): void $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); $this->assertNotSame($response, $result); - $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 200 OK\r\n\r\nResponseBody
RenderBody", (string) $result->getBody()); + $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 200 OK\r\nTest-Header: value\r\n\r\nResponseBody
RenderBody", (string) $result->getBody()); } public function testNotAttachToRedirectResponse(): void { $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); - $response = (new Response())->withStatus(302)->withAddedHeader('Location', 'some-location'); + $response = (new Response())->withStatus(300)->withAddedHeader('Location', 'some-location'); $requestHandler = new RequestHandlerStub($response); $result = $this->middleware->process($request, $requestHandler); - $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); $this->assertSame($response, $result); } + public function testAttachToNonRedirectResponse(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); + $response = (new Response())->withStatus(299)->withAddedHeader('Location', 'some-location'); + + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertNotSame($response, $result); + } + + public function testAttachToNonRedirectResponse2(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); + $response = (new Response())->withStatus(400)->withAddedHeader('Location', 'some-location'); + + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertNotSame($response, $result); + } + public function testAttachToRedirectResponseWithoutLocation(): void { $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); @@ -268,6 +293,7 @@ public function testHandleStaticFile(string $extension, string $contentType): vo $this->assertFalse($requestHandler->isCalled(), 'Request handler is called'); $this->assertNotSame($response, $result); $this->assertSame($contentType, $result->getHeaderLine('Content-type')); + $this->assertSame(200, $result->getStatusCode()); $this->assertSame('filecontent', (string) $result->getBody()); } From 13f77ce6e7cea88899013fc917afafed90802edc Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Sat, 8 Feb 2020 21:12:15 +0100 Subject: [PATCH 05/10] Add php 7.4 support --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 562bfb7..ef58a4d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,6 +8,7 @@ php: - 7.1 - 7.2 - 7.3 + - 7.4 env: - DEPS=lowest From 1820edfd2fbcc7c1fac50b30e542c2f04fd4c01c Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Sat, 8 Feb 2020 22:51:21 +0100 Subject: [PATCH 06/10] Update phpunit --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c370330..c6cab50 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "psr/http-factory-implementation": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^7.5.13", + "phpunit/phpunit": "^7.5.20", "mikey179/vfsStream": "^1.6.4", "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", From 9aaf39c95dd2b3593a5e70aba3247d3e00193d57 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Sat, 8 Feb 2020 22:55:56 +0100 Subject: [PATCH 07/10] Update mikey179/vfsStream --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c6cab50..b6c323c 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,7 @@ }, "require-dev": { "phpunit/phpunit": "^7.5.20", - "mikey179/vfsStream": "^1.6.4", + "mikey179/vfsStream": "^1.6.8", "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", "zendframework/zend-expressive-fastroute": "^3.0.1", From fa7fa054f7539f1d598426afb42242e3aa6e56c9 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Tue, 12 May 2020 20:17:01 +0200 Subject: [PATCH 08/10] Migrate to mezzio, drop php 7.1 support (#34) --- .gitignore | 3 +- .travis.yml | 1 - README.md | 16 ++--- composer.json | 12 ++-- ... => mezzio.middleware_pipeline.config.php} | 0 src/ConfigProvider.php | 2 +- test/AbstractMiddlewareRunnerTest.php | 10 +-- ...{ZendExpressiveTest.php => MezzioTest.php} | 62 +++++++++---------- test/PhpDebugBarMiddlewareTest.php | 12 ++-- test/Slim3Test.php | 4 +- test/TestEmitter.php | 2 +- 11 files changed, 62 insertions(+), 62 deletions(-) rename config/{zend-expressive.middleware_pipeline.config.php => mezzio.middleware_pipeline.config.php} (100%) rename test/{ZendExpressiveTest.php => MezzioTest.php} (69%) diff --git a/.gitignore b/.gitignore index 04af9af..a0f22fe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /vendor/ composer.lock -infection.log \ No newline at end of file +infection.log +.phpunit.result.cache diff --git a/.travis.yml b/.travis.yml index ef58a4d..7121b52 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,6 @@ cache: language: php php: - - 7.1 - 7.2 - 7.3 - 7.4 diff --git a/README.md b/README.md index bb16748..cf9b6ff 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ You don't need to copy any static assets from phpdebugbar vendor! Sometimes you want to have control when enable or disable PHP Debug Bar: * custom content negotiation, -* allow to debug redirects responses. +* allow debug redirects responses. We allow you to disable attaching phpdebugbar using `X-Enable-Debug-Bar: false` header, cookie or request attribute. To force enable just send request with `X-Enable-Debug-Bar` header, cookie or request attribute with `true` value. @@ -42,14 +42,14 @@ This package isn't require any PSR-7 implementation - you need to provide it by #### ... and PSR-11 -If you use provided PSR-11 factories, then you container must have services registered as PSR-17 interface's name. Example for [zend-diactoros](https://github.com/zendframework/zend-diactoros) implementation and [Pimple](https://pimple.symfony.com/): +If you use provided PSR-11 factories, then your container must have services registered as PSR-17 interface's name. Example for [laminas-diactoros](https://github.com/laminas/laminas-diactoros) implementation and [Pimple](https://pimple.symfony.com/): ```php -$container[Psr\Http\Message\ResponseInterface::class] = new Zend\Diactoros\ResponseFactory(); -$container[Psr\Http\Message\StreamFactoryInterface] = new Zend\Diactoros\StreamFactory(); +$container[Psr\Http\Message\ResponseInterface::class] = new Laminas\Diactoros\ResponseFactory(); +$container[Psr\Http\Message\StreamFactoryInterface::class] = new Laminas\Diactoros\StreamFactory(); ``` -### How to install on Zend Expressive? +### How to install on Mezzio? You need to register `PhpMiddleware\PhpDebugBar\ConfigProvider` and pipe provided middleware: @@ -57,7 +57,7 @@ You need to register `PhpMiddleware\PhpDebugBar\ConfigProvider` and pipe provide $app->pipe(\PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware::class); ``` -For more - follow Zend Expressive [documentation](https://docs.zendframework.com/zend-expressive/v3/features/modular-applications/). +For more - follow Mezzio [documentation](https://docs.mezzio.dev/mezzio/v3/features/modular-applications/). ### How to install on Slim 3? @@ -79,7 +79,7 @@ $app->add( ### How to configure using existing factories? -Put array with configuration into `PhpMiddleware\PhpDebugBar\ConfigProvider` service in your container: +Put array with a configuration into `PhpMiddleware\PhpDebugBar\ConfigProvider` service in your container: ```php return [ @@ -106,7 +106,7 @@ return array_merge(PhpMiddleware\PhpDebugBar\ConfigProvider::getConfig(), $myOve ## It's just works with any modern php framework! Middleware tested on: -* [Zend Expressive](https://github.com/zendframework/zend-expressive) +* [Mezzio](https://github.com/mezzio/mezzio) * [Slim 3.x](https://github.com/slimphp/Slim) And any other modern framework [supported PSR-17 middlewares and PSR-7](https://mwop.net/blog/2015-01-08-on-http-middleware-and-psr-7.html). diff --git a/composer.json b/composer.json index b6c323c..f2807e1 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ "psr-11" ], "require": { - "php": "^7.1", + "php": "^7.2", "maximebf/debugbar": "^1.4", "psr/http-server-handler": "^1.0", "psr/http-server-middleware": "^1.0", @@ -22,13 +22,13 @@ "psr/http-factory-implementation": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^7.5.20", + "phpunit/phpunit": "^8.5.4 || ^9.1.4", "mikey179/vfsStream": "^1.6.8", "slim/slim": "^3.0", - "zendframework/zend-expressive": "^3.0", - "zendframework/zend-expressive-fastroute": "^3.0.1", - "zendframework/zend-servicemanager": "^3.3.2", - "zendframework/zend-diactoros": "^2.0", + "mezzio/mezzio": "^3.0", + "mezzio/mezzio-fastroute": "^3.0.1", + "laminas/laminas-servicemanager": "^3.3.2", + "laminas/laminas-diactoros": "^2.0", "infection/infection": "^0.13.3" }, "autoload": { diff --git a/config/zend-expressive.middleware_pipeline.config.php b/config/mezzio.middleware_pipeline.config.php similarity index 100% rename from config/zend-expressive.middleware_pipeline.config.php rename to config/mezzio.middleware_pipeline.config.php diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index fd20daa..6204d59 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -14,7 +14,7 @@ public function __invoke(): array { $config = include __DIR__ . '/../config/phpdebugbar.config.php'; $config['dependencies'] = include __DIR__ . '/../config/dependency.config.php'; - $config['middleware_pipeline'] = include __DIR__ . '/../config/zend-expressive.middleware_pipeline.config.php'; + $config['middleware_pipeline'] = include __DIR__ . '/../config/mezzio.middleware_pipeline.config.php'; return $config; } diff --git a/test/AbstractMiddlewareRunnerTest.php b/test/AbstractMiddlewareRunnerTest.php index 1b505f8..a7dd572 100644 --- a/test/AbstractMiddlewareRunnerTest.php +++ b/test/AbstractMiddlewareRunnerTest.php @@ -6,7 +6,7 @@ use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; -use Zend\Diactoros\Response; +use Laminas\Diactoros\Response; abstract class AbstractMiddlewareRunnerTest extends TestCase { @@ -27,9 +27,9 @@ final public function testAppendJsIntoHtmlContent(): void $responseBody = (string) $response->getBody(); - $this->assertContains('var phpdebugbar = new PhpDebugBar.DebugBar();', $responseBody); - $this->assertContains('Hello!', $responseBody); - $this->assertContains('"/phpdebugbar/debugbar.js"', $responseBody); + $this->assertStringContainsString('var phpdebugbar = new PhpDebugBar.DebugBar();', $responseBody); + $this->assertStringContainsString('Hello!', $responseBody); + $this->assertStringContainsString('"/phpdebugbar/debugbar.js"', $responseBody); } final public function testGetStatics(): void @@ -53,7 +53,7 @@ final public function testGetStatics(): void $contentType = $response->getHeaderLine('Content-type'); - $this->assertContains('text/javascript', $contentType); + $this->assertStringContainsString('text/javascript', $contentType); } abstract protected function dispatchApplication(array $server, array $pipe = []): ResponseInterface; diff --git a/test/ZendExpressiveTest.php b/test/MezzioTest.php similarity index 69% rename from test/ZendExpressiveTest.php rename to test/MezzioTest.php index e5e99bd..f3e340d 100644 --- a/test/ZendExpressiveTest.php +++ b/test/MezzioTest.php @@ -10,35 +10,35 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamFactoryInterface; -use Zend\Diactoros\Response; -use Zend\Diactoros\ResponseFactory; -use Zend\Diactoros\ServerRequestFactory; -use Zend\Diactoros\StreamFactory; -use Zend\Expressive\Container\ApplicationFactory; -use Zend\Expressive\Container\MiddlewareContainerFactory; -use Zend\Expressive\Container\MiddlewareFactoryFactory; -use Zend\Expressive\Container\RequestHandlerRunnerFactory; -use Zend\Expressive\Container\ResponseFactoryFactory; -use Zend\Expressive\Container\ServerRequestErrorResponseGeneratorFactory; -use Zend\Expressive\MiddlewareContainer; -use Zend\Expressive\MiddlewareFactory; -use Zend\Expressive\Response\ServerRequestErrorResponseGenerator; -use Zend\Expressive\Router\FastRouteRouter; -use Zend\Expressive\Router\FastRouteRouterFactory; -use Zend\Expressive\Router\Middleware\DispatchMiddleware; -use Zend\Expressive\Router\Middleware\DispatchMiddlewareFactory; -use Zend\Expressive\Router\Middleware\RouteMiddleware; -use Zend\Expressive\Router\Middleware\RouteMiddlewareFactory; -use Zend\Expressive\Router\RouteCollector; -use Zend\Expressive\Router\RouteCollectorFactory; -use Zend\Expressive\Router\RouterInterface; -use Zend\HttpHandlerRunner\Emitter\EmitterInterface; -use Zend\HttpHandlerRunner\RequestHandlerRunner; -use Zend\ServiceManager\Factory\InvokableFactory; -use Zend\ServiceManager\ServiceManager; -use Zend\Stratigility\MiddlewarePipe; - -final class ZendExpressiveTest extends AbstractMiddlewareRunnerTest +use Laminas\Diactoros\Response; +use Laminas\Diactoros\ResponseFactory; +use Laminas\Diactoros\ServerRequestFactory; +use Laminas\Diactoros\StreamFactory; +use Mezzio\Container\ApplicationFactory; +use Mezzio\Container\MiddlewareContainerFactory; +use Mezzio\Container\MiddlewareFactoryFactory; +use Mezzio\Container\RequestHandlerRunnerFactory; +use Mezzio\Container\ResponseFactoryFactory; +use Mezzio\Container\ServerRequestErrorResponseGeneratorFactory; +use Mezzio\MiddlewareContainer; +use Mezzio\MiddlewareFactory; +use Mezzio\Response\ServerRequestErrorResponseGenerator; +use Mezzio\Router\FastRouteRouter; +use Mezzio\Router\FastRouteRouterFactory; +use Mezzio\Router\Middleware\DispatchMiddleware; +use Mezzio\Router\Middleware\DispatchMiddlewareFactory; +use Mezzio\Router\Middleware\RouteMiddleware; +use Mezzio\Router\Middleware\RouteMiddlewareFactory; +use Mezzio\Router\RouteCollector; +use Mezzio\Router\RouteCollectorFactory; +use Mezzio\Router\RouterInterface; +use Laminas\HttpHandlerRunner\Emitter\EmitterInterface; +use Laminas\HttpHandlerRunner\RequestHandlerRunner; +use Laminas\ServiceManager\Factory\InvokableFactory; +use Laminas\ServiceManager\ServiceManager; +use Laminas\Stratigility\MiddlewarePipe; + +final class MezzioTest extends AbstractMiddlewareRunnerTest { final public function testContainsConfigCollectorOutput(): void { @@ -56,7 +56,7 @@ final public function testContainsConfigCollectorOutput(): void $responseBody = (string) $response->getBody(); - $this->assertContains('DebugBar\\\DataCollector\\\ConfigCollector', $responseBody); + $this->assertStringContainsString('DebugBar\\\DataCollector\\\ConfigCollector', $responseBody); } protected function dispatchApplication(array $server, array $pipe = []): ResponseInterface @@ -105,7 +105,7 @@ private function createContainer(array $server): ContainerInterface $serviceManagerConfig['factories'][ResponseFactory::class] = InvokableFactory::class; $serviceManagerConfig['factories'][StreamFactory::class] = InvokableFactory::class; $serviceManagerConfig['aliases'][RouterInterface::class] = FastRouteRouter::class; - $serviceManagerConfig['aliases'][\Zend\Expressive\ApplicationPipeline::class] = MiddlewarePipe::class; + $serviceManagerConfig['aliases'][\Mezzio\ApplicationPipeline::class] = MiddlewarePipe::class; $serviceManagerConfig['aliases'][ResponseFactoryInterface::class] = ResponseFactory::class; $serviceManagerConfig['aliases'][StreamFactoryInterface::class] = StreamFactory::class; diff --git a/test/PhpDebugBarMiddlewareTest.php b/test/PhpDebugBarMiddlewareTest.php index 62f3297..423b195 100644 --- a/test/PhpDebugBarMiddlewareTest.php +++ b/test/PhpDebugBarMiddlewareTest.php @@ -7,11 +7,11 @@ use org\bovigo\vfs\vfsStream; use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware; use PHPUnit\Framework\TestCase; -use Zend\Diactoros\Response; -use Zend\Diactoros\ResponseFactory; -use Zend\Diactoros\ServerRequest; -use Zend\Diactoros\StreamFactory; -use Zend\Diactoros\Uri; +use Laminas\Diactoros\Response; +use Laminas\Diactoros\ResponseFactory; +use Laminas\Diactoros\ServerRequest; +use Laminas\Diactoros\StreamFactory; +use Laminas\Diactoros\Uri; /** * PhpDebugBarMiddlewareTest @@ -24,7 +24,7 @@ class PhpDebugBarMiddlewareTest extends TestCase /** @var PhpDebugBarMiddleware */ protected $middleware; - protected function setUp() + protected function setUp(): void { $this->debugbarRenderer = $this->getMockBuilder(JavascriptRenderer::class)->disableOriginalConstructor()->getMock(); $this->debugbarRenderer->method('renderHead')->willReturn('RenderHead'); diff --git a/test/Slim3Test.php b/test/Slim3Test.php index 31fea8e..9a7cefd 100644 --- a/test/Slim3Test.php +++ b/test/Slim3Test.php @@ -10,8 +10,8 @@ use Psr\Http\Message\StreamFactoryInterface; use Slim\App; use Slim\Http\Environment; -use Zend\Diactoros\ResponseFactory; -use Zend\Diactoros\StreamFactory; +use Laminas\Diactoros\ResponseFactory; +use Laminas\Diactoros\StreamFactory; final class Slim3Test extends AbstractMiddlewareRunnerTest { diff --git a/test/TestEmitter.php b/test/TestEmitter.php index 7fe122a..fae807b 100644 --- a/test/TestEmitter.php +++ b/test/TestEmitter.php @@ -5,7 +5,7 @@ use BadMethodCallException; use Psr\Http\Message\ResponseInterface; -use Zend\HttpHandlerRunner\Emitter\EmitterInterface; +use Laminas\HttpHandlerRunner\Emitter\EmitterInterface; final class TestEmitter implements EmitterInterface { From 133763e5d26c50f7c8d623739da5c8bb1189f856 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 17 Nov 2021 14:13:53 +0100 Subject: [PATCH 09/10] Updates (#37) * Updates * Remove travis and migrate to GA * Remove infection --- .github/workflows/tests.yml | 32 ++++++++++++++++++++++++++++++++ .gitignore | 1 - .travis.yml | 22 ---------------------- composer.json | 9 ++++----- infection.json.dist | 14 -------------- 5 files changed, 36 insertions(+), 42 deletions(-) create mode 100644 .github/workflows/tests.yml delete mode 100644 .travis.yml delete mode 100644 infection.json.dist diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..ba38486 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,32 @@ +name: CI +on: + - push + - pull_request +jobs: + build: + strategy: + matrix: + dependencies: + - highest + - lowest + php-versions: + - 7.3 + - 7.4 + - 8.0 + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-versions }} + + - name: Install dependencies with Composer + uses: ramsey/composer-install@v1 + with: + dependency-versions: ${{ matrix.dependencies }} + + - name: Run unit tests + run: vendor/bin/phpunit diff --git a/.gitignore b/.gitignore index a0f22fe..0794651 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ /vendor/ composer.lock -infection.log .phpunit.result.cache diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7121b52..0000000 --- a/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -cache: - directories: - - $HOME/.composer/cache/files - -language: php - -php: - - 7.2 - - 7.3 - - 7.4 - -env: - - DEPS=lowest - - DEPS=latest - -before_script: - - phpenv config-rm xdebug.ini - - if [[ $DEPS == 'lowest' ]]; then composer update --prefer-stable --no-interaction --prefer-lowest ; fi - - if [[ $DEPS == 'latest' ]]; then composer update --prefer-stable --no-interaction ; fi - -script: - - ./vendor/bin/phpunit diff --git a/composer.json b/composer.json index f2807e1..15db6bf 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ "psr-11" ], "require": { - "php": "^7.2", + "php": "^7.3 || ^8.0", "maximebf/debugbar": "^1.4", "psr/http-server-handler": "^1.0", "psr/http-server-middleware": "^1.0", @@ -22,14 +22,13 @@ "psr/http-factory-implementation": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^8.5.4 || ^9.1.4", - "mikey179/vfsStream": "^1.6.8", + "phpunit/phpunit": "^9.1.4", + "mikey179/vfsstream": "^1.6.8", "slim/slim": "^3.0", "mezzio/mezzio": "^3.0", "mezzio/mezzio-fastroute": "^3.0.1", "laminas/laminas-servicemanager": "^3.3.2", - "laminas/laminas-diactoros": "^2.0", - "infection/infection": "^0.13.3" + "laminas/laminas-diactoros": "^2.0" }, "autoload": { "psr-4": { diff --git a/infection.json.dist b/infection.json.dist deleted file mode 100644 index 60a2a84..0000000 --- a/infection.json.dist +++ /dev/null @@ -1,14 +0,0 @@ -{ - "timeout": 10, - "source": { - "directories": [ - "src" - ] - }, - "logs": { - "text": "infection.log" - }, - "mutators": { - "@default": true - } -} \ No newline at end of file From 7a55035992c2d7ee3c8b40316d172302ea29021c Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Tue, 22 Feb 2022 14:34:43 +0100 Subject: [PATCH 10/10] Improve deps (#38) * Improve deps * phpstan * Remove on pull request * Fix typos --- .github/workflows/tests.yml | 20 +++++++++++++-- composer.json | 8 +++--- phpunit.xml | 24 +++++++++--------- src/ConfigProvider.php | 6 +++++ src/JavascriptRendererFactory.php | 4 +-- src/PhpDebugBarMiddleware.php | 41 +++++++++++++++++++++++-------- 6 files changed, 72 insertions(+), 31 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index ba38486..0b6a230 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,9 +1,24 @@ name: CI on: - push - - pull_request jobs: - build: + phpstan: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.3 + + - name: Install dependencies with Composer + uses: ramsey/composer-install@v1 + + - name: Run phpstan + run: vendor/bin/phpstan analyse --level=6 src/ + tests: strategy: matrix: dependencies: @@ -13,6 +28,7 @@ jobs: - 7.3 - 7.4 - 8.0 + - 8.1 runs-on: ubuntu-latest steps: - name: Checkout diff --git a/composer.json b/composer.json index 15db6bf..77bcca9 100644 --- a/composer.json +++ b/composer.json @@ -16,9 +16,8 @@ "maximebf/debugbar": "^1.4", "psr/http-server-handler": "^1.0", "psr/http-server-middleware": "^1.0", - "psr/container": "^1.0", - "psr/http-message": "^1.0.1", - "psr/http-factory": "^1.0", + "psr/container-implementation": "^1.0 || ^2.0", + "psr/http-message-implementation": "^1.0", "psr/http-factory-implementation": "^1.0" }, "require-dev": { @@ -28,7 +27,8 @@ "mezzio/mezzio": "^3.0", "mezzio/mezzio-fastroute": "^3.0.1", "laminas/laminas-servicemanager": "^3.3.2", - "laminas/laminas-diactoros": "^2.0" + "laminas/laminas-diactoros": "^2.0", + "phpstan/phpstan": "^1.4" }, "autoload": { "psr-4": { diff --git a/phpunit.xml b/phpunit.xml index b0c7e5f..fd2da66 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,15 +1,13 @@ - - - - - ./test - - - - - - ./src - - + + + + ./src + + + + + ./test + + diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 6204d59..375bad1 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -5,11 +5,17 @@ final class ConfigProvider { + /** + * @return array + */ public static function getConfig(): array { return (new self())(); } + /** + * @return array + */ public function __invoke(): array { $config = include __DIR__ . '/../config/phpdebugbar.config.php'; diff --git a/src/JavascriptRendererFactory.php b/src/JavascriptRendererFactory.php index c47fef0..3063abc 100644 --- a/src/JavascriptRendererFactory.php +++ b/src/JavascriptRendererFactory.php @@ -11,11 +11,11 @@ final class JavascriptRendererFactory { public function __invoke(ContainerInterface $container): JavascriptRenderer { - $debugbar = $container->get(DebugBar::class); + $debugBar = $container->get(DebugBar::class); $config = $container->get(ConfigProvider::class); $rendererOptions = $config['phpmiddleware']['phpdebugbar']['javascript_renderer']; - $renderer = new JavascriptRenderer($debugbar); + $renderer = new JavascriptRenderer($debugBar); $renderer->setOptions($rendererOptions); return $renderer; diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index 6bdc2f6..8d4a892 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -21,16 +21,27 @@ final class PhpDebugBarMiddleware implements MiddlewareInterface { public const FORCE_KEY = 'X-Enable-Debug-Bar'; + /** + * @var DebugBarRenderer + */ private $debugBarRenderer; + + /** + * @var ResponseFactoryInterface + */ private $responseFactory; + + /** + * @var StreamFactoryInterface + */ private $streamFactory; public function __construct( - DebugBarRenderer $debugbarRenderer, + DebugBarRenderer $debugBarRenderer, ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory ) { - $this->debugBarRenderer = $debugbarRenderer; + $this->debugBarRenderer = $debugBarRenderer; $this->responseFactory = $responseFactory; $this->streamFactory = $streamFactory; } @@ -60,7 +71,14 @@ public function process(ServerRequest $request, RequestHandler $handler): Respon public function __invoke(ServerRequest $request, Response $response, callable $next): Response { $handler = new class($next, $response) implements RequestHandler { + /** + * @var callable + */ private $next; + + /** + * @var Response + */ private $response; public function __construct(callable $next, Response $response) @@ -81,9 +99,9 @@ private function shouldReturnResponse(ServerRequest $request, Response $response { $forceHeaderValue = $request->getHeaderLine(self::FORCE_KEY); $forceCookieValue = $request->getCookieParams()[self::FORCE_KEY] ?? ''; - $forceAttibuteValue = $request->getAttribute(self::FORCE_KEY, ''); - $isForceEnable = in_array('true', [$forceHeaderValue, $forceCookieValue, $forceAttibuteValue], true); - $isForceDisable = in_array('false', [$forceHeaderValue, $forceCookieValue, $forceAttibuteValue], true); + $forceAttributeValue = $request->getAttribute(self::FORCE_KEY, ''); + $isForceEnable = in_array('true', [$forceHeaderValue, $forceCookieValue, $forceAttributeValue], true); + $isForceDisable = in_array('false', [$forceHeaderValue, $forceCookieValue, $forceAttributeValue], true); return $isForceDisable || (!$isForceEnable && ($this->isRedirect($response) || !$this->isHtmlAccepted($request))); } @@ -169,22 +187,22 @@ private function getContentTypeByFileName(string $filename): string 'woff2' => 'application/font-woff2', ]; - return isset($map[$ext]) ? $map[$ext] : 'text/plain'; + return $map[$ext] ?? 'text/plain'; } private function isHtmlResponse(Response $response): bool { - return $this->hasHeaderContains($response, 'Content-Type', 'text/html'); + return $this->isHtml($response, 'Content-Type'); } private function isHtmlAccepted(ServerRequest $request): bool { - return $this->hasHeaderContains($request, 'Accept', 'text/html'); + return $this->isHtml($request, 'Accept'); } - private function hasHeaderContains(MessageInterface $message, string $headerName, string $value): bool + private function isHtml(MessageInterface $message, string $headerName): bool { - return strpos($message->getHeaderLine($headerName), $value) !== false; + return strpos($message->getHeaderLine($headerName), 'text/html') !== false; } private function isRedirect(Response $response): bool @@ -216,6 +234,9 @@ private function serializeResponse(Response $response) : string ); } + /** + * @param array> $headers + */ private function serializeHeaders(array $headers) : string { $lines = [];