From a0e3fdf1b0e1b19003152f0ffad161349fcf19cc Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Sun, 13 Nov 2016 22:36:24 +0100 Subject: [PATCH 01/40] Make separate factories for all services --- src/JavascriptRendererFactory.php | 18 ++++++++++++++++++ src/PhpDebugBarMiddlewareFactory.php | 6 ++---- src/StandardDebugBarFactory.php | 13 +++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 src/JavascriptRendererFactory.php create mode 100644 src/StandardDebugBarFactory.php diff --git a/src/JavascriptRendererFactory.php b/src/JavascriptRendererFactory.php new file mode 100644 index 0000000..853c8e5 --- /dev/null +++ b/src/JavascriptRendererFactory.php @@ -0,0 +1,18 @@ +getJavascriptRenderer('/phpdebugbar'); + $rendererFactory = new JavascriptRendererFactory(); + $renderer = $rendererFactory(); return new PhpDebugBarMiddleware($renderer); } diff --git a/src/StandardDebugBarFactory.php b/src/StandardDebugBarFactory.php new file mode 100644 index 0000000..3e81633 --- /dev/null +++ b/src/StandardDebugBarFactory.php @@ -0,0 +1,13 @@ + Date: Sun, 13 Nov 2016 23:39:33 +0100 Subject: [PATCH 02/40] Configurable dependencies --- config/phpdebugbar.config.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 config/phpdebugbar.config.php diff --git a/config/phpdebugbar.config.php b/config/phpdebugbar.config.php new file mode 100644 index 0000000..7a763d6 --- /dev/null +++ b/config/phpdebugbar.config.php @@ -0,0 +1,13 @@ + [ + 'phpdebugbar' => [ + 'javascript_renderer' => [ + 'base_url' => '/phpdebugbar', + ], + 'collectors' => [], + 'storage' => '', + ], + ], +]; From 97014ab748d1dec106b61878fa1440c7bf3af995 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Sun, 13 Nov 2016 23:42:54 +0100 Subject: [PATCH 03/40] Configurable --- composer.json | 1 + config/phpdebugbar.config.php | 2 +- src/ConfigProvider.php | 9 +++++---- src/JavascriptRendererFactory.php | 26 ++++++++++++++++++++++---- src/PhpDebugBarMiddlewareFactory.php | 19 ++++++++++--------- src/StandardDebugBarFactory.php | 23 +++++++++++++++++++++-- 6 files changed, 60 insertions(+), 20 deletions(-) diff --git a/composer.json b/composer.json index 6986873..43d0101 100644 --- a/composer.json +++ b/composer.json @@ -12,6 +12,7 @@ "php": "^5.5 || ^7.0", "maximebf/debugbar": "^1.10", "psr/http-message": "^1.0", + "container-interop/container-interop": "^1.0", "zendframework/zend-diactoros": "^1.1.3" }, "require-dev": { diff --git a/config/phpdebugbar.config.php b/config/phpdebugbar.config.php index 7a763d6..842369c 100644 --- a/config/phpdebugbar.config.php +++ b/config/phpdebugbar.config.php @@ -7,7 +7,7 @@ 'base_url' => '/phpdebugbar', ], 'collectors' => [], - 'storage' => '', + 'storage' => null, ], ], ]; diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 73b3199..328b837 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -12,9 +12,10 @@ public static function getConfig() public function __invoke() { - return [ - 'dependencies' => include __DIR__ . '/../config/dependency.config.php', - 'middleware_pipeline' => include __DIR__ . '/../config/zend-expressive.middleware_pipeline.config.php', - ]; + $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'; + + return $config; } } diff --git a/src/JavascriptRendererFactory.php b/src/JavascriptRendererFactory.php index 853c8e5..7faf310 100644 --- a/src/JavascriptRendererFactory.php +++ b/src/JavascriptRendererFactory.php @@ -2,16 +2,34 @@ namespace PhpMiddleware\PhpDebugBar; +use DebugBar\DebugBar; use DebugBar\JavascriptRenderer; +use Interop\Container\ContainerInterface; final class JavascriptRendererFactory { - public function __invoke() + public function __invoke(ContainerInterface $container = null) { - $standardDebugBarFactory = new StandardDebugBarFactory(); - $debugbar = $standardDebugBarFactory(); + if ($container === null || !$container->has(DebugBar::class)) { + $standardDebugBarFactory = new StandardDebugBarFactory(); + $debugbar = $standardDebugBarFactory($container); + } else { + $debugbar = $container->get(DebugBar::class); + } - $renderer = new JavascriptRenderer($debugbar, '/phpdebugbar'); + $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/PhpDebugBarMiddlewareFactory.php b/src/PhpDebugBarMiddlewareFactory.php index 343bf60..e901009 100644 --- a/src/PhpDebugBarMiddlewareFactory.php +++ b/src/PhpDebugBarMiddlewareFactory.php @@ -2,18 +2,19 @@ namespace PhpMiddleware\PhpDebugBar; -/** - * Default, simple factory for middleware - * - * @author Witold Wasiczko - */ +use DebugBar\JavascriptRenderer; +use Interop\Container\ContainerInterface; + final class PhpDebugBarMiddlewareFactory { - public function __invoke() + public function __invoke(ContainerInterface $container = null) { - $rendererFactory = new JavascriptRendererFactory(); - $renderer = $rendererFactory(); - + if ($container === null || !$container->has(JavascriptRenderer::class)) { + $rendererFactory = new JavascriptRendererFactory(); + $renderer = $rendererFactory($container); + } else { + $renderer = $container->get(JavascriptRenderer::class); + } return new PhpDebugBarMiddleware($renderer); } } diff --git a/src/StandardDebugBarFactory.php b/src/StandardDebugBarFactory.php index 3e81633..b9511d4 100644 --- a/src/StandardDebugBarFactory.php +++ b/src/StandardDebugBarFactory.php @@ -3,11 +3,30 @@ namespace PhpMiddleware\PhpDebugBar; use DebugBar\StandardDebugBar; +use Interop\Container\ContainerInterface; final class StandardDebugBarFactory { - public function __invoke() + public function __invoke(ContainerInterface $container = null) { - return new StandardDebugBar(); + $debugBar = new StandardDebugBar(); + + if ($container !== null) { + $config = $container->has('config') ? $container->get('config') : []; + + $collectors = isset($config['phpmiddleware']['phpdebugbar']['collectors']) ? $config['phpmiddleware']['phpdebugbar']['collectors'] : []; + + foreach ($collectors as $collectorName) { + $collector = $container->get($collectorName); + $debugBar->addCollector($collector); + } + + 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']); + } + } + + return $debugBar; } } From 0ff0f793d3bf9447548ea11a897c3e3b85aa6de9 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Sun, 13 Nov 2016 23:57:59 +0100 Subject: [PATCH 04/40] Config collector by default --- src/ConfigCollectorFactory.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/ConfigCollectorFactory.php diff --git a/src/ConfigCollectorFactory.php b/src/ConfigCollectorFactory.php new file mode 100644 index 0000000..f56b188 --- /dev/null +++ b/src/ConfigCollectorFactory.php @@ -0,0 +1,16 @@ +get('config'); + + return new ConfigCollector($data, 'Config'); + } +} From cbcdea1d22e0d11e580d693109be1e40c9cb73f0 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Mon, 14 Nov 2016 00:00:49 +0100 Subject: [PATCH 05/40] Fix container reqs --- composer.json | 2 +- config/dependency.config.php | 1 + config/phpdebugbar.config.php | 4 +++- test/ZendExpressiveTest.php | 20 ++++++++++++++++++++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 43d0101..0cfa0a4 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ "php": "^5.5 || ^7.0", "maximebf/debugbar": "^1.10", "psr/http-message": "^1.0", - "container-interop/container-interop": "^1.0", + "container-interop/container-interop": "^1.1", "zendframework/zend-diactoros": "^1.1.3" }, "require-dev": { diff --git a/config/dependency.config.php b/config/dependency.config.php index eeb3ea2..d9f21cf 100644 --- a/config/dependency.config.php +++ b/config/dependency.config.php @@ -3,5 +3,6 @@ return [ 'factories' => [ PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware::class => PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory::class, + DebugBar\DataCollector\ConfigCollector::class => PhpMiddleware\PhpDebugBar\ConfigCollectorFactory::class, ], ]; diff --git a/config/phpdebugbar.config.php b/config/phpdebugbar.config.php index 842369c..5a6b9a8 100644 --- a/config/phpdebugbar.config.php +++ b/config/phpdebugbar.config.php @@ -6,7 +6,9 @@ 'javascript_renderer' => [ 'base_url' => '/phpdebugbar', ], - 'collectors' => [], + 'collectors' => [ + DebugBar\DataCollector\ConfigCollector::class, + ], 'storage' => null, ], ], diff --git a/test/ZendExpressiveTest.php b/test/ZendExpressiveTest.php index 7296c2c..f47bcde 100644 --- a/test/ZendExpressiveTest.php +++ b/test/ZendExpressiveTest.php @@ -4,10 +4,12 @@ use Interop\Container\ContainerInterface; use PhpMiddleware\PhpDebugBar\ConfigProvider; +use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\EmitterInterface; use Zend\Diactoros\ServerRequestFactory; use Zend\Expressive\Container\ApplicationFactory; use Zend\ServiceManager\ServiceManager; +use Zend\Stratigility\Http\ResponseInterface; final class ZendExpressiveTest extends AbstractMiddlewareRunnerTest { @@ -20,6 +22,24 @@ protected function setUp() $this->testEmitter = new TestEmitter(); } + final public function testContainsConfigCollectorOutput() + { + $response = $this->dispatchApplication([ + 'REQUEST_URI' => '/hello', + 'REQUEST_METHOD' => 'GET', + 'HTTP_ACCEPT' => 'text/html', + ], [ + '/hello' => function (ServerRequestInterface $request, ResponseInterface $response, $next) { + $response->getBody()->write('Hello!'); + return $response; + }, + ]); + + $responseBody = (string) $response->getBody(); + + $this->assertContains('DebugBar\\\DataCollector\\\ConfigCollector', $responseBody); + } + protected function dispatchApplication(array $server, array $pipe = []) { $container = $this->createContainer(); From 95a1c4dafdf0b978710c4848cbecb9c7d599c26f Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Mon, 14 Nov 2016 22:41:46 +0100 Subject: [PATCH 06/40] Update README.md --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index bb3edfd..5297f2e 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,27 @@ and add middleware from container to app: $app->add($app->getContainer()->get('debugbar_middleware')); ``` +### How to configure using existing factories? + +Put array with configuration into `config` service in your container: + +```php + [ + 'phpdebugbar' => [ + 'javascript_renderer' => [ + 'base_url' => '/phpdebugbar', + ], + 'collectors' => [ + DebugBar\DataCollector\ConfigCollector::class, // Service names of collectors + ], + 'storage' => null, // Service name of storage + ], + ], +]; +``` + ## It's just works with any modern php framework! Middleware tested on: From 6a1f20f07ff5aca52cac11947309d89cc6673eaa Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 20:50:16 +0200 Subject: [PATCH 07/40] Add psr-15 support, drop 5.5 support --- .travis.yml | 5 +-- composer.json | 11 +++-- phpunit.xml | 2 +- src/PhpDebugBarMiddleware.php | 76 +++++++++++++++++++---------------- 4 files changed, 51 insertions(+), 43 deletions(-) diff --git a/.travis.yml b/.travis.yml index 573e782..c4c6989 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.5 - 5.6 - 7.0 - 7.1 @@ -13,8 +12,8 @@ env: before_script: - composer self-update - - if [[ $DEPS == 'lowest' ]]; then travis_retry composer update --prefer-lowest --prefer-stable --no-interaction ; fi - - travis_retry composer install --no-interaction + - 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 0cfa0a4..1b75d09 100644 --- a/composer.json +++ b/composer.json @@ -6,17 +6,20 @@ "debug", "middleware", "psr", - "psr-7" + "psr-7", + "psr-15" ], "require": { - "php": "^5.5 || ^7.0", + "php": ">=5.6", "maximebf/debugbar": "^1.10", "psr/http-message": "^1.0", "container-interop/container-interop": "^1.1", - "zendframework/zend-diactoros": "^1.1.3" + "zendframework/zend-diactoros": "^1.1.3", + "http-interop/http-middleware": "^0.4.1", + "php-middleware/double-pass-compatibility": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^4.8.6", + "phpunit/phpunit": "^5.7.19", "mikey179/vfsStream": "^1.6", "slim/slim": "^3.0", "zendframework/zend-expressive": "^1.0", diff --git a/phpunit.xml b/phpunit.xml index 88ba754..0344107 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -2,7 +2,7 @@ - + ./test diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index 210753d..7f580a5 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -3,6 +3,9 @@ namespace PhpMiddleware\PhpDebugBar; use DebugBar\JavascriptRenderer as DebugBarRenderer; +use Interop\Http\ServerMiddleware\DelegateInterface; +use Interop\Http\ServerMiddleware\MiddlewareInterface; +use PhpMiddleware\DoublePassCompatibilityTrait; use Psr\Http\Message\MessageInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; @@ -18,64 +21,71 @@ * * @author Witold Wasiczko */ -class PhpDebugBarMiddleware +class PhpDebugBarMiddleware implements MiddlewareInterface { - /** - * @var DebugBarRenderer - */ + use DoublePassCompatibilityTrait; + protected $debugBarRenderer; - /** - * @param DebugBarRenderer $debugbarRenderer - */ public function __construct(DebugBarRenderer $debugbarRenderer) { $this->debugBarRenderer = $debugbarRenderer; } /** - * @param ServerRequestInterface $request - * @param ResponseInterface $response - * @param callable $next - * - * @return ResponseInterface + * @inheritDoc */ - public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) + public function process(ServerRequestInterface $request, DelegateInterface $delegate) { if ($staticFile = $this->getStaticFile($request->getUri())) { return $staticFile; } - $outResponse = $next($request, $response); + $response = $delegate->process($request); if (!$this->isHtmlAccepted($request)) { - return $outResponse; + return $response; } - $debugBarHead = $this->debugBarRenderer->renderHead(); - $debugBarBody = $this->debugBarRenderer->render(); - - if ($this->isHtmlResponse($outResponse)) { - $body = $outResponse->getBody(); - if (! $body->eof() && $body->isSeekable()) { - $body->seek(0, SEEK_END); - } - $body->write($debugBarHead . $debugBarBody); - - return $outResponse; + if ($this->isHtmlResponse($response)) { + return $this->attachDebugBarToResponse($response); } + return $this->prepareHtmlResponseWithDebugBar($response); + } - $outResponseBody = Serializer::toString($outResponse); + /** + * @return HtmlResponse + */ + private function prepareHtmlResponseWithDebugBar(ResponseInterface $response) + { + $head = $this->debugBarRenderer->renderHead(); + $body = $this->debugBarRenderer->render(); + $outResponseBody = Serializer::toString($response); $template = '%s

DebugBar

Response:

%s
%s'; $escapedOutResponseBody = htmlspecialchars($outResponseBody); - $result = sprintf($template, $debugBarHead, $escapedOutResponseBody, $debugBarBody); + $result = sprintf($template, $head, $escapedOutResponseBody, $body); return new HtmlResponse($result); } /** - * @param UriInterface $uri - * + * @return ResponseInterface + */ + private function attachDebugBarToResponse(ResponseInterface $response) + { + $head = $this->debugBarRenderer->renderHead(); + $body = $this->debugBarRenderer->render(); + $responseBody = $response->getBody(); + + if (! $responseBody->eof() && $responseBody->isSeekable()) { + $responseBody->seek(0, SEEK_END); + } + $responseBody->write($head . $body); + + return $response; + } + + /** * @return ResponseInterface|null */ private function getStaticFile(UriInterface $uri) @@ -139,11 +149,7 @@ private function getContentTypeByFileName($filename) 'woff2' => 'application/font-woff2', ]; - if (isset($map[$ext])) { - return $map[$ext]; - } - - return 'text/plain'; + return isset($map[$ext]) ? $map[$ext] : 'text/plain'; } /** From d77b58fa65fb225a0f0d354b680cc07c10d45523 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 21:10:16 +0200 Subject: [PATCH 08/40] Simplify config provider --- src/ConfigProvider.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 328b837..7752920 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -6,8 +6,7 @@ final class ConfigProvider { public static function getConfig() { - $self = new self(); - return $self(); + return (new self())(); } public function __invoke() From 1c2485a81cc0ddda063629f9f179ee54b31341f2 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 21:11:20 +0200 Subject: [PATCH 09/40] Drop hhvm support --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c4c6989..0baae28 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,6 @@ php: - 5.6 - 7.0 - 7.1 - - hhvm env: - DEPS=lowest From de4de3b145bcb9bef152d4ff29b183faab24b57a Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 21:12:57 +0200 Subject: [PATCH 10/40] Revert config-provider --- src/ConfigProvider.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 7752920..4bdc374 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -6,7 +6,8 @@ final class ConfigProvider { public static function getConfig() { - return (new self())(); + $self = new self(); + return $self()(); } public function __invoke() From dbfc9d0caa4b2f21ef2566207276f884215a7ff5 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 21:32:48 +0200 Subject: [PATCH 11/40] FIx --- src/ConfigProvider.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 4bdc374..328b837 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -7,7 +7,7 @@ final class ConfigProvider public static function getConfig() { $self = new self(); - return $self()(); + return $self(); } public function __invoke() From 8d6083d1b3d73266bff4e75520c66dffd7eb0303 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 22:41:31 +0200 Subject: [PATCH 12/40] Allow to test zend-expressive v2 --- composer.json | 4 ++-- test/ZendExpressiveTest.php | 15 +++------------ 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/composer.json b/composer.json index 1b75d09..0f50545 100644 --- a/composer.json +++ b/composer.json @@ -22,8 +22,8 @@ "phpunit/phpunit": "^5.7.19", "mikey179/vfsStream": "^1.6", "slim/slim": "^3.0", - "zendframework/zend-expressive": "^1.0", - "zendframework/zend-expressive-fastroute": "^1.0", + "zendframework/zend-expressive": "^1.0 || ^2.0", + "zendframework/zend-expressive-fastroute": "^1.0 || ^2.0", "zendframework/zend-servicemanager": "^3.0" }, "autoload": { diff --git a/test/ZendExpressiveTest.php b/test/ZendExpressiveTest.php index f47bcde..688ec3e 100644 --- a/test/ZendExpressiveTest.php +++ b/test/ZendExpressiveTest.php @@ -4,24 +4,15 @@ use Interop\Container\ContainerInterface; use PhpMiddleware\PhpDebugBar\ConfigProvider; +use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\EmitterInterface; use Zend\Diactoros\ServerRequestFactory; use Zend\Expressive\Container\ApplicationFactory; use Zend\ServiceManager\ServiceManager; -use Zend\Stratigility\Http\ResponseInterface; final class ZendExpressiveTest extends AbstractMiddlewareRunnerTest { - private $testEmitter; - - protected function setUp() - { - parent::setUp(); - - $this->testEmitter = new TestEmitter(); - } - final public function testContainsConfigCollectorOutput() { $response = $this->dispatchApplication([ @@ -58,7 +49,7 @@ protected function dispatchApplication(array $server, array $pipe = []) $app->run($serverRequest); - return $this->testEmitter->getResponse(); + return $container->get(EmitterInterface::class)->getResponse(); } /** @@ -71,7 +62,7 @@ private function createContainer() $serviceManagerConfig = $config['dependencies']; $serviceManagerConfig['services']['config'] = $config; - $serviceManagerConfig['services'][EmitterInterface::class] = $this->testEmitter; + $serviceManagerConfig['services'][EmitterInterface::class] = new TestEmitter(); return new ServiceManager($serviceManagerConfig); } From 5f5989b7ac5c62e29852c65f7dfcb6aa278aa182 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 22:48:26 +0200 Subject: [PATCH 13/40] Add support for phpunit 6.1 --- composer.json | 4 ++-- test/AbstractMiddlewareRunnerTest.php | 4 ++-- test/PhpDebugBarMiddlewareFactoryTest.php | 4 ++-- test/PhpDebugBarMiddlewareTest.php | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 0f50545..0f4a84d 100644 --- a/composer.json +++ b/composer.json @@ -19,8 +19,8 @@ "php-middleware/double-pass-compatibility": "^1.0" }, "require-dev": { - "phpunit/phpunit": "^5.7.19", - "mikey179/vfsStream": "^1.6", + "phpunit/phpunit": "^5.7.19 || ^6.1.3", + "mikey179/vfsStream": "^1.6.4", "slim/slim": "^3.0", "zendframework/zend-expressive": "^1.0 || ^2.0", "zendframework/zend-expressive-fastroute": "^1.0 || ^2.0", diff --git a/test/AbstractMiddlewareRunnerTest.php b/test/AbstractMiddlewareRunnerTest.php index 44bbd4e..9f05610 100644 --- a/test/AbstractMiddlewareRunnerTest.php +++ b/test/AbstractMiddlewareRunnerTest.php @@ -2,11 +2,11 @@ namespace PhpMiddlewareTest\PhpDebugBar; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; -abstract class AbstractMiddlewareRunnerTest extends PHPUnit_Framework_TestCase +abstract class AbstractMiddlewareRunnerTest extends TestCase { final public function testAppendJsIntoHtmlContent() diff --git a/test/PhpDebugBarMiddlewareFactoryTest.php b/test/PhpDebugBarMiddlewareFactoryTest.php index 215bef4..32bd43b 100644 --- a/test/PhpDebugBarMiddlewareFactoryTest.php +++ b/test/PhpDebugBarMiddlewareFactoryTest.php @@ -4,12 +4,12 @@ use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware; use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; /** * @author Witold Wasiczko */ -class PhpDebugBarMiddlewareFactoryTest extends PHPUnit_Framework_TestCase +class PhpDebugBarMiddlewareFactoryTest extends TestCase { public function testFactory() { diff --git a/test/PhpDebugBarMiddlewareTest.php b/test/PhpDebugBarMiddlewareTest.php index f474d81..2eec264 100644 --- a/test/PhpDebugBarMiddlewareTest.php +++ b/test/PhpDebugBarMiddlewareTest.php @@ -5,7 +5,7 @@ use DebugBar\JavascriptRenderer; use org\bovigo\vfs\vfsStream; use PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Zend\Diactoros\Response; use Zend\Diactoros\ServerRequest; use Zend\Diactoros\Uri; @@ -15,7 +15,7 @@ * * @author Witold Wasiczko */ -class PhpDebugBarMiddlewareTest extends PHPUnit_Framework_TestCase +class PhpDebugBarMiddlewareTest extends TestCase { protected $debugbarRenderer; protected $middleware; From 52c216937080c54cb1b421e85aaa5182c8624c6c Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 22:50:22 +0200 Subject: [PATCH 14/40] Sort packages --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 0f4a84d..b7307c8 100644 --- a/composer.json +++ b/composer.json @@ -11,12 +11,12 @@ ], "require": { "php": ">=5.6", - "maximebf/debugbar": "^1.10", - "psr/http-message": "^1.0", "container-interop/container-interop": "^1.1", - "zendframework/zend-diactoros": "^1.1.3", "http-interop/http-middleware": "^0.4.1", - "php-middleware/double-pass-compatibility": "^1.0" + "maximebf/debugbar": "^1.10", + "php-middleware/double-pass-compatibility": "^1.0", + "psr/http-message": "^1.0", + "zendframework/zend-diactoros": "^1.1.3" }, "require-dev": { "phpunit/phpunit": "^5.7.19 || ^6.1.3", From 13cb9116930aa7cfeaf14afd2865ab6fd46a87b0 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 22:57:01 +0200 Subject: [PATCH 15/40] Use psr-11 container --- README.md | 7 +++---- composer.json | 4 ++-- src/ConfigCollectorFactory.php | 2 +- src/JavascriptRendererFactory.php | 2 +- src/PhpDebugBarMiddlewareFactory.php | 2 +- src/StandardDebugBarFactory.php | 2 +- test/ZendExpressiveTest.php | 2 +- 7 files changed, 10 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 5297f2e..e903ebf 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # phpdebugbar middleware [![Build Status](https://travis-ci.org/php-middleware/phpdebugbar.svg?branch=master)](https://travis-ci.org/php-middleware/phpdebugbar) -PHP Debug bar middleware with PSR-7 +PHP Debug bar PSR-15 middleware with PSR-7 -This middleware provide framework-agnostic possibility to attach [PHP Debug bar](http://phpdebugbar.com/) to your response (html on non-html!). +This middleware provide framework-agnostic possibility to attach [PHP Debug Bar](http://phpdebugbar.com/) to your response (html on non-html!). ## Installation @@ -18,7 +18,7 @@ $middleware = new PhpMiddleware\PhpDebugBar\PhpDebugBarMiddleware($debugbarRende // OR -$factory = PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory(); +$factory = new PhpMiddleware\PhpDebugBar\PhpDebugBarMiddlewareFactory(); $middleware = $factory(); $app = new MiddlewareRunner(); @@ -61,7 +61,6 @@ $app->add($app->getContainer()->get('debugbar_middleware')); Put array with configuration into `config` service in your container: ```php - [ 'phpdebugbar' => [ diff --git a/composer.json b/composer.json index b7307c8..4fb321d 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "php-middleware/php-debug-bar", - "description": "PHP Debug bar middleware with PSR-7", + "description": "PHP Debug Bar PSR-15 middleware with PSR-7", "type": "library", "keywords": [ "debug", @@ -11,10 +11,10 @@ ], "require": { "php": ">=5.6", - "container-interop/container-interop": "^1.1", "http-interop/http-middleware": "^0.4.1", "maximebf/debugbar": "^1.10", "php-middleware/double-pass-compatibility": "^1.0", + "psr/container": "^1.0", "psr/http-message": "^1.0", "zendframework/zend-diactoros": "^1.1.3" }, diff --git a/src/ConfigCollectorFactory.php b/src/ConfigCollectorFactory.php index f56b188..75bd70d 100644 --- a/src/ConfigCollectorFactory.php +++ b/src/ConfigCollectorFactory.php @@ -3,7 +3,7 @@ namespace PhpMiddleware\PhpDebugBar; use DebugBar\DataCollector\ConfigCollector; -use Interop\Container\ContainerInterface; +use Psr\Container\ContainerInterface; final class ConfigCollectorFactory { diff --git a/src/JavascriptRendererFactory.php b/src/JavascriptRendererFactory.php index 7faf310..cbb5bd9 100644 --- a/src/JavascriptRendererFactory.php +++ b/src/JavascriptRendererFactory.php @@ -4,7 +4,7 @@ use DebugBar\DebugBar; use DebugBar\JavascriptRenderer; -use Interop\Container\ContainerInterface; +use Psr\Container\ContainerInterface; final class JavascriptRendererFactory { diff --git a/src/PhpDebugBarMiddlewareFactory.php b/src/PhpDebugBarMiddlewareFactory.php index e901009..8c44595 100644 --- a/src/PhpDebugBarMiddlewareFactory.php +++ b/src/PhpDebugBarMiddlewareFactory.php @@ -3,7 +3,7 @@ namespace PhpMiddleware\PhpDebugBar; use DebugBar\JavascriptRenderer; -use Interop\Container\ContainerInterface; +use Psr\Container\ContainerInterface; final class PhpDebugBarMiddlewareFactory { diff --git a/src/StandardDebugBarFactory.php b/src/StandardDebugBarFactory.php index b9511d4..b80f0e3 100644 --- a/src/StandardDebugBarFactory.php +++ b/src/StandardDebugBarFactory.php @@ -3,7 +3,7 @@ namespace PhpMiddleware\PhpDebugBar; use DebugBar\StandardDebugBar; -use Interop\Container\ContainerInterface; +use Psr\Container\ContainerInterface; final class StandardDebugBarFactory { diff --git a/test/ZendExpressiveTest.php b/test/ZendExpressiveTest.php index 688ec3e..7456ed9 100644 --- a/test/ZendExpressiveTest.php +++ b/test/ZendExpressiveTest.php @@ -2,8 +2,8 @@ namespace PhpMiddlewareTest\PhpDebugBar; -use Interop\Container\ContainerInterface; use PhpMiddleware\PhpDebugBar\ConfigProvider; +use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\EmitterInterface; From c6164725ba45358d1ad613bf284b9267b79d73ce Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 23:09:05 +0200 Subject: [PATCH 16/40] Allow lower version of debugbar --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 4fb321d..a0f27af 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ "require": { "php": ">=5.6", "http-interop/http-middleware": "^0.4.1", - "maximebf/debugbar": "^1.10", + "maximebf/debugbar": "^1.4", "php-middleware/double-pass-compatibility": "^1.0", "psr/container": "^1.0", "psr/http-message": "^1.0", @@ -24,7 +24,7 @@ "slim/slim": "^3.0", "zendframework/zend-expressive": "^1.0 || ^2.0", "zendframework/zend-expressive-fastroute": "^1.0 || ^2.0", - "zendframework/zend-servicemanager": "^3.0" + "zendframework/zend-servicemanager": "^3.3" }, "autoload": { "psr-4": { From fa788619b6ed96726e6a799d361ef0ca9b031ddc Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 11 May 2017 23:12:27 +0200 Subject: [PATCH 17/40] Disable xdebug to speedup travis --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 0baae28..a919868 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,7 @@ env: - DEPS=latest before_script: + - phpenv config-rm xdebug.ini - composer self-update - if [[ $DEPS == 'lowest' ]]; then composer update --prefer-stable --no-interaction --prefer-lowest ; fi - if [[ $DEPS == 'latest' ]]; then composer update --prefer-stable --no-interaction ; fi From 4cd4c088da7271362e787cdc86e43a218c576086 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Tue, 16 May 2017 23:56:55 +0200 Subject: [PATCH 18/40] Add MIT license --- LICENSE | 21 +++++++++++++++++++++ composer.json | 1 + 2 files changed, 22 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..301f924 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 PHP Middleware + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/composer.json b/composer.json index a0f27af..2543e54 100644 --- a/composer.json +++ b/composer.json @@ -2,6 +2,7 @@ "name": "php-middleware/php-debug-bar", "description": "PHP Debug Bar PSR-15 middleware with PSR-7", "type": "library", + "license": "MIT", "keywords": [ "debug", "middleware", From b631fb66602ab3e60fe8303bf04459540a99a89d Mon Sep 17 00:00:00 2001 From: prolic Date: Mon, 26 Mar 2018 23:42:26 +0800 Subject: [PATCH 19/40] update to final psr-15, support expressive 3 only --- composer.json | 12 ++++++------ src/PhpDebugBarMiddleware.php | 9 +++------ 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/composer.json b/composer.json index 2543e54..0eeb0c9 100644 --- a/composer.json +++ b/composer.json @@ -11,20 +11,20 @@ "psr-15" ], "require": { - "php": ">=5.6", - "http-interop/http-middleware": "^0.4.1", + "php": ">=7", + "psr/http-server-handler": "^1.0", + "psr/http-server-middleware": "^1.0", "maximebf/debugbar": "^1.4", - "php-middleware/double-pass-compatibility": "^1.0", "psr/container": "^1.0", "psr/http-message": "^1.0", "zendframework/zend-diactoros": "^1.1.3" }, "require-dev": { - "phpunit/phpunit": "^5.7.19 || ^6.1.3", + "phpunit/phpunit": "^6.6", "mikey179/vfsStream": "^1.6.4", "slim/slim": "^3.0", - "zendframework/zend-expressive": "^1.0 || ^2.0", - "zendframework/zend-expressive-fastroute": "^1.0 || ^2.0", + "zendframework/zend-expressive": "^3.0", + "zendframework/zend-expressive-fastroute": "^3.0", "zendframework/zend-servicemanager": "^3.3" }, "autoload": { diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index 7f580a5..1661194 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -3,13 +3,12 @@ namespace PhpMiddleware\PhpDebugBar; use DebugBar\JavascriptRenderer as DebugBarRenderer; -use Interop\Http\ServerMiddleware\DelegateInterface; -use Interop\Http\ServerMiddleware\MiddlewareInterface; use PhpMiddleware\DoublePassCompatibilityTrait; use Psr\Http\Message\MessageInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UriInterface; +use Psr\Http\Server\MiddlewareInterface; use Slim\Http\Uri; use Zend\Diactoros\Response; use Zend\Diactoros\Response\HtmlResponse; @@ -23,8 +22,6 @@ */ class PhpDebugBarMiddleware implements MiddlewareInterface { - use DoublePassCompatibilityTrait; - protected $debugBarRenderer; public function __construct(DebugBarRenderer $debugbarRenderer) @@ -35,13 +32,13 @@ public function __construct(DebugBarRenderer $debugbarRenderer) /** * @inheritDoc */ - public function process(ServerRequestInterface $request, DelegateInterface $delegate) + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { if ($staticFile = $this->getStaticFile($request->getUri())) { return $staticFile; } - $response = $delegate->process($request); + $response = $handler->handle($request); if (!$this->isHtmlAccepted($request)) { return $response; From 0f9639628e497c43ebe7546fedccd7742ce1eccf Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Tue, 27 Mar 2018 00:07:44 +0800 Subject: [PATCH 20/40] Update PhpDebugBarMiddleware.php --- src/PhpDebugBarMiddleware.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index 1661194..da42e5d 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -9,6 +9,7 @@ use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UriInterface; use Psr\Http\Server\MiddlewareInterface; +use Psr\Http\Server\RequestHandlerInterface; use Slim\Http\Uri; use Zend\Diactoros\Response; use Zend\Diactoros\Response\HtmlResponse; From 73e559e8d09af71d877a22e9df28f9c7430c8b0c Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Tue, 27 Mar 2018 00:20:03 +0800 Subject: [PATCH 21/40] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 0eeb0c9..8eeae6a 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,7 @@ "zendframework/zend-diactoros": "^1.1.3" }, "require-dev": { - "phpunit/phpunit": "^6.6", + "phpunit/phpunit": "^6.5", "mikey179/vfsStream": "^1.6.4", "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", From de627dfbf79407c8945f133ff674f8170f6c17f4 Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Tue, 27 Mar 2018 00:20:14 +0800 Subject: [PATCH 22/40] Update .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a919868..09d2386 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,9 @@ language: php php: - - 5.6 - 7.0 - 7.1 + - 7.2 env: - DEPS=lowest From de86ba5a6fa2c73d4c32f52cc44efb44cdde6e36 Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Tue, 27 Mar 2018 00:24:30 +0800 Subject: [PATCH 23/40] Update composer.json --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 8eeae6a..ad3f3aa 100644 --- a/composer.json +++ b/composer.json @@ -14,17 +14,17 @@ "php": ">=7", "psr/http-server-handler": "^1.0", "psr/http-server-middleware": "^1.0", - "maximebf/debugbar": "^1.4", + "maximebf/debugbar": "^1.15", "psr/container": "^1.0", - "psr/http-message": "^1.0", - "zendframework/zend-diactoros": "^1.1.3" + "psr/http-message": "^1.0.1", + "zendframework/zend-diactoros": "^1.7.1" }, "require-dev": { "phpunit/phpunit": "^6.5", "mikey179/vfsStream": "^1.6.4", "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", - "zendframework/zend-expressive-fastroute": "^3.0", + "zendframework/zend-expressive-fastroute": "^3.0.1", "zendframework/zend-servicemanager": "^3.3" }, "autoload": { From 45ddc088e29ca477d3d5f6d7436f3a38dd545f2e Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Tue, 27 Mar 2018 00:25:52 +0800 Subject: [PATCH 24/40] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index ad3f3aa..0e82ea9 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ "psr-15" ], "require": { - "php": ">=7", + "php": "^7.1", "psr/http-server-handler": "^1.0", "psr/http-server-middleware": "^1.0", "maximebf/debugbar": "^1.15", From 6a36fb60c085702935fdbd7e2fc1681534a78543 Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Tue, 27 Mar 2018 00:26:14 +0800 Subject: [PATCH 25/40] Update .travis.yml --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 09d2386..8209ccd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 7.0 - 7.1 - 7.2 From 393ef44b823bbe7ef0e18475f080519fbf6cdd84 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 11 Apr 2018 22:59:19 +0200 Subject: [PATCH 26/40] Fix tests, update implementation to use php 7.1 and update docs --- README.md | 14 +--- composer.json | 6 +- src/ConfigCollectorFactory.php | 3 +- src/ConfigProvider.php | 5 +- src/JavascriptRendererFactory.php | 3 +- src/PhpDebugBarMiddleware.php | 24 +++++- src/PhpDebugBarMiddlewareFactory.php | 3 +- src/ResponseInjector/AlwaysInjector.php | 40 ++++++++++ .../ResponseInjectorInterface.php | 15 ++++ src/StandardDebugBarFactory.php | 3 +- test/AbstractMiddlewareRunnerTest.php | 14 ++-- test/PhpDebugBarMiddlewareFactoryTest.php | 3 +- test/PhpDebugBarMiddlewareTest.php | 79 +++++++++---------- test/RequestHandlerStub.php | 32 ++++++++ test/Slim3Test.php | 4 +- test/TestEmitter.php | 9 ++- test/ZendExpressiveTest.php | 69 ++++++++++++---- 17 files changed, 232 insertions(+), 94 deletions(-) create mode 100644 src/ResponseInjector/AlwaysInjector.php create mode 100644 src/ResponseInjector/ResponseInjectorInterface.php create mode 100644 test/RequestHandlerStub.php diff --git a/README.md b/README.md index e903ebf..85bb850 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # 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 middleware with PSR-7 +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]([PSR-7](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!). @@ -30,17 +30,7 @@ You don't need to copy any static assets from phpdebugbar vendor! ### How to install on Zend Expressive? -Use [mtymek/expressive-config-manager](https://github.com/mtymek/expressive-config-manager) and add -`PhpMiddleware\PhpDebugBar\ConfigProvider` class name: - -```php -$configManager = new \Zend\Expressive\ConfigManager\ConfigManager([ - \PhpMiddleware\PhpDebugBar\ConfigProvider::class, - new \Zend\Expressive\ConfigManager\PhpFileProvider('config/autoload/{{,*.}global,{,*.}local}.php'), -]); -``` - -more [about config manager](https://zendframework.github.io/zend-expressive/cookbook/modular-layout/). +[Follow Zend Expressive documentation](https://docs.zendframework.com/zend-expressive/v3/features/modular-applications/). ### How to install on Slim 3? diff --git a/composer.json b/composer.json index 0e82ea9..496df0c 100644 --- a/composer.json +++ b/composer.json @@ -12,15 +12,15 @@ ], "require": { "php": "^7.1", + "maximebf/debugbar": "^1.4", "psr/http-server-handler": "^1.0", "psr/http-server-middleware": "^1.0", - "maximebf/debugbar": "^1.15", "psr/container": "^1.0", "psr/http-message": "^1.0.1", - "zendframework/zend-diactoros": "^1.7.1" + "zendframework/zend-diactoros": "^1.1.3" }, "require-dev": { - "phpunit/phpunit": "^6.5", + "phpunit/phpunit": "^7.1.2", "mikey179/vfsStream": "^1.6.4", "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", diff --git a/src/ConfigCollectorFactory.php b/src/ConfigCollectorFactory.php index 75bd70d..faed230 100644 --- a/src/ConfigCollectorFactory.php +++ b/src/ConfigCollectorFactory.php @@ -1,4 +1,5 @@ get('config'); diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 328b837..018c386 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -1,16 +1,17 @@ has(DebugBar::class)) { $standardDebugBarFactory = new StandardDebugBarFactory(); diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index da42e5d..c29defd 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -1,9 +1,9 @@ */ -class PhpDebugBarMiddleware implements MiddlewareInterface +final class PhpDebugBarMiddleware implements MiddlewareInterface { protected $debugBarRenderer; @@ -51,6 +51,26 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface return $this->prepareHtmlResponseWithDebugBar($response); } + public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface + { + $handler = new class($next, $response) implements RequestHandlerInterface { + private $next; + private $response; + + public function __construct(callable $next, ResponseInterface $response) + { + $this->next = $next; + $this->response = $response; + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return ($this->next)($request, $this->response); + } + }; + return $this->process($request, $handler); + } + /** * @return HtmlResponse */ diff --git a/src/PhpDebugBarMiddlewareFactory.php b/src/PhpDebugBarMiddlewareFactory.php index 8c44595..8135d75 100644 --- a/src/PhpDebugBarMiddlewareFactory.php +++ b/src/PhpDebugBarMiddlewareFactory.php @@ -1,4 +1,5 @@ has(JavascriptRenderer::class)) { $rendererFactory = new JavascriptRendererFactory(); diff --git a/src/ResponseInjector/AlwaysInjector.php b/src/ResponseInjector/AlwaysInjector.php new file mode 100644 index 0000000..1b84a42 --- /dev/null +++ b/src/ResponseInjector/AlwaysInjector.php @@ -0,0 +1,40 @@ +renderHead(); + $debugBarBody = $debugBarRenderer->render(); + + if ($this->isHtmlResponse($outResponse)) { + $body = $outResponse->getBody(); + if (! $body->eof() && $body->isSeekable()) { + $body->seek(0, SEEK_END); + } + $body->write($debugBarHead . $debugBarBody); + + return $outResponse; + } + + $outResponseBody = Serializer::toString($outResponse); + $template = '%s

DebugBar

Response:

%s
%s'; + $escapedOutResponseBody = htmlspecialchars($outResponseBody); + $result = sprintf($template, $debugBarHead, $escapedOutResponseBody, $debugBarBody); + + return new HtmlResponse($result); + } + + private function isHtmlResponse(ResponseInterface $response): bool + { + return $this->hasHeaderContains($response, 'Content-Type', 'text/html'); + } +} diff --git a/src/ResponseInjector/ResponseInjectorInterface.php b/src/ResponseInjector/ResponseInjectorInterface.php new file mode 100644 index 0000000..2c1910e --- /dev/null +++ b/src/ResponseInjector/ResponseInjectorInterface.php @@ -0,0 +1,15 @@ + + */ +interface ResponseInjectorInterface +{ + public function injectPhpDebugBar(ResponseInterface $response, JavascriptRenderer $debugBar): ResponseInterface; +} diff --git a/src/StandardDebugBarFactory.php b/src/StandardDebugBarFactory.php index b80f0e3..aedfb83 100644 --- a/src/StandardDebugBarFactory.php +++ b/src/StandardDebugBarFactory.php @@ -1,4 +1,5 @@ dispatchApplication([ 'REQUEST_URI' => '/hello', 'REQUEST_METHOD' => 'GET', 'HTTP_ACCEPT' => 'text/html', ], [ - '/hello' => function (ServerRequestInterface $request, ResponseInterface $response, $next) { + '/hello' => function (ServerRequestInterface $request) { + $response = new Response(); $response->getBody()->write('Hello!'); return $response; }, @@ -29,7 +32,7 @@ final public function testAppendJsIntoHtmlContent() $this->assertContains('"/phpdebugbar/debugbar.js"', $responseBody); } - final public function testGetStatics() + final public function testGetStatics(): void { $response = $this->dispatchApplication([ 'DOCUMENT_ROOT' => __DIR__, @@ -53,8 +56,5 @@ final public function testGetStatics() $this->assertContains('text/javascript', $contentType); } - /** - * @return ResponseInterface - */ - abstract protected function dispatchApplication(array $server, array $pipe = []); + abstract protected function dispatchApplication(array $server, array $pipe = []): ResponseInterface; } diff --git a/test/PhpDebugBarMiddlewareFactoryTest.php b/test/PhpDebugBarMiddlewareFactoryTest.php index 32bd43b..0082589 100644 --- a/test/PhpDebugBarMiddlewareFactoryTest.php +++ b/test/PhpDebugBarMiddlewareFactoryTest.php @@ -1,4 +1,5 @@ middleware = new PhpDebugBarMiddleware($this->debugbarRenderer); } - public function testNotAttachIfNotAccept() + public function testTwoPassCallingForCompatibility(): void { $request = new ServerRequest(); $response = new Response(); @@ -42,92 +43,89 @@ public function testNotAttachIfNotAccept() $this->assertSame($response, $result); } - public function testAttachToNoneHtmlResponse() + public function testNotAttachIfNotAccept(): void + { + $request = new ServerRequest(); + $response = new Response(); + $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 testAttachToNoneHtmlResponse(): void { $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); $response = new Response(); $response->getBody()->write('ResponseBody'); - $calledOut = false; - $outFunction = function ($request, $response) use (&$calledOut) { - $calledOut = true; - return $response; - }; + + $requestHandler = new RequestHandlerStub($response); $this->debugbarRenderer->expects($this->once())->method('renderHead')->willReturn('RenderHead'); $this->debugbarRenderer->expects($this->once())->method('render')->willReturn('RenderBody'); - $result = call_user_func($this->middleware, $request, $response, $outFunction); + $result = $this->middleware->process($request, $requestHandler); - $this->assertTrue($calledOut, 'Out is not called'); + $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()); } - public function testAttachToHtmlResponse() + public function testAttachToHtmlResponse(): void { $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); $response = new Response('php://memory', 200, ['Content-Type' => 'text/html']); $response->getBody()->write('ResponseBody'); - $calledOut = false; - $outFunction = function ($request, $response) use (&$calledOut) { - $calledOut = true; - return $response; - }; + $requestHandler = new RequestHandlerStub($response); $this->debugbarRenderer->expects($this->once())->method('renderHead')->willReturn('RenderHead'); $this->debugbarRenderer->expects($this->once())->method('render')->willReturn('RenderBody'); - $result = call_user_func($this->middleware, $request, $response, $outFunction); + $result = $this->middleware->process($request, $requestHandler); - $this->assertTrue($calledOut, 'Out is not called'); + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); $this->assertSame($response, $result); $this->assertSame("ResponseBodyRenderHeadRenderBody", (string) $result->getBody()); } - public function testAppendsToEndOfHtmlResponse() + public function testAppendsToEndOfHtmlResponse(): void { $html = 'FooContent'; $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); $response = new Response\HtmlResponse($html); - $calledOut = false; - $outFunction = function ($request, $response) use (&$calledOut) { - $calledOut = true; - return $response; - }; + $requestHandler = new RequestHandlerStub($response); $this->debugbarRenderer->expects($this->once())->method('renderHead')->willReturn('RenderHead'); $this->debugbarRenderer->expects($this->once())->method('render')->willReturn('RenderBody'); - $result = call_user_func($this->middleware, $request, $response, $outFunction); + $result = $this->middleware->process($request, $requestHandler); - $this->assertTrue($calledOut, 'Out is not called'); + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); $this->assertSame($response, $result); $this->assertSame($html . 'RenderHeadRenderBody', (string) $result->getBody()); } - public function testTryToHandleNotExistingStaticFile() + 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(''); + $requestHandler = new RequestHandlerStub($response); - $calledOut = false; - $outFunction = function ($request, $response) use (&$calledOut) { - $calledOut = true; - return $response; - }; + $result = $this->middleware->process($request, $requestHandler); - $result = call_user_func($this->middleware, $request, $response, $outFunction); - $this->assertTrue($calledOut, 'Out is not called'); + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); $this->assertSame($response, $result); } /** * @dataProvider getContentTypes */ - public function testHandleStaticFile($extension, $contentType) + public function testHandleStaticFile(string $extension, string $contentType): void { $root = vfsStream::setup('boo'); @@ -140,20 +138,17 @@ public function testHandleStaticFile($extension, $contentType) vfsStream::newFile(sprintf('debugbar.%s', $extension))->withContent('filecontent')->at($root); - $calledOut = false; - $outFunction = function ($request, $response) use (&$calledOut) { - $calledOut = true; - return $response; - }; + $requestHandler = new RequestHandlerStub($response); - $result = call_user_func($this->middleware, $request, $response, $outFunction); - $this->assertFalse($calledOut, 'Out is called'); + $result = $this->middleware->process($request, $requestHandler); + + $this->assertFalse($requestHandler->isCalled(), 'Request handler is called'); $this->assertNotSame($response, $result); $this->assertSame($contentType, $result->getHeaderLine('Content-type')); $this->assertSame('filecontent', (string) $result->getBody()); } - public function getContentTypes() + public function getContentTypes(): array { return [ ['css', 'text/css'], diff --git a/test/RequestHandlerStub.php b/test/RequestHandlerStub.php new file mode 100644 index 0000000..2fb41da --- /dev/null +++ b/test/RequestHandlerStub.php @@ -0,0 +1,32 @@ +response = $response; + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + $this->called = true; + + return $this->response; + } + + public function isCalled(): bool + { + return $this->called; + } +} \ No newline at end of file diff --git a/test/Slim3Test.php b/test/Slim3Test.php index fc67b7e..26959b0 100644 --- a/test/Slim3Test.php +++ b/test/Slim3Test.php @@ -1,14 +1,16 @@ getContainer()['environment'] = function() use ($server) { diff --git a/test/TestEmitter.php b/test/TestEmitter.php index 6bc5b18..7fe122a 100644 --- a/test/TestEmitter.php +++ b/test/TestEmitter.php @@ -1,23 +1,24 @@ response = $response; - return $response; + return true; } - public function getResponse() + public function getResponse(): ResponseInterface { if ($this->response instanceof ResponseInterface) { return $this->response; diff --git a/test/ZendExpressiveTest.php b/test/ZendExpressiveTest.php index 7456ed9..52bdaea 100644 --- a/test/ZendExpressiveTest.php +++ b/test/ZendExpressiveTest.php @@ -1,26 +1,50 @@ dispatchApplication([ 'REQUEST_URI' => '/hello', 'REQUEST_METHOD' => 'GET', 'HTTP_ACCEPT' => 'text/html', ], [ - '/hello' => function (ServerRequestInterface $request, ResponseInterface $response, $next) { + '/hello' => function (ServerRequestInterface $request) { + $response = new Response(); $response->getBody()->write('Hello!'); return $response; }, @@ -31,38 +55,51 @@ final public function testContainsConfigCollectorOutput() $this->assertContains('DebugBar\\\DataCollector\\\ConfigCollector', $responseBody); } - protected function dispatchApplication(array $server, array $pipe = []) + protected function dispatchApplication(array $server, array $pipe = []): ResponseInterface { - $container = $this->createContainer(); + $container = $this->createContainer($server); $appFactory = new ApplicationFactory(); $app = $appFactory($container); + $app->pipe(RouteMiddleware::class); + + $app->pipe(PhpDebugBarMiddleware::class); + + $app->pipe(DispatchMiddleware::class); + foreach ($pipe as $pattern => $middleware) { $app->get($pattern, $middleware); } - $app->pipeRoutingMiddleware(); - $app->pipeDispatchMiddleware(); - - $serverRequest = ServerRequestFactory::fromGlobals($server); - - $app->run($serverRequest); + $app->run(); return $container->get(EmitterInterface::class)->getResponse(); } - /** - * - * @return ContainerInterface - */ - private function createContainer() + private function createContainer(array $server): ContainerInterface { $config = ConfigProvider::getConfig(); + $config['debug'] = true; $serviceManagerConfig = $config['dependencies']; $serviceManagerConfig['services']['config'] = $config; $serviceManagerConfig['services'][EmitterInterface::class] = new TestEmitter(); + $serviceManagerConfig['services'][ServerRequestInterface::class] = function() use ($server) { + return ServerRequestFactory::fromGlobals($server, [], [], [], []); + }; + $serviceManagerConfig['factories'][MiddlewareFactory::class] = MiddlewareFactoryFactory::class; + $serviceManagerConfig['factories'][MiddlewareContainer::class] = MiddlewareContainerFactory::class; + $serviceManagerConfig['factories'][MiddlewarePipe::class] = InvokableFactory::class; + $serviceManagerConfig['factories'][RouteCollector::class] = RouteCollectorFactory::class; + $serviceManagerConfig['factories'][FastRouteRouter::class] = FastRouteRouterFactory::class; + $serviceManagerConfig['factories'][RequestHandlerRunner::class] = RequestHandlerRunnerFactory::class; + $serviceManagerConfig['factories'][ServerRequestErrorResponseGenerator::class] = ServerRequestErrorResponseGeneratorFactory::class; + $serviceManagerConfig['factories'][ResponseInterface::class] = ResponseFactoryFactory::class; + $serviceManagerConfig['factories'][RouteMiddleware::class] = RouteMiddlewareFactory::class; + $serviceManagerConfig['factories'][DispatchMiddleware::class] = DispatchMiddlewareFactory::class; + $serviceManagerConfig['aliases'][RouterInterface::class] = FastRouteRouter::class; + $serviceManagerConfig['aliases'][\Zend\Expressive\ApplicationPipeline::class] = MiddlewarePipe::class; return new ServiceManager($serviceManagerConfig); } From 4883713935e3c39d4030b343a348803858328ce3 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 11 Apr 2018 23:08:00 +0200 Subject: [PATCH 27/40] Fixes --- .travis.yml | 1 - README.md | 10 ++++++++-- composer.json | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8209ccd..c9528a5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,7 +10,6 @@ env: before_script: - phpenv config-rm xdebug.ini - - composer self-update - if [[ $DEPS == 'lowest' ]]; then composer update --prefer-stable --no-interaction --prefer-lowest ; fi - if [[ $DEPS == 'latest' ]]; then composer update --prefer-stable --no-interaction ; fi diff --git a/README.md b/README.md index 85bb850..3abdfb7 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # 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]([PSR-7](https://www.php-fig.org/psr/psr-11/)) +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/) This middleware provide framework-agnostic possibility to attach [PHP Debug Bar](http://phpdebugbar.com/) to your response (html on non-html!). @@ -30,7 +30,13 @@ You don't need to copy any static assets from phpdebugbar vendor! ### How to install on Zend Expressive? -[Follow Zend Expressive documentation](https://docs.zendframework.com/zend-expressive/v3/features/modular-applications/). +You need to register ConfigProvider and pipe provided middleware: + +```php +$app->pipe(PhpDebugBarMiddleware::class); +``` + +For more follow Zend Expressive [documentation](https://docs.zendframework.com/zend-expressive/v3/features/modular-applications/). ### How to install on Slim 3? diff --git a/composer.json b/composer.json index 496df0c..38f8648 100644 --- a/composer.json +++ b/composer.json @@ -25,7 +25,7 @@ "slim/slim": "^3.0", "zendframework/zend-expressive": "^3.0", "zendframework/zend-expressive-fastroute": "^3.0.1", - "zendframework/zend-servicemanager": "^3.3" + "zendframework/zend-servicemanager": "^3.3.2" }, "autoload": { "psr-4": { From 0fe14973084767d9dea3ea51d5b51bffd939d56e Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 11 Apr 2018 23:11:38 +0200 Subject: [PATCH 28/40] Enable travis deps cache --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index c9528a5..f2ad2f7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,7 @@ +cache: + directories: + - $HOME/.composer/cache/files + language: php php: From 48bcd9cd1cab9b4be709417bea8a359088182df5 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 11 Apr 2018 23:13:25 +0200 Subject: [PATCH 29/40] Update composer --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 38f8648..2eabc37 100644 --- a/composer.json +++ b/composer.json @@ -8,7 +8,8 @@ "middleware", "psr", "psr-7", - "psr-15" + "psr-15", + "psr-11" ], "require": { "php": "^7.1", From 6c2c461b726d36fdbb16498e3d3577948275865c Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Thu, 26 Apr 2018 13:29:22 +0200 Subject: [PATCH 30/40] Disable and enable debug bar (#21) * Disable and enable debug bar using header, cookie, attribute * Disable debug bar on redirect responses --- README.md | 9 ++ src/ConfigProvider.php | 3 +- src/JavascriptRendererFactory.php | 3 +- src/PhpDebugBarMiddleware.php | 97 +++++------- src/PhpDebugBarMiddlewareFactory.php | 3 +- src/ResponseInjector/AlwaysInjector.php | 40 ----- .../ResponseInjectorInterface.php | 15 -- src/StandardDebugBarFactory.php | 2 +- test/PhpDebugBarMiddlewareTest.php | 139 ++++++++++++++++-- 9 files changed, 181 insertions(+), 130 deletions(-) delete mode 100644 src/ResponseInjector/AlwaysInjector.php delete mode 100644 src/ResponseInjector/ResponseInjectorInterface.php diff --git a/README.md b/README.md index 3abdfb7..0e4cd82 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,15 @@ $app->run($request, $response); 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: +* 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. + ### How to install on Zend Expressive? You need to register ConfigProvider and pipe provided middleware: diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 018c386..fd20daa 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -7,8 +7,7 @@ final class ConfigProvider { public static function getConfig(): array { - $self = new self(); - return $self(); + return (new self())(); } public function __invoke(): array diff --git a/src/JavascriptRendererFactory.php b/src/JavascriptRendererFactory.php index 5d961cd..6fa7ec4 100644 --- a/src/JavascriptRendererFactory.php +++ b/src/JavascriptRendererFactory.php @@ -12,8 +12,7 @@ final class JavascriptRendererFactory public function __invoke(ContainerInterface $container = null): JavascriptRenderer { if ($container === null || !$container->has(DebugBar::class)) { - $standardDebugBarFactory = new StandardDebugBarFactory(); - $debugbar = $standardDebugBarFactory($container); + $debugbar = (new StandardDebugBarFactory())($container); } else { $debugbar = $container->get(DebugBar::class); } diff --git a/src/PhpDebugBarMiddleware.php b/src/PhpDebugBarMiddleware.php index c29defd..5331054 100644 --- a/src/PhpDebugBarMiddleware.php +++ b/src/PhpDebugBarMiddleware.php @@ -5,13 +5,13 @@ use DebugBar\JavascriptRenderer as DebugBarRenderer; use Psr\Http\Message\MessageInterface; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\ResponseInterface as Response; +use Psr\Http\Message\ServerRequestInterface as ServerRequest; use Psr\Http\Message\UriInterface; use Psr\Http\Server\MiddlewareInterface; -use Psr\Http\Server\RequestHandlerInterface; -use Slim\Http\Uri; -use Zend\Diactoros\Response; +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; @@ -23,6 +23,8 @@ */ final class PhpDebugBarMiddleware implements MiddlewareInterface { + public const FORCE_KEY = 'X-Enable-Debug-Bar'; + protected $debugBarRenderer; public function __construct(DebugBarRenderer $debugbarRenderer) @@ -33,7 +35,7 @@ public function __construct(DebugBarRenderer $debugbarRenderer) /** * @inheritDoc */ - public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + public function process(ServerRequest $request, RequestHandler $handler): Response { if ($staticFile = $this->getStaticFile($request->getUri())) { return $staticFile; @@ -41,7 +43,13 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $response = $handler->handle($request); - if (!$this->isHtmlAccepted($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)))) { return $response; } @@ -51,19 +59,19 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface return $this->prepareHtmlResponseWithDebugBar($response); } - public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface + public function __invoke(ServerRequest $request, Response $response, callable $next): Response { - $handler = new class($next, $response) implements RequestHandlerInterface { + $handler = new class($next, $response) implements RequestHandler { private $next; private $response; - public function __construct(callable $next, ResponseInterface $response) + public function __construct(callable $next, Response $response) { $this->next = $next; $this->response = $response; } - public function handle(ServerRequestInterface $request): ResponseInterface + public function handle(ServerRequest $request): Response { return ($this->next)($request, $this->response); } @@ -71,10 +79,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface return $this->process($request, $handler); } - /** - * @return HtmlResponse - */ - private function prepareHtmlResponseWithDebugBar(ResponseInterface $response) + private function prepareHtmlResponseWithDebugBar(Response $response): HtmlResponse { $head = $this->debugBarRenderer->renderHead(); $body = $this->debugBarRenderer->render(); @@ -86,10 +91,7 @@ private function prepareHtmlResponseWithDebugBar(ResponseInterface $response) return new HtmlResponse($result); } - /** - * @return ResponseInterface - */ - private function attachDebugBarToResponse(ResponseInterface $response) + private function attachDebugBarToResponse(Response $response): Response { $head = $this->debugBarRenderer->renderHead(); $body = $this->debugBarRenderer->render(); @@ -103,15 +105,12 @@ private function attachDebugBarToResponse(ResponseInterface $response) return $response; } - /** - * @return ResponseInterface|null - */ - private function getStaticFile(UriInterface $uri) + private function getStaticFile(UriInterface $uri): ?Response { $path = $this->extractPath($uri); if (strpos($path, $this->debugBarRenderer->getBaseUrl()) !== 0) { - return; + return null; } $pathToFile = substr($path, strlen($this->debugBarRenderer->getBaseUrl())); @@ -119,26 +118,21 @@ private function getStaticFile(UriInterface $uri) $fullPathToFile = $this->debugBarRenderer->getBasePath() . $pathToFile; if (!file_exists($fullPathToFile)) { - return; + return null; } $contentType = $this->getContentTypeByFileName($fullPathToFile); $stream = new Stream($fullPathToFile, 'r'); - return new Response($stream, 200, [ + return new DiactorosResponse($stream, 200, [ 'Content-type' => $contentType, ]); } - /** - * @param UriInterface $uri - * - * @return string - */ - private function extractPath(UriInterface $uri) + private function extractPath(UriInterface $uri): string { // Slim3 compatibility - if ($uri instanceof Uri) { + if ($uri instanceof SlimUri) { $basePath = $uri->getBasePath(); if (!empty($basePath)) { return $basePath; @@ -147,12 +141,7 @@ private function extractPath(UriInterface $uri) return $uri->getPath(); } - /** - * @param string $filename - * - * @return string - */ - private function getContentTypeByFileName($filename) + private function getContentTypeByFileName(string $filename): string { $ext = pathinfo($filename, PATHINFO_EXTENSION); @@ -170,35 +159,25 @@ private function getContentTypeByFileName($filename) return isset($map[$ext]) ? $map[$ext] : 'text/plain'; } - /** - * @param ResponseInterface $response - * - * @return bool - */ - private function isHtmlResponse(ResponseInterface $response) + private function isHtmlResponse(Response $response): bool { return $this->hasHeaderContains($response, 'Content-Type', 'text/html'); } - /** - * @param ServerRequestInterface $request - * - * @return bool - */ - private function isHtmlAccepted(ServerRequestInterface $request) + private function isHtmlAccepted(ServerRequest $request): bool { return $this->hasHeaderContains($request, 'Accept', 'text/html'); } - /** - * @param MessageInterface $message - * @param string $headerName - * @param string $value - * - * @return bool - */ - private function hasHeaderContains(MessageInterface $message, $headerName, $value) + private function hasHeaderContains(MessageInterface $message, string $headerName, string $value): bool { return strpos($message->getHeaderLine($headerName), $value) !== false; } + + private function isRedirect(Response $response): bool + { + $statusCode = $response->getStatusCode(); + + return ($statusCode >= 300 || $statusCode < 400) && $response->getHeaderLine('Location') !== ''; + } } diff --git a/src/PhpDebugBarMiddlewareFactory.php b/src/PhpDebugBarMiddlewareFactory.php index 8135d75..27dfea3 100644 --- a/src/PhpDebugBarMiddlewareFactory.php +++ b/src/PhpDebugBarMiddlewareFactory.php @@ -11,8 +11,7 @@ final class PhpDebugBarMiddlewareFactory public function __invoke(ContainerInterface $container = null): PhpDebugBarMiddleware { if ($container === null || !$container->has(JavascriptRenderer::class)) { - $rendererFactory = new JavascriptRendererFactory(); - $renderer = $rendererFactory($container); + $renderer = (new JavascriptRendererFactory())($container); } else { $renderer = $container->get(JavascriptRenderer::class); } diff --git a/src/ResponseInjector/AlwaysInjector.php b/src/ResponseInjector/AlwaysInjector.php deleted file mode 100644 index 1b84a42..0000000 --- a/src/ResponseInjector/AlwaysInjector.php +++ /dev/null @@ -1,40 +0,0 @@ -renderHead(); - $debugBarBody = $debugBarRenderer->render(); - - if ($this->isHtmlResponse($outResponse)) { - $body = $outResponse->getBody(); - if (! $body->eof() && $body->isSeekable()) { - $body->seek(0, SEEK_END); - } - $body->write($debugBarHead . $debugBarBody); - - return $outResponse; - } - - $outResponseBody = Serializer::toString($outResponse); - $template = '%s

DebugBar

Response:

%s
%s'; - $escapedOutResponseBody = htmlspecialchars($outResponseBody); - $result = sprintf($template, $debugBarHead, $escapedOutResponseBody, $debugBarBody); - - return new HtmlResponse($result); - } - - private function isHtmlResponse(ResponseInterface $response): bool - { - return $this->hasHeaderContains($response, 'Content-Type', 'text/html'); - } -} diff --git a/src/ResponseInjector/ResponseInjectorInterface.php b/src/ResponseInjector/ResponseInjectorInterface.php deleted file mode 100644 index 2c1910e..0000000 --- a/src/ResponseInjector/ResponseInjectorInterface.php +++ /dev/null @@ -1,15 +0,0 @@ - - */ -interface ResponseInjectorInterface -{ - public function injectPhpDebugBar(ResponseInterface $response, JavascriptRenderer $debugBar): ResponseInterface; -} diff --git a/src/StandardDebugBarFactory.php b/src/StandardDebugBarFactory.php index aedfb83..b21ac63 100644 --- a/src/StandardDebugBarFactory.php +++ b/src/StandardDebugBarFactory.php @@ -15,7 +15,7 @@ public function __invoke(ContainerInterface $container = null): StandardDebugBar if ($container !== null) { $config = $container->has('config') ? $container->get('config') : []; - $collectors = isset($config['phpmiddleware']['phpdebugbar']['collectors']) ? $config['phpmiddleware']['phpdebugbar']['collectors'] : []; + $collectors = $config['phpmiddleware']['phpdebugbar']['collectors'] ?: []; foreach ($collectors as $collectorName) { $collector = $container->get($collectorName); diff --git a/test/PhpDebugBarMiddlewareTest.php b/test/PhpDebugBarMiddlewareTest.php index f405259..9f912c7 100644 --- a/test/PhpDebugBarMiddlewareTest.php +++ b/test/PhpDebugBarMiddlewareTest.php @@ -24,6 +24,9 @@ class PhpDebugBarMiddlewareTest extends TestCase protected function setUp() { $this->debugbarRenderer = $this->getMockBuilder(JavascriptRenderer::class)->disableOriginalConstructor()->getMock(); + $this->debugbarRenderer->method('renderHead')->willReturn('RenderHead'); + $this->debugbarRenderer->method('render')->willReturn('RenderBody'); + $this->middleware = new PhpDebugBarMiddleware($this->debugbarRenderer); } @@ -31,6 +34,7 @@ public function testTwoPassCallingForCompatibility(): void { $request = new ServerRequest(); $response = new Response(); + $response->getBody()->write('ResponseBody'); $calledOut = false; $outFunction = function ($request, $response) use (&$calledOut) { $calledOut = true; @@ -40,6 +44,7 @@ public function testTwoPassCallingForCompatibility(): void $result = call_user_func($this->middleware, $request, $response, $outFunction); $this->assertTrue($calledOut, 'Out is not called'); + $this->assertSame('ResponseBody', (string) $result->getBody()); $this->assertSame($response, $result); } @@ -47,14 +52,54 @@ public function testNotAttachIfNotAccept(): void { $request = new ServerRequest(); $response = new Response(); + $response->getBody()->write('ResponseBody'); $requestHandler = new RequestHandlerStub($response); $result = $this->middleware->process($request, $requestHandler); $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); + $this->assertSame('ResponseBody', (string) $result->getBody()); $this->assertSame($response, $result); } + public function testForceAttachDebugbarIfHeaderPresents(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'application/json', 'X-Enable-Debug-Bar' => 'true']); + $response = new Response(); + $response->getBody()->write('ResponseBody'); + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 200 OK\r\n\r\nResponseBody
RenderBody", (string) $result->getBody()); + } + + public function testForceAttachDebugbarIfCookiePresents(): void + { + $cookies = ['X-Enable-Debug-Bar' => 'true']; + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'application/json'], $cookies); + $response = new Response(); + $response->getBody()->write('ResponseBody'); + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 200 OK\r\n\r\nResponseBody
RenderBody", (string) $result->getBody()); + } + + public function testForceAttachDebugbarIfAttributePresents(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'application/json']); + $request = $request->withAttribute('X-Enable-Debug-Bar', 'true'); + $response = new Response(); + $response->getBody()->write('ResponseBody'); + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 200 OK\r\n\r\nResponseBody
RenderBody", (string) $result->getBody()); + } + public function testAttachToNoneHtmlResponse(): void { $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); @@ -63,9 +108,6 @@ public function testAttachToNoneHtmlResponse(): void $requestHandler = new RequestHandlerStub($response); - $this->debugbarRenderer->expects($this->once())->method('renderHead')->willReturn('RenderHead'); - $this->debugbarRenderer->expects($this->once())->method('render')->willReturn('RenderBody'); - $result = $this->middleware->process($request, $requestHandler); $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); @@ -73,6 +115,47 @@ public function testAttachToNoneHtmlResponse(): void $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 200 OK\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'); + + $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 testAttachToRedirectResponseWithoutLocation(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); + $response = (new Response())->withStatus(302); + + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); + $this->assertNotSame($response, $result); + $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 302 Found\r\n\r\n
RenderBody", (string) $result->getBody()); + } + + public function testForceAttachToRedirectResponse(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html', 'X-Enable-Debug-Bar' => 'true']); + $response = (new Response())->withStatus(302)->withAddedHeader('Location', 'some-location'); + + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); + $this->assertNotSame($response, $result); + $this->assertSame("RenderHead

DebugBar

Response:

HTTP/1.1 302 Found\r\nLocation: some-location\r\n\r\n
RenderBody", (string) $result->getBody()); + } + public function testAttachToHtmlResponse(): void { $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); @@ -80,14 +163,55 @@ public function testAttachToHtmlResponse(): void $response->getBody()->write('ResponseBody'); $requestHandler = new RequestHandlerStub($response); - $this->debugbarRenderer->expects($this->once())->method('renderHead')->willReturn('RenderHead'); - $this->debugbarRenderer->expects($this->once())->method('render')->willReturn('RenderBody'); + $result = $this->middleware->process($request, $requestHandler); + + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); + $this->assertSame($response, $result); + $this->assertSame('ResponseBodyRenderHeadRenderBody', (string) $result->getBody()); + } + + public function testForceNotAttachDebugbarIfHeaderPresents(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html', 'X-Enable-Debug-Bar' => 'false']); + $response = new Response('php://memory', 200, ['Content-Type' => 'text/html']); + $response->getBody()->write('ResponseBody'); + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); + $this->assertSame($response, $result); + $this->assertSame('ResponseBody', (string) $result->getBody()); + } + + public function testForceNotAttachDebugbarIfCookiePresents(): void + { + $cookie = ['X-Enable-Debug-Bar' => 'false']; + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html'], $cookie); + $response = new Response('php://memory', 200, ['Content-Type' => 'text/html']); + $response->getBody()->write('ResponseBody'); + $requestHandler = new RequestHandlerStub($response); $result = $this->middleware->process($request, $requestHandler); $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); $this->assertSame($response, $result); - $this->assertSame("ResponseBodyRenderHeadRenderBody", (string) $result->getBody()); + $this->assertSame('ResponseBody', (string) $result->getBody()); + } + + public function testForceNotAttachDebugbarIfAttributePresents(): void + { + $request = new ServerRequest([], [], null, null, 'php://input', ['Accept' => 'text/html']); + $request = $request->withAttribute('X-Enable-Debug-Bar', 'false'); + $response = new Response('php://memory', 200, ['Content-Type' => 'text/html']); + $response->getBody()->write('ResponseBody'); + $requestHandler = new RequestHandlerStub($response); + + $result = $this->middleware->process($request, $requestHandler); + + $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); + $this->assertSame($response, $result); + $this->assertSame('ResponseBody', (string) $result->getBody()); } public function testAppendsToEndOfHtmlResponse(): void @@ -97,9 +221,6 @@ public function testAppendsToEndOfHtmlResponse(): void $response = new Response\HtmlResponse($html); $requestHandler = new RequestHandlerStub($response); - $this->debugbarRenderer->expects($this->once())->method('renderHead')->willReturn('RenderHead'); - $this->debugbarRenderer->expects($this->once())->method('render')->willReturn('RenderBody'); - $result = $this->middleware->process($request, $requestHandler); $this->assertTrue($requestHandler->isCalled(), 'Request handler is not called'); From 160e7920eaadb6127657784ce2b1d44ba01a81c5 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Tue, 9 Oct 2018 11:07:32 +0200 Subject: [PATCH 31/40] 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 32/40] 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 33/40] 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 34/40] 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 35/40] 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 36/40] 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 37/40] 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 38/40] 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 39/40] 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 40/40] 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 = [];