diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e23604..3a9eb55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ This project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased](https://github.com/orca-services/cakephp-app-version) ### Added +- More ways to expose the app version, all reading `App.version` [#18](https://github.com/orca-services/cakephp-app-version/issues/18): + - `AppVersion` view helper with `get()`, `getUrlEncoded()` and `meta()` + - Version endpoint controller serving JSON, XML or HTML depending on the extension, e.g. `GET /app-version.json` + - `bin/cake app_version` CLI command + - `AppVersion::extractVersion()` to read the app version from a `VERSION` file ### Changed diff --git a/README.md b/README.md index 48293cc..c516d7f 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,17 @@ # CakePHP App Version Plugin -A CakePHP plugin for adding a configurable app version as an HTTP header. +A CakePHP plugin for exposing a configurable app version as an HTTP header, in views (helper, meta tag), via an +endpoint (as JSON, XML or HTML) and on the CLI. ## Compatibility | Plugin Version | CakePHP Compatibility | Branch | Status | -|----------------|-----------------------|-------------| --------- | +|----------------|-----------------------|-------------|-----------| | 1.x | 5.x | cakephp-5.x | Supported | | 0.x | 4.x | cakephp-4.x | Supported | Note: + - There is no plugin version for CakePHP 3.x. - Previous versions of the plugin that supported previous versions of CakePHP are not supported anymore. diff --git a/composer.json b/composer.json index 21a1f29..f76c85c 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,15 @@ { "name": "orca-services/cakephp-app-version", - "description": "A CakePHP plugin for adding a configurable app version as an HTTP header", - "keywords": ["CakePHP", "Plugin", "HTTP", "Headers", "Application version"], + "description": "A CakePHP plugin for exposing a configurable app version as an HTTP header, in views, via an endpoint and on the CLI", + "keywords": [ + "CakePHP", + "Plugin", + "HTTP", + "Headers", + "Application version", + "View helper", + "CLI" + ], "type": "cakephp-plugin", "homepage": "https://github.com/orca-services/cakephp-app-version", "license": "MIT", diff --git a/docs/Configuration.md b/docs/Configuration.md index d84d6f7..f33fbc3 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -1,13 +1,16 @@ # Configuration -The plugin reads two values from CakePHP's `Configure` registry: +## App version -| Key | Purpose | Default | +All outputs of the plugin read the version from CakePHP's `Configure` registry. +`App.version` is the **single source of truth**: + +| Key | Purpose | Fallback | |---------------------|---------------------------------------|-------------| | `App.version` | The version string to expose | `"Unknown"` | | `App.versionPrefix` | The vendor prefix for the header name | `"X"` | -Set them in `config/app.php` (or `config/app_local.php`): +Set them in `config/app.php` (or `config/app_local.php`), like so: ```php 'App' => [ @@ -16,23 +19,28 @@ Set them in `config/app.php` (or `config/app_local.php`): ], ``` -This will produce the HTTP response header: +With the [header middleware](Usage.md#http-response-header) this will add a HTTP response header: ``` Acme-App-Version: 1.2.3 ``` -To keep the version in sync with your release process, read it dynamically in `config/bootstrap.php`, for example from a `VERSION` file: +To keep the version in sync with your release process, read it dynamically in `config/bootstrap.php` +from a version file: ```php -Configure::write( - 'App.version', - trim((string)@file_get_contents(ROOT . DS . 'VERSION')) ?: 'Unknown' -); +use AppVersion\AppVersion; + +Configure::write('App.version', AppVersion::extractVersion()); ``` +By default, `AppVersion::extractVersion()` reads the `VERSION` file in your application's root directory +(`AppVersion::DEFAULT_VERSION_FILE`) and removes leading and trailing whitespace. +Pass another path to read a different file, e.g. `AppVersion::extractVersion(CONFIG . 'version.txt')`. +If the file is missing, unreadable or empty, `"Unknown"` is returned. + Make sure this runs before the middleware queue is built. --- -Back to the [Documentation](../README.md). +Continue with the [usage](./Usage.md) or Back to the [documentation](../README.md). diff --git a/docs/Installation.md b/docs/Installation.md index 632d84a..d653b43 100644 --- a/docs/Installation.md +++ b/docs/Installation.md @@ -2,8 +2,8 @@ ### Requirements -- PHP >= 7.4 -- CakePHP 4.x +- PHP >= 8.2 +- CakePHP >= 5.3.6 ### CakePHP Version Support @@ -17,15 +17,21 @@ First, require the package through Composer: composer require orca-services/cakephp-app-version ```` -Then load the plugin in your application as documented in the section -[Loading a Plugin](https://book.cakephp.org/4.x/plugins.html#loading-a-plugin) +Then load the plugin in your application with the plugin load command: + +```` +php bin/cake.php plugin load AppVersion +```` + +Alternatively, load it manually as documented in the section +[Loading a Plugin](https://book.cakephp.org/5.x/plugins.html#loading-a-plugin) in the CakePHP CookBook. ### Installation alternatives Refer to the CakePHP CookBook section -[Manually Installing a Plugin](https://book.cakephp.org/4.x/plugins.html#manually-installing-a-plugin). +[Manually Installing a Plugin](https://book.cakephp.org/5.x/plugins.html#manually-installing-a-plugin). --- -Back to the [Documentation](../README.md). +Continue with the [configuration](./Configuration.md) or Back to the [documentation](../README.md). diff --git a/docs/Usage.md b/docs/Usage.md index 6fc501a..259605d 100644 --- a/docs/Usage.md +++ b/docs/Usage.md @@ -1,6 +1,21 @@ # Usage -Once the plugin is installed and loaded (see [Installation](Installation.md)), add the middleware to your middleware queue in `src/Application.php`: +Once the plugin is [installed and loaded](Installation.md), the app version can be exposed in several ways. + +All of them read the same `App.version` value from the [configuration](Configuration.md). +If `App.version` is not set, all of them return `"Unknown"` instead. + +| Output | Example | Available | +|-----------------------------------------------|-----------------------------------------------------|-------------------------------------| +| [HTTP response header](#http-response-header) | `X-App-Version: 1.2.3` | When the middleware is added | +| [View helper](#view-helper) | `$this->AppVersion->get()` → `1.2.3` | When the helper is loaded | +| [HTML meta tag](#html-meta-tag) | `` | When `meta()` is used in a template | +| [Version endpoint](#version-endpoint) | `GET /app-version.json` → `{"app-version":"1.2.3"}` | When you connect its route | +| [CLI command](#cli-command) | `bin/cake app_version` → `1.2.3` | Always | + +## HTTP response header + +Add the app version [middleware](https://book.cakephp.org/5.x/controllers/middleware.html#middleware) to your [middleware queue](https://book.cakephp.org/5.x/controllers/middleware.html#using-middleware) in `src/Application.php`: ```php use AppVersion\Middleware\AppVersionHeaderMiddleware; @@ -18,14 +33,150 @@ public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue Add `AppVersionHeaderMiddleware` **before** `ErrorHandlerMiddleware` if you want the header to be present on error responses as well. -Configure the header value and prefix as described in [Configuration](Configuration.md). - Every response will then include an HTTP header of the form: ``` {Prefix}-App-Version: {Version} ``` +## View helper + +Load the [helper](https://book.cakephp.org/5.x/views/helpers.html#helpers) in your view class, e.g. `src/View/AppView.php`, +and type hint it in the class docblock for IDE autocompletion and static analysis: + +```php +/** + * @property \AppVersion\View\Helper\AppVersionHelper $AppVersion + */ +class AppView extends View +{ + public function initialize(): void + { + parent::initialize(); + + $this->addHelper('AppVersion.AppVersion'); + } +} +``` + +Then use it in your templates, e.g. in a footer: + +```php + + += $this->Html->script('app.js?v=' . $this->AppVersion->getUrlEncoded()) ?> +``` + +`get()` returns the raw version, escape it with [`h()`](https://book.cakephp.org/5.x/core-libraries/global-constants-and-functions.html#h) when printing it in HTML. +`getUrlEncoded()` returns the URL encoded version, e.g. for cache busting query strings. + +## HTML meta tag + +Add an app version [meta tag](https://book.cakephp.org/5.x/views/helpers/html.html#creating-meta-tags) to your [layout](https://book.cakephp.org/5.x/views.html#layouts), e.g. `templates/layout/default.php`: + +```php +
+ = $this->AppVersion->meta() ?> + +``` + +This renders: + +```html + + + +``` + +To append it to the `meta` view block instead, pass `['block' => true]`. + +The version can then be read from frontend code or E2E tests: + +```js +document.querySelector('meta[name="app-version"]')?.content; +``` + +## Version endpoint + +The plugin does not connect any route on its own, so the version endpoint is only available if you connect it +in your [routes](https://book.cakephp.org/5.x/development/routing.html#quick-tour), e.g. in `config/routes.php`: + +```php +$routes->scope('/', function (RouteBuilder $builder): void { + $builder->get( + '/app-version', + ['plugin' => 'AppVersion', 'controller' => 'Version', 'action' => 'show'], + 'AppVersion.version', + )->setExtensions(['json', 'xml', 'html']); +}); +``` + +You are free to choose the connected URL path and route name. You decide in which environments the route is connected. + +The response format depends on the [file extension](https://book.cakephp.org/5.x/development/routing.html#routing-file-extensions): + +``` +$ curl https://example.com/app-version.json +{"app-version":"1.2.3"} + +$ curl https://example.com/app-version.xml + +App version: = h($appVersion) ?>
+ + diff --git a/tests/TestCase/AppVersionPluginTest.php b/tests/TestCase/AppVersionPluginTest.php new file mode 100644 index 0000000..8fafa38 --- /dev/null +++ b/tests/TestCase/AppVersionPluginTest.php @@ -0,0 +1,41 @@ +isEnabled('routes')); + } + + /** + * Test the command is added + * + * @return void + * @covers ::console + */ + public function testConsole(): void + { + $commands = (new AppVersionPlugin())->console(new CommandCollection()); + + self::assertTrue($commands->has('app_version')); + self::assertSame(AppVersionCommand::class, $commands->get('app_version')); + } +} diff --git a/tests/TestCase/AppVersionTest.php b/tests/TestCase/AppVersionTest.php new file mode 100644 index 0000000..08adaeb --- /dev/null +++ b/tests/TestCase/AppVersionTest.php @@ -0,0 +1,133 @@ + + */ + protected array $versionFiles = []; + + /** + * @inheritDoc + */ + public function setUp(): void + { + parent::setUp(); + + Configure::delete('App.version'); + } + + /** + * Test get method + * + * @return void + * @covers ::get + */ + public function testGet(): void + { + Configure::write('App.version', '1.2.3'); + + self::assertSame('1.2.3', AppVersion::get()); + } + + /** + * Test get method when the app version is not set, empty or not scalar + * + * @return void + * @covers ::get + */ + public function testGetNotSet(): void + { + self::assertSame('Unknown', AppVersion::get()); + + Configure::write('App.version', ''); + self::assertSame('Unknown', AppVersion::get()); + + Configure::write('App.version', ['1.2.3']); + self::assertSame('Unknown', AppVersion::get()); + } + + /** + * Test extractVersion method trims the version from the version file + * + * @return void + * @covers ::extractVersion + */ + public function testExtractVersion(): void + { + $versionFile = $this->createVersionFile(" 1.2.3\n"); + + self::assertSame('1.2.3', AppVersion::extractVersion($versionFile)); + } + + /** + * Test extractVersion method when the version file is missing or empty + * + * @return void + * @covers ::extractVersion + */ + public function testExtractVersionMissingOrEmpty(): void + { + self::assertSame('Unknown', AppVersion::extractVersion(TMP . 'missing-version-file')); + self::assertSame('Unknown', AppVersion::extractVersion(TMP)); + self::assertSame('Unknown', AppVersion::extractVersion($this->createVersionFile(" \n"))); + } + + /** + * Test extractVersion method reads `ROOT/VERSION` by default + * + * @return void + * @covers ::extractVersion + */ + public function testExtractVersionDefaultFile(): void + { + self::assertSame(ROOT . DS . 'VERSION', AppVersion::DEFAULT_VERSION_FILE); + + $expected = is_file(AppVersion::DEFAULT_VERSION_FILE) + ? AppVersion::extractVersion(AppVersion::DEFAULT_VERSION_FILE) + : 'Unknown'; + self::assertSame($expected, AppVersion::extractVersion()); + } + + /** + * Create a temporary version file + * + * @param string $content The content of the version file. + * @return string The path of the version file. + */ + protected function createVersionFile(string $content): string + { + $versionFile = (string)tempnam(TMP, 'version'); + file_put_contents($versionFile, $content); + $this->versionFiles[] = $versionFile; + + return $versionFile; + } + + /** + * @inheritDoc + */ + public function tearDown(): void + { + foreach ($this->versionFiles as $versionFile) { + unlink($versionFile); + } + $this->versionFiles = []; + + parent::tearDown(); + } +} diff --git a/tests/TestCase/Command/AppVersionCommandTest.php b/tests/TestCase/Command/AppVersionCommandTest.php new file mode 100644 index 0000000..d6fefdb --- /dev/null +++ b/tests/TestCase/Command/AppVersionCommandTest.php @@ -0,0 +1,107 @@ +out = new StubConsoleOutput(); + $this->err = new StubConsoleOutput(); + $this->io = new ConsoleIo($this->out, $this->err); + } + + /** + * Test the command name + * + * @return void + * @covers ::defaultName + */ + public function testDefaultName(): void + { + self::assertSame('app_version', AppVersionCommand::defaultName()); + } + + /** + * Test execute method + * + * @return void + * @covers ::execute + */ + public function testExecute(): void + { + $result = (new AppVersionCommand())->run([], $this->io); + + self::assertSame(AppVersionCommand::CODE_SUCCESS, $result); + self::assertSame(['1.2.3'], $this->out->messages()); + } + + /** + * Test execute method when the app version is not set + * + * @return void + * @covers ::execute + */ + public function testExecuteAppVersionNotSet(): void + { + Configure::delete('App.version'); + + (new AppVersionCommand())->run([], $this->io); + + self::assertSame(['Unknown'], $this->out->messages()); + } + + /** + * Test execute method with the full option + * + * @return void + * @covers ::execute + */ + public function testExecuteFull(): void + { + Configure::write('debug', false); + + (new AppVersionCommand())->run(['--full'], $this->io); + + $expected = sprintf( + 'PHP %s, CakePHP %s (debug: false), app version 1.2.3', + PHP_VERSION, + Configure::version(), + ); + self::assertSame([$expected], $this->out->messages()); + } +} diff --git a/tests/TestCase/Controller/VersionControllerTest.php b/tests/TestCase/Controller/VersionControllerTest.php new file mode 100644 index 0000000..8eaf21c --- /dev/null +++ b/tests/TestCase/Controller/VersionControllerTest.php @@ -0,0 +1,165 @@ +loadPlugins(['AppVersion' => ['path' => dirname(__DIR__, 3) . DS]]); + } + + /** + * Create the controller for a request + * + * @param string|null $extension The requested file extension. + * @param string $method The HTTP method. + * @return VersionController + */ + protected function createController(?string $extension = null, string $method = 'GET'): VersionController + { + $request = new ServerRequest([ + 'url' => '/app-version' . ($extension ? '.' . $extension : ''), + 'params' => [ + 'plugin' => 'AppVersion', + 'controller' => 'Version', + 'action' => 'show', + '_ext' => $extension, + 'pass' => [], + ], + 'environment' => ['REQUEST_METHOD' => $method], + ]); + + return new VersionController($request); + } + + /** + * Call the show action and render it + * + * @param string|null $extension The requested file extension. + * @return Response + */ + protected function renderShow(?string $extension = null): Response + { + $controller = $this->createController($extension); + $controller->show(); + + return $controller->render(); + } + + /** + * Test show method returns JSON for the json extension + * + * @return void + * @covers ::show + */ + public function testShowJson(): void + { + $response = $this->renderShow('json'); + + self::assertSame(200, $response->getStatusCode()); + self::assertSame('application/json', $response->getType()); + self::assertSame('no-store', $response->getHeaderLine('Cache-Control')); + self::assertSame(['app-version' => '1.2.3'], json_decode((string)$response->getBody(), true)); + } + + /** + * Test show method returns JSON with "Unknown" if the app version is not set + * + * @return void + * @covers ::show + */ + public function testShowJsonAppVersionNotSet(): void + { + Configure::delete('App.version'); + + $response = $this->renderShow('json'); + + self::assertSame(['app-version' => 'Unknown'], json_decode((string)$response->getBody(), true)); + } + + /** + * Test show method returns XML for the .xml extension + * + * @return void + * @covers ::show + */ + public function testShowXml(): void + { + $response = $this->renderShow('xml'); + + self::assertSame(200, $response->getStatusCode()); + self::assertSame('application/xml', $response->getType()); + self::assertSame('no-store', $response->getHeaderLine('Cache-Control')); + self::assertXmlStringEqualsXmlString( + '