diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6d3a5c..834ec4d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,7 @@ on: push: branches: - master + - cake6 pull_request: branches: - '*' @@ -13,10 +14,35 @@ permissions: jobs: testsuite: - uses: ADmad/.github/.github/workflows/testsuite-without-db.yml@master - secrets: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + glide: ['^3.0', '^4.0'] + + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.5' + extensions: mbstring, intl, pdo_sqlite, gd + ini-values: zend.assertions=1 + coverage: pcov + + - name: Install dependencies + run: composer require 'league/glide:${{ matrix.glide }}' --no-interaction --prefer-dist + + - name: Run PHPUnit + run: vendor/bin/phpunit --display-all-issues --fail-on-all-issues --coverage-clover=coverage.xml + + - name: Code Coverage Report + if: matrix.glide == '^4.0' + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} cs-stan: - uses: ADmad/.github/.github/workflows/cs-stan.yml@master + uses: ADmad/.github/.github/workflows/cs-stan.yml@cake6 secrets: inherit diff --git a/README.md b/README.md index 9a9c3f6..061349b 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,13 @@ Load the plugin using CLI: bin/cake plugin load ADmad/Glide ``` +## Upgrading from the CakePHP 5 version + +Protected properties and methods no longer have a leading underscore, following +CakePHP 6 conventions. Update any subclasses accordingly, including overrides of +`$defaultConfig`. Failure event listeners must use `$event->setResult($response)` +instead of returning the response, as shown below. + ## Usage ### Middleware @@ -114,15 +121,16 @@ the middleware will throw a `ADmad\Glide\Exception\SignatureException` exception If a response image could not be generated by the Glide library then by default the middleware will throw a `ADmad\Glide\Exception\ResponseException`. A `Glide.response_failure` event will also be triggered in this case. You can setup a -listener for this event and return a response instance from it. In this case +listener for this event and set a response instance as the event result. In this case that response will be sent to client and `ResponseException` will not be thrown. ```php \Cake\Event\EventManager::instance()->on( \ADmad\Glide\Middleware\GlideMiddleware::RESPONSE_FAILURE_EVENT, function ($event) { - return (new Response()) - ->withFile('/path/to/default-image.jpg'); + $event->setResult( + (new \Cake\Http\Response())->withFile('/path/to/default-image.jpg'), + ); } ); ``` diff --git a/composer.json b/composer.json index 4b42375..1632fae 100644 --- a/composer.json +++ b/composer.json @@ -28,12 +28,12 @@ "issues":"https://github.com/ADmad/cakephp-glide/issues" }, "require": { - "php": ">=8.1", - "cakephp/cakephp": "^5.0", + "php": ">=8.5", + "cakephp/cakephp": "^6.0", "league/glide": "^3.0 || ^4.0" }, "require-dev": { - "phpunit/phpunit": "^10.1 || ^11.5.3 || ^12.1.3 || ^13.0" + "phpunit/phpunit": "^13.0" }, "autoload": { "psr-4": { @@ -46,6 +46,8 @@ "TestApp\\": "tests/test_app/src" } }, + "minimum-stability": "dev", + "prefer-stable": true, "config": { "sort-packages": true, "allow-plugins": { diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 7f5ba23..3188b6a 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,5 +1,5 @@ - + ./tests/TestCase diff --git a/src/Middleware/GlideMiddleware.php b/src/Middleware/GlideMiddleware.php index 7c7ead4..1c22964 100644 --- a/src/Middleware/GlideMiddleware.php +++ b/src/Middleware/GlideMiddleware.php @@ -30,14 +30,14 @@ class GlideMiddleware implements MiddlewareInterface, EventDispatcherInterface use InstanceConfigTrait; - public const RESPONSE_FAILURE_EVENT = 'Glide.response_failure'; + public const string RESPONSE_FAILURE_EVENT = 'Glide.response_failure'; /** * Default config. * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'path' => null, 'cacheTime' => '+1 days', 'server' => [ @@ -59,7 +59,7 @@ class GlideMiddleware implements MiddlewareInterface, EventDispatcherInterface * * @var string */ - protected string $_path = ''; + protected string $path = ''; /** * Constructor. @@ -86,21 +86,21 @@ public function __construct(array $config = [], ?EventManagerInterface $eventMan public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $uri = $request->getUri(); - $this->_path = urldecode($uri->getPath()); + $this->path = urldecode($uri->getPath()); $config = $this->getConfig(); - if ($config['path'] && strpos($this->_path, $config['path']) !== 0) { + if ($config['path'] && strpos($this->path, $config['path']) !== 0) { return $handler->handle($request); } - $this->_checkSignature($request); + $this->checkSignature($request); - $server = $this->_getServer($config['server']); + $server = $this->getServer($config['server']); $modifiedTime = null; if ($config['cacheTime']) { - $return = $this->_checkModified($request, $server); + $return = $this->checkModified($request, $server); if ($return === null) { return $handler->handle($request); } @@ -110,21 +110,21 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $modifiedTime = $return; } - $response = $this->_getResponse($request, $server); + $response = $this->getResponse($request, $server); if ($response === null) { return $handler->handle($request); } if ($config['cacheTime']) { /** @psalm-suppress PossiblyNullArgument */ - $response = $this->_withCacheHeaders( + $response = $this->withCacheHeaders( $response, $config['cacheTime'], $modifiedTime, ); } - $response = $this->_withCustomHeaders($response); + $response = $this->withCustomHeaders($response); return $response; } @@ -135,7 +135,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface * @param callable|array $config Config array or callable. * @return \League\Glide\Server */ - protected function _getServer(callable|array $config): Server + protected function getServer(callable|array $config): Server { if (is_array($config)) { return ServerFactory::create($config); @@ -151,7 +151,7 @@ protected function _getServer(callable|array $config): Server * @throws \ADmad\Glide\Exception\SignatureException * @return void */ - protected function _checkSignature(ServerRequestInterface $request): void + protected function checkSignature(ServerRequestInterface $request): void { if (!$this->getConfig('security.secureUrls')) { return; @@ -160,7 +160,7 @@ protected function _checkSignature(ServerRequestInterface $request): void $signKey = $this->getConfig('security.signKey') ?: Security::getSalt(); try { SignatureFactory::create($signKey)->validateRequest( - $this->_path, + $this->path, $request->getQueryParams(), ); } catch (Exception $exception) { @@ -178,18 +178,18 @@ protected function _checkSignature(ServerRequestInterface $request): void * @param \League\Glide\Server $server Glide server. * @return \Psr\Http\Message\ResponseInterface|int|null */ - protected function _checkModified(ServerRequestInterface $request, Server $server): ResponseInterface|int|null + protected function checkModified(ServerRequestInterface $request, Server $server): ResponseInterface|int|null { try { $modifiedTime = $server->getSource() - ->lastModified($server->getSourcePath($this->_path)); + ->lastModified($server->getSourcePath($this->path)); } catch (Exception $exception) { - return $this->_handleException($request, $exception); + return $this->handleException($request, $exception); } - if ($this->_isNotModified($request, $modifiedTime)) { + if ($this->isNotModified($request, $modifiedTime)) { $response = new Response(['status' => 304]); - $response = $this->_withCustomHeaders($response); + $response = $this->withCustomHeaders($response); return $response->withHeader('Last-Modified', (string)$modifiedTime); } @@ -204,7 +204,7 @@ protected function _checkModified(ServerRequestInterface $request, Server $serve * @param \League\Glide\Server $server Glide server. * @return \Psr\Http\Message\ResponseInterface|null Response instance on success else null */ - protected function _getResponse(ServerRequestInterface $request, Server $server): ?ResponseInterface + protected function getResponse(ServerRequestInterface $request, Server $server): ?ResponseInterface { $queryParams = $request->getQueryParams(); $allowedParams = $this->getConfig('allowedParams'); @@ -219,9 +219,9 @@ protected function _getResponse(ServerRequestInterface $request, Server $server) && $this->getConfig('originalPassThrough') ) { try { - $response = $this->_passThrough($request, $server); + $response = $this->passThrough($request, $server); } catch (Exception $exception) { - return $this->_handleException($request, $exception); + return $this->handleException($request, $exception); } return $response; @@ -234,9 +234,9 @@ protected function _getResponse(ServerRequestInterface $request, Server $server) } try { - $response = $server->getImageResponse($this->_path, $queryParams); + $response = $server->getImageResponse($this->path, $queryParams); } catch (Exception $exception) { - return $this->_handleException($request, $exception); + return $this->handleException($request, $exception); } return $response; @@ -250,10 +250,10 @@ protected function _getResponse(ServerRequestInterface $request, Server $server) * @throws \ADmad\Glide\Exception\ResponseException * @return \Psr\Http\Message\ResponseInterface Response instance */ - protected function _passThrough(ServerRequestInterface $request, Server $server): ?ResponseInterface + protected function passThrough(ServerRequestInterface $request, Server $server): ?ResponseInterface { $source = $server->getSource(); - $path = $server->getSourcePath($this->_path); + $path = $server->getSourcePath($this->path); $resource = $source->readStream($path); $stream = new Stream($resource); @@ -283,7 +283,7 @@ protected function _passThrough(ServerRequestInterface $request, Server $server) * @param string|int $modifiedTime Last modified time of file. * @return bool */ - protected function _isNotModified(ServerRequestInterface $request, string|int $modifiedTime): bool + protected function isNotModified(ServerRequestInterface $request, string|int $modifiedTime): bool { $modifiedSince = $request->getHeaderLine('If-Modified-Since'); if (!$modifiedSince) { @@ -301,7 +301,7 @@ protected function _isNotModified(ServerRequestInterface $request, string|int $m * @param string|int $modifiedTime Modified time. * @return \Psr\Http\Message\ResponseInterface */ - protected function _withCacheHeaders( + protected function withCacheHeaders( ResponseInterface $response, string $cacheTime, string|int $modifiedTime, @@ -323,7 +323,7 @@ protected function _withCacheHeaders( * @param \Psr\Http\Message\ResponseInterface $response The response. * @return \Psr\Http\Message\ResponseInterface */ - protected function _withCustomHeaders(ResponseInterface $response): ResponseInterface + protected function withCustomHeaders(ResponseInterface $response): ResponseInterface { foreach ((array)$this->getConfig('headers') as $key => $value) { $response = $response->withHeader($key, $value); @@ -340,7 +340,7 @@ protected function _withCustomHeaders(ResponseInterface $response): ResponseInte * @throws \ADmad\Glide\Exception\ResponseException * @return \Psr\Http\Message\ResponseInterface|null */ - protected function _handleException(ServerRequestInterface $request, Exception $exception): ?ResponseInterface + protected function handleException(ServerRequestInterface $request, Exception $exception): ?ResponseInterface { $event = $this->dispatchEvent( static::RESPONSE_FAILURE_EVENT, diff --git a/src/View/Helper/GlideHelper.php b/src/View/Helper/GlideHelper.php index 5d87517..3ad887a 100644 --- a/src/View/Helper/GlideHelper.php +++ b/src/View/Helper/GlideHelper.php @@ -34,7 +34,7 @@ class GlideHelper extends Helper * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'baseUrl' => '/images/', 'secureUrls' => false, 'signKey' => null, @@ -45,7 +45,7 @@ class GlideHelper extends Helper * * @var \League\Glide\Urls\UrlBuilder|null */ - protected ?UrlBuilder $_urlBuilder = null; + protected ?UrlBuilder $urlBuilder = null; /** * Creates a formatted IMG element. @@ -97,18 +97,18 @@ public function url(string $path, array $params = []): string public function urlBuilder(?UrlBuilder $urlBuilder = null): UrlBuilder { if ($urlBuilder !== null) { - return $this->_urlBuilder = $urlBuilder; + return $this->urlBuilder = $urlBuilder; } - if (!isset($this->_urlBuilder)) { + if (!isset($this->urlBuilder)) { $config = $this->getConfig(); - $this->_urlBuilder = UrlBuilderFactory::create( + $this->urlBuilder = UrlBuilderFactory::create( $config['baseUrl'], $config['secureUrls'] ? ($config['signKey'] ?: Security::getSalt()) : null, ); } - return $this->_urlBuilder; + return $this->urlBuilder; } } diff --git a/tests/TestCase/Middleware/GlideMiddlewareTest.php b/tests/TestCase/Middleware/GlideMiddlewareTest.php index 5ec726f..d723165 100644 --- a/tests/TestCase/Middleware/GlideMiddlewareTest.php +++ b/tests/TestCase/Middleware/GlideMiddlewareTest.php @@ -7,6 +7,7 @@ use ADmad\Glide\Exception\SignatureException; use ADmad\Glide\Middleware\GlideMiddleware; use Cake\Core\Configure; +use Cake\Event\EventInterface; use Cake\Event\EventManager; use Cake\Http\Response; use Cake\Http\ServerRequest; @@ -28,6 +29,8 @@ class GlideMiddlewareTest extends TestCase public function setUp(): void { + parent::setUp(); + $this->config = [ 'server' => [ 'source' => PLUGIN_ROOT . '/test_app/webroot/upload', @@ -58,6 +61,16 @@ public function testNormalResponse() $this->assertTrue(isset($headers['Content-Length'])); } + public function testDefaultConfig(): void + { + $middleware = new GlideMiddleware($this->config); + + $this->assertSame('/images/', $middleware->getConfig('server.base_url')); + $this->assertSame($this->config['server']['source'], $middleware->getConfig('server.source')); + $this->assertSame('+1 days', $middleware->getConfig('cacheTime')); + $this->assertFalse($middleware->getConfig('security.secureUrls')); + } + public function testServerCallable() { $config = $this->config; @@ -262,7 +275,6 @@ public function testResponseException() Configure::write('debug', false); $this->expectException(ResponseException::class); $middleware->process($request, $this->handler); - Configure::write('debug', true); } public function testExceptionEventListener() @@ -273,12 +285,33 @@ public function testExceptionEventListener() ]); EventManager::instance()->on(GlideMiddleware::RESPONSE_FAILURE_EVENT, function ($event) { - return (new Response()) - ->withFile(PLUGIN_ROOT . '/test_app/webroot/upload/cake-logo.png'); + $event->setResult( + (new Response())->withFile(PLUGIN_ROOT . '/test_app/webroot/upload/cake-logo.png'), + ); }); $response = $middleware->process($request, $this->handler); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/png', $response->getHeaderLine('Content-Type')); } + + public function testStoppedExceptionEvent(): void + { + $eventManager = new EventManager(); + $eventManager->on(GlideMiddleware::RESPONSE_FAILURE_EVENT, function (EventInterface $event): void { + $event->stopPropagation(); + }); + $middleware = new GlideMiddleware($this->config, $eventManager); + $request = ServerRequestFactory::fromGlobals([ + 'REQUEST_URI' => '/images/non-existent.jpg', + ]); + $fallback = new Response(['status' => 418]); + $handler = new TestRequestHandler(function ($receivedRequest) use ($request, $fallback) { + $this->assertSame($request, $receivedRequest); + + return $fallback; + }); + + $this->assertSame($fallback, $middleware->process($request, $handler)); + } } diff --git a/tests/TestCase/View/Helper/GlideHelperTest.php b/tests/TestCase/View/Helper/GlideHelperTest.php index c438d08..afdcd2d 100644 --- a/tests/TestCase/View/Helper/GlideHelperTest.php +++ b/tests/TestCase/View/Helper/GlideHelperTest.php @@ -18,6 +18,8 @@ class GlideHelperTest extends TestCase public function setUp(): void { + parent::setUp(); + $this->request = new ServerRequest(); $this->request = $this->request->withAttribute('webroot', '/'); $this->view = new View($this->request); @@ -45,6 +47,15 @@ public function testUrl() $this->assertStringContainsString('&s=', $result); } + public function testDefaultConfig(): void + { + $helper = new GlideHelper($this->view); + + $this->assertSame('/images/logo.png', $helper->url('logo.png')); + $this->assertFalse($helper->getConfig('secureUrls')); + $this->assertNull($helper->getConfig('signKey')); + } + public function testImage() { $result = $this->helper->image('logo.png', ['w' => 100], ['width' => 100]);