diff --git a/composer.json b/composer.json index cb4fa01..b5bbca9 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,7 @@ } }, "require": { - "php": "~8.4.1 || ~8.5.0", + "php": "~8.4.1 || ~8.5.0 || ~8.6.0", "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", @@ -30,6 +30,7 @@ "laminas/laminas-servicemanager": "^4.5", "laminas/laminas-view": "^3.1", "league/commonmark": "^2.10", + "mezzio/mezzio-laminasviewrenderer": "^3.0", "psr/container": "^2.0", "psr/http-client": "^1.0", "psr/http-factory": "^1.1", diff --git a/composer.lock b/composer.lock index 0ee7ab2..1eae66b 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "78323ab414adf507e8b19ce1ec2b64ec", + "content-hash": "d6378edf257f5ea0bcd144e0d02b5601", "packages": [ { "name": "brick/math", @@ -479,28 +479,28 @@ }, { "name": "laminas/laminas-escaper", - "version": "2.18.0", + "version": "2.19.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-escaper.git", - "reference": "06f211dfffff18d91844c1f55250d5d13c007e18" + "reference": "766b8583bbf64be9d3330e7a075197f54c46f642" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-escaper/zipball/06f211dfffff18d91844c1f55250d5d13c007e18", - "reference": "06f211dfffff18d91844c1f55250d5d13c007e18", + "url": "https://api.github.com/repos/laminas/laminas-escaper/zipball/766b8583bbf64be9d3330e7a075197f54c46f642", + "reference": "766b8583bbf64be9d3330e7a075197f54c46f642", "shasum": "" }, "require": { "ext-ctype": "*", "ext-mbstring": "*", - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" }, "conflict": { "zendframework/zend-escaper": "*" }, "require-dev": { - "infection/infection": "^0.31.0", + "infection/infection": "^0.32.0", "laminas/laminas-coding-standard": "~3.1.0", "phpunit/phpunit": "^11.5.42", "psalm/plugin-phpunit": "^0.19.5", @@ -532,12 +532,12 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2025-10-14T18:31:13+00:00", - "published-time": "2025-10-14T19:13:23+00:00" + "time": "2026-11-10T12:33:38+00:00", + "published-time": "2026-11-10T12:34:26+00:00" }, { "name": "laminas/laminas-eventmanager", @@ -841,30 +841,30 @@ }, { "name": "laminas/laminas-stdlib", - "version": "3.21.0", + "version": "3.22.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-stdlib.git", - "reference": "b1c81514cfe158aadf724c42b34d3d0a8164c096" + "reference": "1053fe6ecbcf6f0352e687eda749ee16ace5cc8b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-stdlib/zipball/b1c81514cfe158aadf724c42b34d3d0a8164c096", - "reference": "b1c81514cfe158aadf724c42b34d3d0a8164c096", + "url": "https://api.github.com/repos/laminas/laminas-stdlib/zipball/1053fe6ecbcf6f0352e687eda749ee16ace5cc8b", + "reference": "1053fe6ecbcf6f0352e687eda749ee16ace5cc8b", "shasum": "" }, "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" }, "conflict": { "zendframework/zend-stdlib": "*" }, "require-dev": { "laminas/laminas-coding-standard": "^3.1.0", - "phpbench/phpbench": "^1.4.1", - "phpunit/phpunit": "^11.5.42", - "psalm/plugin-phpunit": "^0.19.5", - "vimeo/psalm": "^6.13.1" + "phpbench/phpbench": "^1.7.0", + "phpunit/phpunit": "^11.5.57", + "psalm/plugin-phpunit": "^0.19.7", + "vimeo/psalm": "^6.20.10" }, "type": "library", "autoload": { @@ -892,34 +892,35 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2025-10-11T18:13:12+00:00", - "published-time": "2025-10-11T18:14:19+00:00" + "time": "2026-11-09T22:51:17+00:00", + "published-time": "2026-11-09T22:52:04+00:00" }, { "name": "laminas/laminas-translator", - "version": "2.0.0", + "version": "2.1.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-translator.git", - "reference": "0169180f44f3d3273bd9a7b00e23ad6b0b870f17" + "reference": "3d85838296c60be5df0ee577c07e36faa1d32263" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-translator/zipball/0169180f44f3d3273bd9a7b00e23ad6b0b870f17", - "reference": "0169180f44f3d3273bd9a7b00e23ad6b0b870f17", + "url": "https://api.github.com/repos/laminas/laminas-translator/zipball/3d85838296c60be5df0ee577c07e36faa1d32263", + "reference": "3d85838296c60be5df0ee577c07e36faa1d32263", "shasum": "" }, "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" }, "require-dev": { + "laminas/internal-tooling": "^1.0", "laminas/laminas-coding-standard": "~3.1.0", - "phpunit/phpunit": "^11.5.55", - "vimeo/psalm": "^6.16.1" + "phpunit/phpunit": "^11.5.57", + "vimeo/psalm": "^6.20.10" }, "type": "library", "autoload": { @@ -947,25 +948,25 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2026-06-02T11:36:39+00:00", - "published-time": "2026-06-02T11:37:21+00:00" + "time": "2026-11-10T00:27:07+00:00", + "published-time": "2026-11-10T00:27:40+00:00" }, { "name": "laminas/laminas-view", - "version": "3.1.0", + "version": "3.2.0", "source": { "type": "git", "url": "https://github.com/laminas/laminas-view.git", - "reference": "b734610c8a83bc49b32536dd7dccd2f13ab3f601" + "reference": "9f8751ea7e74d3dd1b95863fc7ddf7b99eb69d3f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-view/zipball/b734610c8a83bc49b32536dd7dccd2f13ab3f601", - "reference": "b734610c8a83bc49b32536dd7dccd2f13ab3f601", + "url": "https://api.github.com/repos/laminas/laminas-view/zipball/9f8751ea7e74d3dd1b95863fc7ddf7b99eb69d3f", + "reference": "9f8751ea7e74d3dd1b95863fc7ddf7b99eb69d3f", "shasum": "" }, "require": { @@ -974,17 +975,19 @@ "laminas/laminas-servicemanager": "^4.4.0", "laminas/laminas-stdlib": "^3.10.1", "laminas/laminas-translator": "^1.1 || ^2.0", - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "psr/container": "^1 || ^2" }, "require-dev": { - "amphp/dns": "^2.4.0", - "amphp/socket": "^2.4.0", + "amphp/dns": "^2.4.2", + "amphp/socket": "^2.4.2", + "boundwize/structarmed": "^0.21.8", + "laminas/internal-tooling": "^1.2", "laminas/laminas-coding-standard": "~3.1.0", - "phpunit/phpunit": "^11.5.55 || ^12.5.9", - "psalm/plugin-phpunit": "^0.19.7", - "symfony/console": "7.4.13", - "vimeo/psalm": "^6.16.1" + "phpunit/phpunit": "^11.5.55 || ^12.5.43", + "psalm/plugin-phpunit": "^0.22.2", + "symfony/console": "7.4.23", + "vimeo/psalm": "^6.20.11" }, "suggest": { "laminas/laminas-authentication": "Laminas\\Authentication component", @@ -1030,12 +1033,12 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2026-06-02T22:39:05+00:00", - "published-time": "2026-06-02T22:53:16+00:00" + "time": "2026-11-12T14:11:14+00:00", + "published-time": "2026-11-12T14:12:00+00:00" }, { "name": "league/commonmark", @@ -1230,21 +1233,21 @@ }, { "name": "mezzio/mezzio-helpers", - "version": "5.20.0", + "version": "5.21.0", "source": { "type": "git", "url": "https://github.com/mezzio/mezzio-helpers.git", - "reference": "a26ba04bd449d5cdb5ad38b17ce672365dbc9d90" + "reference": "2eb571e2f4a20b83ffd94b4d56a1720024a0cd39" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/mezzio/mezzio-helpers/zipball/a26ba04bd449d5cdb5ad38b17ce672365dbc9d90", - "reference": "a26ba04bd449d5cdb5ad38b17ce672365dbc9d90", + "url": "https://api.github.com/repos/mezzio/mezzio-helpers/zipball/2eb571e2f4a20b83ffd94b4d56a1720024a0cd39", + "reference": "2eb571e2f4a20b83ffd94b4d56a1720024a0cd39", "shasum": "" }, "require": { "mezzio/mezzio-router": "^3.18 || ^4.0", - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "psr/container": "^1.0 || ^2.0", "psr/http-message": "^1.0.1 || ^2.0.0", "psr/http-server-middleware": "^1.0" @@ -1257,11 +1260,12 @@ }, "require-dev": { "ext-json": "*", + "laminas/internal-tooling": "^1.0.0", "laminas/laminas-coding-standard": "~3.1.0", - "laminas/laminas-diactoros": "^3.6", - "phpunit/phpunit": "^11.5.42", - "psalm/plugin-phpunit": "^0.19.5", - "vimeo/psalm": "^6.13.1" + "laminas/laminas-diactoros": "^3.10", + "phpunit/phpunit": "^11.5.57", + "psalm/plugin-phpunit": "^0.19.7", + "vimeo/psalm": "^6.20.10" }, "suggest": { "ext-json": "If you wish to use the JsonStrategy with BodyParamsMiddleware" @@ -1301,25 +1305,25 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2025-10-11T08:40:34+00:00", - "published-time": "2025-10-11T08:41:22+00:00" + "time": "2026-11-10T00:02:54+00:00", + "published-time": "2026-11-10T00:03:19+00:00" }, { "name": "mezzio/mezzio-laminasviewrenderer", - "version": "3.0.0", + "version": "3.1.0", "source": { "type": "git", "url": "https://github.com/mezzio/mezzio-laminasviewrenderer.git", - "reference": "ac78584ea1c417f4f4289616add5ca8d96c78f62" + "reference": "348b0abc4683f267c2de2a79cba2cf840fb36cf0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/mezzio/mezzio-laminasviewrenderer/zipball/ac78584ea1c417f4f4289616add5ca8d96c78f62", - "reference": "ac78584ea1c417f4f4289616add5ca8d96c78f62", + "url": "https://api.github.com/repos/mezzio/mezzio-laminasviewrenderer/zipball/348b0abc4683f267c2de2a79cba2cf840fb36cf0", + "reference": "348b0abc4683f267c2de2a79cba2cf840fb36cf0", "shasum": "" }, "require": { @@ -1328,16 +1332,17 @@ "mezzio/mezzio-helpers": "^5.15.0", "mezzio/mezzio-router": "^3.16.1 || ^4.0.0", "mezzio/mezzio-template": "^3.0", - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "psr/container": "^1.0 || ^2.0", "psr/http-message": "^1.0.1 || ^2.0.0" }, "require-dev": { + "laminas/internal-tooling": "^1.0.0", "laminas/laminas-coding-standard": "^3.1.0", - "mezzio/mezzio-fastroute": "^3.14", - "phpunit/phpunit": "^11.5.44", - "psalm/plugin-phpunit": "^0.19.5", - "vimeo/psalm": "^6.13.1" + "mezzio/mezzio-fastroute": "^3.15", + "phpunit/phpunit": "^11.5.57", + "psalm/plugin-phpunit": "^0.19.7", + "vimeo/psalm": "^6.20.10" }, "type": "library", "extra": { @@ -1374,30 +1379,30 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2025-11-26T16:34:39+00:00", - "published-time": "2025-12-02T21:50:52+00:00" + "time": "2026-11-10T00:28:34+00:00", + "published-time": "2026-11-10T00:29:19+00:00" }, { "name": "mezzio/mezzio-router", - "version": "4.2.0", + "version": "4.3.0", "source": { "type": "git", "url": "https://github.com/mezzio/mezzio-router.git", - "reference": "e7a6505d7e460ce30c4135e146241d7d24d81c27" + "reference": "28e5ce526c2ea58df14a93a44277a41e7fc820a2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/mezzio/mezzio-router/zipball/e7a6505d7e460ce30c4135e146241d7d24d81c27", - "reference": "e7a6505d7e460ce30c4135e146241d7d24d81c27", + "url": "https://api.github.com/repos/mezzio/mezzio-router/zipball/28e5ce526c2ea58df14a93a44277a41e7fc820a2", + "reference": "28e5ce526c2ea58df14a93a44277a41e7fc820a2", "shasum": "" }, "require": { "fig/http-message-util": "^1.1.5", - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "psr/container": "^1.1.2 || ^2.0", "psr/http-factory": "^1.0.2", "psr/http-message": "^1.0.1 || ^2.0.0", @@ -1409,13 +1414,15 @@ "zendframework/zend-expressive-router": "*" }, "require-dev": { + "boundwize/structarmed": "^0.21.8", + "laminas/internal-tooling": "^1.0.0", "laminas/laminas-coding-standard": "~3.1.0", - "laminas/laminas-diactoros": "^3.6.0", - "laminas/laminas-servicemanager": "^4.4.0", - "laminas/laminas-stratigility": "^4.2.0", - "phpunit/phpunit": "^11.5.42", - "psalm/plugin-phpunit": "^0.19.5", - "vimeo/psalm": "^6.13.1" + "laminas/laminas-diactoros": "^3.10.0", + "laminas/laminas-servicemanager": "^4.5.1", + "laminas/laminas-stratigility": "^4.3.1", + "phpunit/phpunit": "^11.5.57", + "psalm/plugin-phpunit": "^0.22.2", + "vimeo/psalm": "^6.20.10" }, "suggest": { "mezzio/mezzio-fastroute": "^3.0 to use the FastRoute routing adapter", @@ -1456,38 +1463,39 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2026-01-09T11:44:24+00:00", - "published-time": "2026-01-09T11:46:24+00:00" + "time": "2026-11-10T09:34:13+00:00", + "published-time": "2026-11-10T09:34:51+00:00" }, { "name": "mezzio/mezzio-template", - "version": "3.0.0", + "version": "3.1.0", "source": { "type": "git", "url": "https://github.com/mezzio/mezzio-template.git", - "reference": "49a797e19b167b208327854c81eb079937f0b161" + "reference": "6acd0a275986cf91ee5d0bc172c510af3296e7af" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/mezzio/mezzio-template/zipball/49a797e19b167b208327854c81eb079937f0b161", - "reference": "49a797e19b167b208327854c81eb079937f0b161", + "url": "https://api.github.com/repos/mezzio/mezzio-template/zipball/6acd0a275986cf91ee5d0bc172c510af3296e7af", + "reference": "6acd0a275986cf91ee5d0bc172c510af3296e7af", "shasum": "" }, "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" }, "conflict": { "zendframework/zend-expressive-template": "*" }, "require-dev": { + "laminas/internal-tooling": "^1.0.0", "laminas/laminas-coding-standard": "~3.1.0", - "phpunit/phpunit": "^11.5.42", - "psalm/plugin-phpunit": "^0.19.5", - "vimeo/psalm": "^6.13.1" + "phpunit/phpunit": "^11.5.57", + "psalm/plugin-phpunit": "^0.22.2", + "vimeo/psalm": "^6.20.10" }, "suggest": { "mezzio/mezzio-laminasviewrenderer": "^2.0 to use the laminas-view PhpRenderer template renderer", @@ -1521,12 +1529,12 @@ }, "funding": [ { - "url": "https://funding.communitybridge.org/projects/laminas-project", - "type": "community_bridge" + "url": "https://crowdfunding.linuxfoundation.org/initiatives/laminas-project", + "type": "custom" } ], - "time": "2025-10-11T09:18:27+00:00", - "published-time": "2025-10-13T12:50:39+00:00" + "time": "2026-11-10T21:13:23+00:00", + "published-time": "2026-11-10T21:14:07+00:00" }, { "name": "monolog/monolog", @@ -12624,7 +12632,7 @@ "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": "~8.4.1 || ~8.5.0", + "php": "~8.4.1 || ~8.5.0 || ~8.6.0", "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*" diff --git a/config/autoload/commonmark.global.php b/config/autoload/commonmark.global.php index ec4a7b2..dc22af8 100644 --- a/config/autoload/commonmark.global.php +++ b/config/autoload/commonmark.global.php @@ -112,8 +112,8 @@ 'internal_hosts' => [], 'open_in_new_window' => false, 'html_class' => '', - // Each of these takes 'none', 'all', 'internal' or 'external'. - 'nofollow' => 'none', + // Each of these takes '' (apply to none), 'all', 'internal' or 'external'. + 'nofollow' => '', 'noopener' => 'external', 'noreferrer' => 'external', ], diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 6fb3663..c882661 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -21,16 +21,20 @@ use CommonDoc\Container\BuildSiteHandlerFactory; use CommonDoc\Container\CommandPostHandleListenerFactory; use CommonDoc\Container\CommandPreHandleListenerFactory; +use CommonDoc\Container\DocumentViewRendererFactory; use CommonDoc\Container\EnvironmentFactory; use CommonDoc\Container\ExtensionPluginManager; use CommonDoc\Container\ExtensionPluginManagerFactory; -use CommonDoc\Container\LayoutWrappingMiddlewareFactory; use CommonDoc\Container\MarkdownConverterFactory; +use CommonDoc\Container\PageContextFactory; +use CommonDoc\Container\PageContextListenerFactory; use CommonDoc\Container\SourceLoadingMiddlewareFactory; use CommonDoc\Listener\CommandPostHandleListener; use CommonDoc\Listener\CommandPreHandleListener; -use CommonDoc\Middleware\LayoutWrappingMiddleware; use CommonDoc\Middleware\SourceLoadingMiddleware; +use CommonDoc\View\DocumentViewRenderer; +use CommonDoc\View\PageContext; +use CommonDoc\View\PageContextListener; use League\CommonMark\ConverterInterface; use League\CommonMark\Environment\EnvironmentInterface; use League\CommonMark\MarkdownConverter; @@ -62,8 +66,15 @@ * * The middleware pipeline merges the same way, and the priorities are the * ordering contract: 100 pre-handle event, 50 source loading, 1 message handler, - * 0 layout wrapping, -100 post-handle event. `SplPriorityQueue` is not stable, - * so each custom middleware needs a priority of its own rather than a shared one. + * -100 post-handle event. `SplPriorityQueue` is not stable, so the one custom + * middleware carries a priority of its own rather than a shared one. + * + * The view configuration is contributed here rather than in an autoload file for + * the same reason: a host that overrides a local file still aggregates this + * provider, so the body and layout addresses always resolve. Both are map + * entries, which is the override seam a site uses when it wants a different body + * without a code change: adding the same address to its own `templates.map` + * replaces the entry, and the map outranks the path stack. * * The extension plugin manager is wired here in both halves: its factory entry * and the plugin manager's class-name key. Neither half belongs in an autoload @@ -98,13 +109,14 @@ * invokables?: array, * } * @type Dependencies = array{ - * aliases: array, + * aliases: array, * factories: array, * } - * @type ViewConfig = array{template_path_stack: list} + * @type TemplateMap = array + * @type ViewConfig = array{map: TemplateMap, layout: non-empty-string} * @type ProviderConfig = array{ * dependencies: Dependencies, - * view_manager: ViewConfig, + * templates: ViewConfig, * Webware\Console\ConsoleInterface: ConsoleConfig, * Webware\MessageBus\MessageBusInterface: BusConfig, * listeners: ListenerConfig, @@ -126,10 +138,6 @@ public function getBusConfig(): array 'middleware' => SourceLoadingMiddleware::class, 'priority' => 50, ], - [ - 'middleware' => LayoutWrappingMiddleware::class, - 'priority' => 0, - ], ], ]; } @@ -156,10 +164,12 @@ public function getDependencies(): array BuildSiteHandler::class => BuildSiteHandlerFactory::class, CommandPostHandleListener::class => CommandPostHandleListenerFactory::class, CommandPreHandleListener::class => CommandPreHandleListenerFactory::class, + DocumentViewRenderer::class => DocumentViewRendererFactory::class, EnvironmentInterface::class => EnvironmentFactory::class, ExtensionPluginManager::class => ExtensionPluginManagerFactory::class, - LayoutWrappingMiddleware::class => LayoutWrappingMiddlewareFactory::class, MarkdownConverter::class => MarkdownConverterFactory::class, + PageContext::class => PageContextFactory::class, + PageContextListener::class => PageContextListenerFactory::class, SourceLoadingMiddleware::class => SourceLoadingMiddlewareFactory::class, ], ]; @@ -193,9 +203,11 @@ public function getListenerConfig(): array public function getViewConfig(): array { return [ - 'template_path_stack' => [ - dirname(__DIR__) . '/templates', + 'map' => [ + 'commondoc::document' => dirname(__DIR__) . '/templates/commondoc/document.phtml', + 'commondoc::layout' => dirname(__DIR__) . '/templates/commondoc/layout.phtml', ], + 'layout' => 'commondoc::layout', ]; } @@ -204,7 +216,7 @@ public function __invoke(): array { return [ 'dependencies' => $this->getDependencies(), - 'view_manager' => $this->getViewConfig(), + 'templates' => $this->getViewConfig(), ConsoleInterface::class => $this->getConsoleConfig(), MessageBusInterface::class => $this->getBusConfig(), EventProvider::LISTENER_KEY => $this->getListenerConfig(), diff --git a/src/Container/DocumentViewRendererFactory.php b/src/Container/DocumentViewRendererFactory.php new file mode 100644 index 0000000..8ddc5d5 --- /dev/null +++ b/src/Container/DocumentViewRendererFactory.php @@ -0,0 +1,44 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Container; + +use CommonDoc\View\DocumentViewRenderer; +use Laminas\ServiceManager\Factory\FactoryInterface; +use Mezzio\Template\TemplateRendererInterface; +use Override; +use Psr\Container\ContainerInterface; + +/** + * Construction seam for the document view renderer. + * + * The template renderer is the framework's, so the layout, the resolver chain + * and every view helper come from the host container rather than from here. + * + * @internal + */ +final readonly class DocumentViewRendererFactory implements FactoryInterface +{ + /** + * @param ?array $options + */ + #[Override] + public function __invoke( + ContainerInterface $container, + string $requestedName, + ?array $options = null, + ): DocumentViewRenderer { + return new DocumentViewRenderer($container->get(TemplateRendererInterface::class)); + } +} diff --git a/src/Container/EnvironmentFactory.php b/src/Container/EnvironmentFactory.php index 45c1a43..b602b7b 100644 --- a/src/Container/EnvironmentFactory.php +++ b/src/Container/EnvironmentFactory.php @@ -14,12 +14,16 @@ namespace CommonDoc\Container; +use CommonDoc\View\DocumentViewRenderer; +use CommonDoc\View\PageContextListener; use Laminas\ServiceManager\Factory\FactoryInterface; use League\CommonMark\Environment\Environment; use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentPreRenderEvent; use League\CommonMark\Exception\AlreadyInitializedException; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\Extension\ExtensionInterface; +use League\CommonMark\Node\Block\Document; use Override; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; @@ -39,6 +43,12 @@ * constructed with the const defaults already merged into the application's * section, so this class never re-reads the section and cannot load a name twice. * + * The document node is then pointed at the view renderer at priority 10, so it + * outranks the core HTML renderer for the same class and the whole document is + * rendered as a view rather than as finished HTML. The page context listener is + * registered on the pre-render event, which is where the page reaches the + * document's own data. Both collaborators come from the container. + * * @internal */ final readonly class EnvironmentFactory implements FactoryInterface @@ -80,6 +90,12 @@ public function __invoke( $environment->addExtension($extension); } + $environment->addRenderer(Document::class, $container->get(DocumentViewRenderer::class), 10); + $environment->addEventListener( + DocumentPreRenderEvent::class, + $container->get(PageContextListener::class), + ); + return $environment; } } diff --git a/src/Container/LayoutWrappingMiddlewareFactory.php b/src/Container/PageContextFactory.php similarity index 60% rename from src/Container/LayoutWrappingMiddlewareFactory.php rename to src/Container/PageContextFactory.php index cf2ad64..76986e1 100644 --- a/src/Container/LayoutWrappingMiddlewareFactory.php +++ b/src/Container/PageContextFactory.php @@ -14,21 +14,20 @@ namespace CommonDoc\Container; -use CommonDoc\Middleware\LayoutWrappingMiddleware; +use CommonDoc\View\PageContext; use Laminas\ServiceManager\Factory\FactoryInterface; use Override; use Psr\Container\ContainerInterface; /** - * Construction seam for the layout wrapping middleware. + * Construction seam for the page context. * - * This factory is load bearing: the pipeline factory skips any spec the - * container cannot resolve, so without it the middleware would vanish from the - * pipeline without an error. + * The service manager shares a factory result by default, so the listener and + * the caller that sets the page resolve the same slot. * * @internal */ -final readonly class LayoutWrappingMiddlewareFactory implements FactoryInterface +final readonly class PageContextFactory implements FactoryInterface { /** * @param ?array $options @@ -38,7 +37,7 @@ public function __invoke( ContainerInterface $container, string $requestedName, ?array $options = null, - ): LayoutWrappingMiddleware { - return new LayoutWrappingMiddleware(); + ): PageContext { + return new PageContext(); } } diff --git a/src/Container/PageContextListenerFactory.php b/src/Container/PageContextListenerFactory.php new file mode 100644 index 0000000..c3e6bdf --- /dev/null +++ b/src/Container/PageContextListenerFactory.php @@ -0,0 +1,41 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Container; + +use CommonDoc\View\PageContext; +use CommonDoc\View\PageContextListener; +use Laminas\ServiceManager\Factory\FactoryInterface; +use Override; +use Psr\Container\ContainerInterface; + +/** + * Construction seam for the page context listener. + * + * @internal + */ +final readonly class PageContextListenerFactory implements FactoryInterface +{ + /** + * @param ?array $options + */ + #[Override] + public function __invoke( + ContainerInterface $container, + string $requestedName, + ?array $options = null, + ): PageContextListener { + return new PageContextListener($container->get(PageContext::class)); + } +} diff --git a/src/Middleware/LayoutWrappingMiddleware.php b/src/Middleware/LayoutWrappingMiddleware.php deleted file mode 100644 index b5858a3..0000000 --- a/src/Middleware/LayoutWrappingMiddleware.php +++ /dev/null @@ -1,39 +0,0 @@ - - * and contributors. - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace CommonDoc\Middleware; - -use Override; -use Webware\MessageBus\MessageInterface; -use Webware\MessageBus\MiddlewareInterface; -use Webware\MessageBus\PipelineHandlerInterface; -use Webware\MessageBus\ResultInterface; - -/** - * Wraps the handler's rendered pages in the site layout. - * - * Registered at priority 0, so it runs after the handler and before the - * post-handle event: a diagnostics listener sees the wrapped result rather than - * the raw one. The body is a pass-through for now. - * - * @api - */ -final readonly class LayoutWrappingMiddleware implements MiddlewareInterface -{ - #[Override] - public function process(MessageInterface $message, PipelineHandlerInterface $next): ResultInterface - { - return $next->handle($message); - } -} diff --git a/src/View/DocumentViewRenderer.php b/src/View/DocumentViewRenderer.php new file mode 100644 index 0000000..0449d77 --- /dev/null +++ b/src/View/DocumentViewRenderer.php @@ -0,0 +1,88 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\View; + +use Dflydev\DotAccessData\Exception\InvalidPathException; +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use League\CommonMark\Renderer\NodeRendererInterface; +use Mezzio\Template\TemplateRendererInterface; +use Override; +use Stringable; + +use function sprintf; + +/** + * Renders the document node as a view instead of as finished HTML. + * + * CommonMark asks for the body through the injected child renderer, which is the + * only correct source of node output, and the body is handed to the view + * renderer once. The view renderer owns the layout wrap, the additional view + * helpers and the helper state reset, so nothing here reimplements any of it. + * + * The page travels on the document's own data, written by `PageContextListener`, + * which is what keeps a document rendered outside a build working with no page. + * + * @internal + */ +final readonly class DocumentViewRenderer implements NodeRendererInterface +{ + public function __construct( + private TemplateRendererInterface $renderer, + ) {} + + /** + * @throws InvalidArgumentException when the node is not a document + * @throws InvalidPathException from the page read, which the default value + * prevents in practice + */ + #[Override] + public function render(Node $node, ChildNodeRendererInterface $childRenderer): Stringable|string|null + { + if (! $node instanceof Document) { + throw new InvalidArgumentException(sprintf( + 'The document view renderer renders only a %s node, %s given.', + Document::class, + $node::class, + )); + } + + return $this->renderer->render('commondoc::document', [ + 'documentBody' => $childRenderer->renderNodes($node->children()), + 'page' => $this->pageFor($node), + ]); + } + + /** + * The page this document belongs to, or null when the render is not part of + * a build. + * + * The read carries a null default and the result is narrowed, so the null + * case is a declared outcome rather than an assumption: a preview render and + * a build render travel the same path. + * + * @throws InvalidPathException from the data read, which the default value + * prevents in practice + */ + private function pageFor(Document $document): ?Page + { + /** @var mixed $page */ + $page = $document->data->get('commondoc.page', null); + + return $page instanceof Page ? $page : null; + } +} diff --git a/src/View/Page.php b/src/View/Page.php new file mode 100644 index 0000000..216cce0 --- /dev/null +++ b/src/View/Page.php @@ -0,0 +1,219 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\View; + +use ArrayIterator; +use Laminas\View\Model\ModelInterface; +use LogicException; +use Override; +use Traversable; + +use function count; +use function sprintf; + +/** + * The identity of one converted document, as a readonly view model. + * + * This implements the view model contract for its state, never for its + * placement. `LaminasViewRenderer::render()` writes to the model it is handed + * and walks every attached child through `beforeRender()`, so a readonly page + * cannot occupy a position in that tree. It reaches templates as the "page" + * value on the render root instead, and templates read it through this + * interface. + * + * The mutators exist to satisfy the contract and every one of them throws. + */ +// @mago-expect lint:too-many-methods - ModelInterface plus its Countable and IteratorAggregate parents require all fourteen methods. +final readonly class Page implements ModelInterface +{ + /** + * Required fields come first, then the optional ones, alphabetical within + * each group. + * + * @param list $children + * @param non-empty-string $captureTo + */ + // @mago-expect lint:excessive-parameter-list - a page descriptor needs all eleven inputs. + public function __construct( + public string $label, + public string $projectName, + public string $projectSlug, + public string $sourcePath, + public string $url, + public string $versionLabel, + public bool $append = false, + public string $captureTo = 'page', + public array $children = [], + public string $template = 'commondoc::page', + public bool $terminal = false, + ) {} + + /** + * @throws LogicException always, because a page is immutable + */ + #[Override] + public function addChild( + ModelInterface $child, + ?string $captureTo = null, + ?bool $append = null, + ): static { + throw $this->immutable(); + } + + #[Override] + public function captureTo(): string + { + return $this->captureTo; + } + + #[Override] + public function count(): int + { + return count($this->children); + } + + /** + * @return list + */ + #[Override] + public function getChildren(): array + { + return $this->children; + } + + /** + * @return Traversable + */ + #[Override] + public function getIterator(): Traversable + { + return new ArrayIterator($this->children); + } + + #[Override] + public function getTemplate(): string + { + return $this->template; + } + + #[Override] + public function getVariable(string $name, mixed $default = null): mixed + { + return $this->getVariables()[$name] ?? $default; + } + + /** + * The typed projection of the page fields. No key is ever named `content`, + * because Mezzio reserves that name for the layout. + * + * @return array + */ + #[Override] + public function getVariables(): array + { + return [ + 'label' => $this->label, + 'url' => $this->url, + 'projectSlug' => $this->projectSlug, + 'projectName' => $this->projectName, + 'versionLabel' => $this->versionLabel, + 'sourcePath' => $this->sourcePath, + 'captureTo' => $this->captureTo, + 'append' => $this->append, + 'terminal' => $this->terminal, + 'children' => $this->children, + ]; + } + + #[Override] + public function hasChildren(): bool + { + return [] !== $this->children; + } + + #[Override] + public function isAppend(): bool + { + return $this->append; + } + + /** + * @throws LogicException always, because a page is immutable + */ + #[Override] + public function setAppend(bool $append): static + { + throw $this->immutable(); + } + + /** + * @throws LogicException always, because a page is immutable + */ + #[Override] + public function setCaptureTo(string $capture): static + { + throw $this->immutable(); + } + + /** + * @throws LogicException always, because a page is immutable + */ + #[Override] + public function setTemplate(string $template): static + { + throw $this->immutable(); + } + + /** + * @throws LogicException always, because a page is immutable + */ + #[Override] + public function setTerminal(bool $terminate): static + { + throw $this->immutable(); + } + + /** + * @throws LogicException always, because a page is immutable + */ + #[Override] + public function setVariable(string $name, mixed $value): static + { + throw $this->immutable(); + } + + /** + * @throws LogicException always, because a page is immutable + */ + #[Override] + public function setVariables(iterable $variables, bool $overwrite = false): static + { + throw $this->immutable(); + } + + #[Override] + public function terminate(): bool + { + return $this->terminal; + } + + private function immutable(): LogicException + { + return new LogicException(sprintf( + 'Cannot modify page "%s": a Page is immutable.', + $this->label, + )); + } +} diff --git a/src/View/PageContext.php b/src/View/PageContext.php new file mode 100644 index 0000000..f06618a --- /dev/null +++ b/src/View/PageContext.php @@ -0,0 +1,43 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\View; + +/** + * The page being converted, for the duration of one conversion. + * + * One slot, no stack and no static state: a caller converts one document at a + * time and brackets the conversion with `set()` and `clear()`. The listener + * reads this slot on `DocumentPreRenderEvent`, so nothing else in the render + * path needs to be told about the page. + */ +final class PageContext +{ + private ?Page $page = null; + + public function clear(): void + { + $this->page = null; + } + + public function current(): ?Page + { + return $this->page; + } + + public function set(Page $page): void + { + $this->page = $page; + } +} diff --git a/src/View/PageContextListener.php b/src/View/PageContextListener.php new file mode 100644 index 0000000..08c3297 --- /dev/null +++ b/src/View/PageContextListener.php @@ -0,0 +1,49 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\View; + +use Dflydev\DotAccessData\Exception\DataException; +use Dflydev\DotAccessData\Exception\InvalidPathException; +use League\CommonMark\Event\DocumentPreRenderEvent; + +/** + * Carries the current page from the conversion caller to the document. + * + * Writing it into the document's data rather than into this listener's own + * state keeps the page attached to the document it belongs to, which is what + * the renderer reads, and it leaves a document that was built outside the + * build loop with whatever page it already had. + */ +final readonly class PageContextListener +{ + public function __construct( + private PageContext $context, + ) {} + + /** + * @throws DataException when the document data cannot be written + * @throws InvalidPathException when the data key cannot be resolved + */ + public function __invoke(DocumentPreRenderEvent $event): void + { + $page = $this->context->current(); + + if (null === $page) { + return; + } + + $event->getDocument()->data->set('commondoc.page', $page); + } +} diff --git a/templates/commondoc/document.phtml b/templates/commondoc/document.phtml index 0d4c948..e5b0a1a 100644 --- a/templates/commondoc/document.phtml +++ b/templates/commondoc/document.phtml @@ -9,19 +9,18 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * - * @var string $title - * @var string $content + * The body template for one document. The body arrives already rendered by + * CommonMark and is echoed inside the body region; the page arrives when the + * render belongs to one and is absent otherwise, so it is only read behind a + * null check. `content` belongs to the layout and is never set here. + * + * @var string $documentBody + * @var \CommonDoc\View\Page|null $page */ ?> - - - - - <?= $this->escapeHtml($title) ?> - - -
- -
- - + + headTitle($page->label); ?> + +
+ +
diff --git a/templates/commondoc/layout.phtml b/templates/commondoc/layout.phtml new file mode 100644 index 0000000..9ac04ed --- /dev/null +++ b/templates/commondoc/layout.phtml @@ -0,0 +1,28 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * The layout shell for one document. The view renderer writes the body render + * into `content`, so this template reads that and nothing else: it must not + * assume a page, because a render performed outside a build still wraps here. + * + * @var string $content + */ +?> + + + + + headTitle()->setSeparator(' | ') ?> + + + content ?> + + diff --git a/test/integration/ConfigProviderWiringTest.php b/test/integration/ConfigProviderWiringTest.php index 6ea5ab8..e725f20 100644 --- a/test/integration/ConfigProviderWiringTest.php +++ b/test/integration/ConfigProviderWiringTest.php @@ -15,8 +15,14 @@ namespace CommonDocTestIntegration; use CommonDoc\ConfigProvider; +use CommonDoc\Container\DocumentViewRendererFactory; +use CommonDoc\View\DocumentViewRenderer; +use CommonDoc\View\PageContext; +use CommonDoc\View\PageContextListener; use JsonException; +use Laminas\ServiceManager\ServiceManager; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -26,12 +32,17 @@ use const JSON_THROW_ON_ERROR; /** - * Guards the wiring contract between composer.json and this package's namespace. + * Guards the wiring contract between composer.json, the aggregated config and + * this package's namespace. * * Renaming the namespace but missing `extra.laminas.config-provider` breaks every - * consumer silently, so the two are asserted to agree. + * consumer silently, so the two are asserted to agree. The remaining cases boot + * the real container, because a provider entry that is never aggregated is only + * visible that way. */ #[CoversClass(ConfigProvider::class)] +#[CoversMethod(ConfigProvider::class, 'getDependencies')] +#[CoversMethod(ConfigProvider::class, 'getViewConfig')] final class ConfigProviderWiringTest extends TestCase { /** @@ -50,4 +61,45 @@ public function composerDeclaresThisPackageAsItsConfigProvider(): void $composer['extra']['laminas']['config-provider'], ); } + + #[Test] + public function publishesTheTemplateMapAndTheLayout(): void + { + /** @var array{templates: array{map: array, layout: string}} $config */ + $config = $this->container()->get('config'); + + $provider = new ConfigProvider()->getViewConfig(); + + static::assertSame($provider['map'], $config['templates']['map']); + static::assertSame($provider['layout'], $config['templates']['layout']); + } + + #[Test] + public function resolvesTheDocumentViewRendererFromItsFactory(): void + { + $dependencies = new ConfigProvider()->getDependencies(); + + static::assertSame( + DocumentViewRendererFactory::class, + $dependencies['factories'][DocumentViewRenderer::class], + ); + static::assertInstanceOf( + DocumentViewRenderer::class, + $this->container()->get(DocumentViewRenderer::class), + ); + } + + #[Test] + public function resolvesThePageContextAndItsListener(): void + { + $container = $this->container(); + + static::assertInstanceOf(PageContext::class, $container->get(PageContext::class)); + static::assertInstanceOf(PageContextListener::class, $container->get(PageContextListener::class)); + } + + private function container(): ServiceManager + { + return require __DIR__ . '/../../config/container.php'; + } } diff --git a/test/integration/ContainerBootTest.php b/test/integration/ContainerBootTest.php index f69fdf1..babf20c 100644 --- a/test/integration/ContainerBootTest.php +++ b/test/integration/ContainerBootTest.php @@ -21,7 +21,6 @@ use CommonDoc\Container\ExtensionPluginManager; use CommonDoc\Listener\CommandPostHandleListener; use CommonDoc\Listener\CommandPreHandleListener; -use CommonDoc\Middleware\LayoutWrappingMiddleware; use CommonDoc\Middleware\SourceLoadingMiddleware; use Laminas\ServiceManager\ServiceManager; use League\CommonMark\Environment\EnvironmentInterface; @@ -69,7 +68,6 @@ #[CoversClass(CommandPreHandleListener::class)] #[CoversClass(CommandPostHandleListener::class)] #[CoversClass(SourceLoadingMiddleware::class)] -#[CoversClass(LayoutWrappingMiddleware::class)] #[CoversClass(ExtensionPluginManager::class)] final class ContainerBootTest extends TestCase { @@ -156,7 +154,6 @@ public function ordersThePipelineFromThePreEventToThePostEvent(): void CommandPreHandleMiddleware::class, SourceLoadingMiddleware::class, MessageHandlerMiddleware::class, - LayoutWrappingMiddleware::class, CommandPostHandleMiddleware::class, ], $order, @@ -190,16 +187,12 @@ public function registersAListenerForEachCommandEvent(): void } #[Test] - public function resolvesBothCustomMiddleware(): void + public function resolvesTheSourceLoadingMiddleware(): void { static::assertInstanceOf( SourceLoadingMiddleware::class, $this->container()->get(SourceLoadingMiddleware::class), ); - static::assertInstanceOf( - LayoutWrappingMiddleware::class, - $this->container()->get(LayoutWrappingMiddleware::class), - ); } private function container(): ServiceManager diff --git a/test/integration/DocumentViewRenderingTest.php b/test/integration/DocumentViewRenderingTest.php new file mode 100644 index 0000000..43f7f2e --- /dev/null +++ b/test/integration/DocumentViewRenderingTest.php @@ -0,0 +1,249 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTestIntegration; + +use CommonDoc\View\DocumentViewRenderer; +use CommonDoc\View\PageContext; +use Laminas\ServiceManager\ServiceManager; +use Laminas\View\Exception\RenderingFailedException; +use League\CommonMark\ConverterInterface; +use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\MarkdownConverter; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Renderer\Block\DocumentRenderer; +use League\CommonMark\Renderer\NodeRendererInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +use function array_map; +use function bin2hex; +use function file_put_contents; +use function glob; +use function is_array; +use function mkdir; +use function random_bytes; +use function rmdir; +use function sys_get_temp_dir; +use function unlink; + +/** + * Renders a document through the whole seam: the real container, the real + * CommonMark environment and the real Laminas view renderer. + * + * Only an integration test can prove the three claims that matter here, because + * each one is a claim about composition: a site replaces the body by + * configuration alone, the packaged body renders inside the layout, and a body + * name that resolves to nothing surfaces as the view renderer's own exception. + */ +#[CoversClass(DocumentViewRenderer::class)] +#[CoversMethod(DocumentViewRenderer::class, 'render')] +final class DocumentViewRenderingTest extends TestCase +{ + private string $directory; + + #[Test] + public function keepsTheLibraryRendererAndConverterUnsubclassed(): void + { + $container = $this->container($this->config()); + + static::assertSame(MarkdownConverter::class, $container->get(ConverterInterface::class)::class); + + /** @var EnvironmentInterface $environment */ + $environment = $container->get(EnvironmentInterface::class); + + $renderers = array_map( + static fn(NodeRendererInterface $renderer): string => $renderer::class, + [...$environment->getRenderersForClass(Document::class)], + ); + + static::assertSame(DocumentViewRenderer::class, $renderers[0]); + static::assertContains(DocumentRenderer::class, $renderers); + } + + #[Test] + public function raisesTheTemplateNotFoundFailureWhenTheBodyNameResolvesToNothing(): void + { + $this->expectException(RenderingFailedException::class); + $this->expectExceptionMessage('commondoc::document'); + + $this->renderDocument($this->configWithoutABodyTemplate()); + } + + #[Test] + public function rendersADocumentWithNoPagePresent(): void + { + $container = $this->container($this->config()); + + /** @var PageContext $context */ + $context = $container->get(PageContext::class); + + static::assertNull($context->current()); + + /** @var ConverterInterface $converter */ + $converter = $container->get(ConverterInterface::class); + + $output = (string) $converter->convert("# Heading\n\nBody paragraph."); + + static::assertStringContainsString('', $output); + static::assertStringContainsString('
', $output); + static::assertStringContainsString('

Body paragraph.

', $output); + static::assertStringContainsString('', $output); + } + + #[Test] + public function rendersAHelperContributedRegionInsideTheBody(): void + { + $body = "{$this->directory}/helper.phtml"; + file_put_contents($body, data: <<<'PHTML' + headLink()->appendStylesheet('/assets/helper.css'); ?> +
+ headLink() ?> + +
+ PHTML); + + $output = $this->renderDocument($this->configMappedTo($body)); + + static::assertStringContainsString('helper.css', $output); + static::assertStringContainsString('rel="stylesheet"', $output); + static::assertStringContainsString('

Body paragraph.

', $output); + } + + #[Test] + public function rendersANodeContributedByAnInstalledExtension(): void + { + $output = $this->renderDocument( + $this->config(), + "| a | b |\n| - | - |\n| 1 | 2 |", + ); + + static::assertStringContainsString('', $output); + static::assertStringContainsString('', $output); + } + + #[Test] + public function rendersTheBodyTemplateTheSiteConfigures(): void + { + $override = "{$this->directory}/override.phtml"; + file_put_contents($override, data: '
'); + + $output = $this->renderDocument($this->configMappedTo($override)); + + static::assertStringContainsString('
', $output); + static::assertStringContainsString('

Body paragraph.

', $output); + static::assertStringNotContainsString('
', $output); + } + + #[Test] + public function wrapsThePackagedBodyInTheLayout(): void + { + $output = $this->renderDocument($this->config()); + + static::assertStringContainsString('', $output); + static::assertStringContainsString('
', $output); + static::assertStringContainsString('

Body paragraph.

', $output); + static::assertStringContainsString('', $output); + } + + protected function setUp(): void + { + $this->directory = sys_get_temp_dir() . '/commondoc-' . bin2hex(random_bytes(8)); + mkdir($this->directory); + } + + protected function tearDown(): void + { + foreach ([...glob("{$this->directory}/*.phtml")] as $file) { + unlink($file); + } + + rmdir($this->directory); + } + + /** + * @return array<string, mixed> + */ + private function config(): array + { + $config = require __DIR__ . '/../../config/config.php'; + + return is_array($config) ? $config : []; + } + + /** + * @return array<string, mixed> + */ + private function configMappedTo(string $path): array + { + $config = $this->config(); + + /** @var mixed $templates */ + $templates = $config['templates'] ?? []; + + /** @var array{map: array<string, string>, layout: string} $templates */ + $templates['map']['commondoc::document'] = $path; + $config['templates'] = $templates; + + return $config; + } + + /** + * @return array<string, mixed> + */ + private function configWithoutABodyTemplate(): array + { + $config = $this->config(); + + /** @var mixed $templates */ + $templates = $config['templates'] ?? []; + + /** @var array{map: array<string, string>, layout: string} $templates */ + unset($templates['map']['commondoc::document']); + $config['templates'] = $templates; + + return $config; + } + + /** + * @param array<string, mixed> $config + */ + private function container(array $config): ServiceManager + { + /** @var mixed $declared */ + $declared = $config['dependencies'] ?? []; + + /** @var array<string, mixed> $dependencies */ + $dependencies = is_array($declared) ? $declared : []; + + $dependencies['services']['config'] = $config; + + return new ServiceManager($dependencies); + } + + /** + * @param array<string, mixed> $config + */ + private function renderDocument(array $config, string $markdown = "# Heading\n\nBody paragraph."): string + { + $container = $this->container($config); + + /** @var ConverterInterface $converter */ + $converter = $container->get(ConverterInterface::class); + + return (string) $converter->convert($markdown); + } +} diff --git a/test/unit/ConfigProviderTest.php b/test/unit/ConfigProviderTest.php index 4dbd378..2a5a11d 100644 --- a/test/unit/ConfigProviderTest.php +++ b/test/unit/ConfigProviderTest.php @@ -22,16 +22,20 @@ use CommonDoc\Container\BuildSiteHandlerFactory; use CommonDoc\Container\CommandPostHandleListenerFactory; use CommonDoc\Container\CommandPreHandleListenerFactory; +use CommonDoc\Container\DocumentViewRendererFactory; use CommonDoc\Container\EnvironmentFactory; use CommonDoc\Container\ExtensionPluginManager; use CommonDoc\Container\ExtensionPluginManagerFactory; -use CommonDoc\Container\LayoutWrappingMiddlewareFactory; use CommonDoc\Container\MarkdownConverterFactory; +use CommonDoc\Container\PageContextFactory; +use CommonDoc\Container\PageContextListenerFactory; use CommonDoc\Container\SourceLoadingMiddlewareFactory; use CommonDoc\Listener\CommandPostHandleListener; use CommonDoc\Listener\CommandPreHandleListener; -use CommonDoc\Middleware\LayoutWrappingMiddleware; use CommonDoc\Middleware\SourceLoadingMiddleware; +use CommonDoc\View\DocumentViewRenderer; +use CommonDoc\View\PageContext; +use CommonDoc\View\PageContextListener; use League\CommonMark\ConverterInterface; use League\CommonMark\Environment\EnvironmentInterface; use League\CommonMark\MarkdownConverter; @@ -46,6 +50,10 @@ use Webware\MessageBus\Event\Command\CommandPreHandleEvent; use Webware\MessageBus\MessageBusInterface; +use function array_keys; +use function strlen; +use function substr; + #[CoversClass(ConfigProvider::class)] #[CoversMethod(ConfigProvider::class, '__invoke')] #[CoversMethod(ConfigProvider::class, 'getBusConfig')] @@ -64,7 +72,7 @@ public function aggregatesEverySection(): void static::assertSame( [ 'dependencies' => $provider->getDependencies(), - 'view_manager' => $provider->getViewConfig(), + 'templates' => $provider->getViewConfig(), ConsoleInterface::class => $provider->getConsoleConfig(), MessageBusInterface::class => $provider->getBusConfig(), EventProvider::LISTENER_KEY => $provider->getListenerConfig(), @@ -87,6 +95,12 @@ public function contributesTheBuildCommandToTheConsole(): void ); } + #[Test] + public function leavesTheDeadPathStackOutOfTheViewConfig(): void + { + static::assertArrayNotHasKey('template_path_stack', new ConfigProvider()->getViewConfig()); + } + #[Test] public function mapsTheBuildSiteCommandToItsHandler(): void { @@ -99,7 +113,7 @@ public function mapsTheBuildSiteCommandToItsHandler(): void } #[Test] - public function pipesTheCustomMiddlewareAtDistinctPriorities(): void + public function pipesTheSourceLoadingMiddleware(): void { $config = new ConfigProvider()->__invoke(); @@ -109,10 +123,6 @@ public function pipesTheCustomMiddlewareAtDistinctPriorities(): void 'middleware' => SourceLoadingMiddleware::class, 'priority' => 50, ], - [ - 'middleware' => LayoutWrappingMiddleware::class, - 'priority' => 0, - ], ], $config[MessageBusInterface::class][MessageBusConfigProvider::MIDDLEWARE_PIPELINE_KEY], ); @@ -123,12 +133,13 @@ public function pointsTheViewAtTheShippedTemplates(): void { $config = new ConfigProvider()->getViewConfig(); - static::assertCount(1, $config['template_path_stack']); - - $root = $config['template_path_stack'][0]; + static::assertSame(['commondoc::document', 'commondoc::layout'], array_keys($config['map'])); + static::assertSame('commondoc::layout', $config['layout']); - static::assertDirectoryExists($root); - static::assertFileExists("{$root}/commondoc/document.phtml"); + foreach ($config['map'] as $name => $path) { + static::assertStringEndsWith('/commondoc/' . substr($name, strlen('commondoc::')) . '.phtml', $path); + static::assertFileExists($path); + } } #[Test] @@ -168,10 +179,12 @@ public function registersTheCommandsTheHandlersTheMiddlewareAndTheConverter(): v BuildSiteHandler::class => BuildSiteHandlerFactory::class, CommandPostHandleListener::class => CommandPostHandleListenerFactory::class, CommandPreHandleListener::class => CommandPreHandleListenerFactory::class, + DocumentViewRenderer::class => DocumentViewRendererFactory::class, EnvironmentInterface::class => EnvironmentFactory::class, ExtensionPluginManager::class => ExtensionPluginManagerFactory::class, - LayoutWrappingMiddleware::class => LayoutWrappingMiddlewareFactory::class, MarkdownConverter::class => MarkdownConverterFactory::class, + PageContext::class => PageContextFactory::class, + PageContextListener::class => PageContextListenerFactory::class, SourceLoadingMiddleware::class => SourceLoadingMiddlewareFactory::class, ], $dependencies['factories'], diff --git a/test/unit/DocumentViewRendererFactoryTest.php b/test/unit/DocumentViewRendererFactoryTest.php new file mode 100644 index 0000000..5f79557 --- /dev/null +++ b/test/unit/DocumentViewRendererFactoryTest.php @@ -0,0 +1,57 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the commondoc package. + * + * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest; + +use CommonDoc\Container\DocumentViewRendererFactory; +use CommonDoc\View\DocumentViewRenderer; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use Mezzio\Template\TemplateRendererInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerInterface; + +#[CoversClass(DocumentViewRendererFactory::class)] +#[CoversMethod(DocumentViewRendererFactory::class, '__invoke')] +final class DocumentViewRendererFactoryTest extends TestCase +{ + #[Test] + public function buildsTheRendererFromTheTemplateRenderer(): void + { + $template = $this->createStub(TemplateRendererInterface::class); + $template->method('render')->willReturn('<html>rendered document</html>'); + + $container = $this->createStub(ContainerInterface::class); + $container + ->method('get') + ->willReturnCallback( + static fn(string $id): mixed => TemplateRendererInterface::class === $id ? $template : null, + ); + + $renderer = new DocumentViewRendererFactory()($container, DocumentViewRenderer::class); + + static::assertInstanceOf(DocumentViewRenderer::class, $renderer); + + $childRenderer = $this->createStub(ChildNodeRendererInterface::class); + $childRenderer->method('renderNodes')->willReturn('<p>body</p>'); + + static::assertSame( + '<html>rendered document</html>', + $renderer->render(new Document(), $childRenderer), + ); + } +} diff --git a/test/unit/DocumentViewRendererTest.php b/test/unit/DocumentViewRendererTest.php new file mode 100644 index 0000000..48780e8 --- /dev/null +++ b/test/unit/DocumentViewRendererTest.php @@ -0,0 +1,242 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the commondoc package. + * + * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest; + +use CommonDoc\View\DocumentViewRenderer; +use CommonDoc\View\Page; +use League\CommonMark\Exception\InvalidArgumentException; +use League\CommonMark\Node\Block\Document; +use League\CommonMark\Node\Block\Paragraph; +use League\CommonMark\Node\Node; +use League\CommonMark\Renderer\ChildNodeRendererInterface; +use Mezzio\Template\TemplateRendererInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +use function is_array; + +#[CoversClass(DocumentViewRenderer::class)] +#[CoversMethod(DocumentViewRenderer::class, 'render')] +final class DocumentViewRendererTest extends TestCase +{ + /** + * @param list<Node> $children + */ + private static function documentWith(array $children): Document + { + $document = new Document(); + + foreach ($children as $child) { + $document->appendChild($child); + } + + return $document; + } + + private static function page(string $label): Page + { + return new Page( + label : $label, + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/page.md', + url : '/page', + versionLabel: '1.0', + ); + } + + #[Test] + public function asksTheChildRendererOnceForTheDocumentChildren(): void + { + $children = [new Paragraph(), new Paragraph()]; + $document = self::documentWith($children); + + $childRenderer = $this->createMock(ChildNodeRendererInterface::class); + $childRenderer + ->expects($this->once()) + ->method('renderNodes') + ->with($children) + ->willReturn('<p>body</p>'); + + new DocumentViewRenderer($this->createStub(TemplateRendererInterface::class)) + ->render($document, $childRenderer); + } + + #[Test] + public function handsTheChildRendererOutputToTheTemplateUnchanged(): void + { + $body = "<p>first</p>\n<p>second & third</p>"; + $name = null; + $params = null; + + new DocumentViewRenderer($this->templateCapturing($name, $params)) + ->render(self::documentWith([new Paragraph()]), $this->childRendererReturning($body)); + + static::assertSame($body, $params['documentBody'] ?? null); + } + + #[Test] + public function passesANullPageWhenTheDocumentCarriesNone(): void + { + $name = null; + $params = null; + + new DocumentViewRenderer($this->templateCapturing($name, $params)) + ->render(new Document(), $this->childRendererReturning('<p>body</p>')); + + static::assertSame('commondoc::document', $name); + static::assertSame(['documentBody' => '<p>body</p>', 'page' => null], $params); + } + + #[Test] + public function passesANullPageWhenTheDocumentEntryIsExplicitlyNull(): void + { + $document = self::documentWith([new Paragraph()]); + $document->data->set('commondoc.page', null); + + $name = null; + $params = null; + + new DocumentViewRenderer($this->templateCapturing($name, $params)) + ->render($document, $this->childRendererReturning('<p>body</p>')); + + static::assertSame('commondoc::document', $name); + static::assertSame(['documentBody' => '<p>body</p>', 'page' => null], $params); + } + + #[Test] + public function passesANullPageWhenTheDocumentEntryIsNotAPage(): void + { + $document = self::documentWith([new Paragraph()]); + $document->data->set('commondoc.page', 'not a page'); + + $name = null; + $params = null; + + new DocumentViewRenderer($this->templateCapturing($name, $params)) + ->render($document, $this->childRendererReturning('<p>body</p>')); + + static::assertSame(['documentBody' => '<p>body</p>', 'page' => null], $params); + } + + #[Test] + public function passesTheBodyAndThePageToTheBodyTemplate(): void + { + $page = self::page('Reference page'); + $document = self::documentWith([new Paragraph()]); + $document->data->set('commondoc.page', $page); + + $name = null; + $params = null; + + new DocumentViewRenderer($this->templateCapturing($name, $params)) + ->render($document, $this->childRendererReturning('<p>body</p>')); + + static::assertSame('commondoc::document', $name); + static::assertSame(['documentBody' => '<p>body</p>', 'page' => $page], $params); + } + + #[Test] + public function rejectsANodeThatIsNotADocument(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Document'); + + new DocumentViewRenderer($this->createStub(TemplateRendererInterface::class)) + ->render(new Paragraph(), $this->childRendererReturning('<p>body</p>')); + } + + #[Test] + public function rendersTheDocumentChildrenThroughTheChildRenderer(): void + { + $children = [new Paragraph(), new Paragraph()]; + $document = self::documentWith($children); + $receivedNodes = []; + + $childRenderer = $this->createStub(ChildNodeRendererInterface::class); + $childRenderer + ->method('renderNodes') + ->willReturnCallback(static function (iterable $nodes) use (&$receivedNodes): string { + $receivedNodes = [...$nodes]; + + return '<p>body</p>'; + }); + + new DocumentViewRenderer($this->createStub(TemplateRendererInterface::class)) + ->render($document, $childRenderer); + + static::assertSame($children, $receivedNodes); + } + + #[Test] + public function rendersTheDocumentWhenTheChildRendererReturnsAnEmptyString(): void + { + $name = null; + $params = null; + + $result = new DocumentViewRenderer($this->templateCapturing($name, $params)) + ->render(self::documentWith([new Paragraph()]), $this->childRendererReturning('')); + + static::assertSame('commondoc::document', $name); + static::assertSame('', $params['documentBody'] ?? null); + static::assertNotSame('', $result); + } + + #[Test] + public function returnsTheRenderedBodyTemplateUnchanged(): void + { + $template = $this->createStub(TemplateRendererInterface::class); + $template->method('render')->willReturn('<html>rendered document</html>'); + + static::assertSame( + '<html>rendered document</html>', + new DocumentViewRenderer($template) + ->render(new Document(), $this->childRendererReturning('<p>body</p>')), + ); + } + + private function childRendererReturning(string $body): ChildNodeRendererInterface + { + $childRenderer = $this->createStub(ChildNodeRendererInterface::class); + $childRenderer->method('renderNodes')->willReturn($body); + + return $childRenderer; + } + + /** + * @param array<non-empty-string, mixed>|null $receivedParams + */ + private function templateCapturing(?string &$receivedName, ?array &$receivedParams): TemplateRendererInterface + { + $template = $this->createStub(TemplateRendererInterface::class); + $template + ->method('render') + ->willReturnCallback( + static function (string $name, array|object $params = []) use ( + &$receivedName, + &$receivedParams, + ): string { + $receivedName = $name; + $receivedParams = is_array($params) ? $params : []; + + return '<html>rendered document</html>'; + }, + ); + + return $template; + } +} diff --git a/test/unit/EnvironmentFactoryTest.php b/test/unit/EnvironmentFactoryTest.php index 0ae98a1..9c488e3 100644 --- a/test/unit/EnvironmentFactoryTest.php +++ b/test/unit/EnvironmentFactoryTest.php @@ -16,7 +16,12 @@ use CommonDoc\Container\EnvironmentFactory; use CommonDoc\Container\ExtensionPluginManager; +use CommonDoc\View\DocumentViewRenderer; +use CommonDoc\View\Page; +use CommonDoc\View\PageContext; +use CommonDoc\View\PageContextListener; use League\CommonMark\Environment\EnvironmentInterface; +use League\CommonMark\Event\DocumentPreRenderEvent; use League\CommonMark\Extension\Attributes\AttributesExtension; use League\CommonMark\Extension\Autolink\AutolinkExtension; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; @@ -30,6 +35,8 @@ use League\CommonMark\Extension\Table\TableExtension; use League\CommonMark\Extension\TableOfContents\TableOfContentsExtension; use League\CommonMark\Extension\TaskList\TaskListExtension; +use League\CommonMark\Node\Block\Document; +use Mezzio\Template\TemplateRendererInterface; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\Test; @@ -42,6 +49,11 @@ #[CoversMethod(EnvironmentFactory::class, '__invoke')] final class EnvironmentFactoryTest extends TestCase { + private PageContext $context; + private PageContextListener $listener; + private Page $page; + private DocumentViewRenderer $renderer; + /** * @return list<class-string<ExtensionInterface>> */ @@ -175,6 +187,52 @@ public function registersCoreFirstThenTheAlwaysLoadedExtensions(): void ); } + #[Test] + public function registersThePageContextListenerForThePreRenderEvent(): void + { + $environment = new EnvironmentFactory()( + $this->containerWithConfig([]), + EnvironmentInterface::class, + ); + + $document = new Document(); + $this->context->set($this->page); + + $environment->dispatch(new DocumentPreRenderEvent($document, 'html')); + + static::assertSame($this->page, $document->data->get('commondoc.page', null)); + } + + #[Test] + public function rendersTheDocumentThroughTheDocumentViewRenderer(): void + { + $environment = new EnvironmentFactory()( + $this->containerWithConfig([]), + EnvironmentInterface::class, + ); + + $renderers = [...$environment->getRenderersForClass(Document::class)]; + + static::assertNotEmpty($renderers); + static::assertSame($this->renderer, $renderers[0]); + } + + protected function setUp(): void + { + $this->page = new Page( + label : 'Install', + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/install.md', + url : '/install/', + versionLabel: '1.0', + ); + + $this->context = new PageContext(); + $this->listener = new PageContextListener($this->context); + $this->renderer = new DocumentViewRenderer($this->createStub(TemplateRendererInterface::class)); + } + /** * @param array<string, mixed> $managerSection */ @@ -188,9 +246,11 @@ private function containerWithConfig( $container ->method('get') ->willReturnCallback( - static fn(string $id): mixed => match ($id) { + fn(string $id): mixed => match ($id) { 'config' => $config, ExtensionPluginManager::class => $pluginManager, + DocumentViewRenderer::class => $this->renderer, + PageContextListener::class => $this->listener, default => null, }, ); diff --git a/test/unit/LayoutWrappingMiddlewareFactoryTest.php b/test/unit/LayoutWrappingMiddlewareFactoryTest.php deleted file mode 100644 index 7b0e062..0000000 --- a/test/unit/LayoutWrappingMiddlewareFactoryTest.php +++ /dev/null @@ -1,39 +0,0 @@ -<?php - -declare(strict_types=1); - -/** - * This file is part of the commondoc package. - * - * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> - * and contributors. - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace CommonDocTest; - -use CommonDoc\Container\LayoutWrappingMiddlewareFactory; -use CommonDoc\Middleware\LayoutWrappingMiddleware; -use PHPUnit\Framework\Attributes\CoversClass; -use PHPUnit\Framework\Attributes\CoversMethod; -use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; - -#[CoversClass(LayoutWrappingMiddlewareFactory::class)] -#[CoversMethod(LayoutWrappingMiddlewareFactory::class, '__invoke')] -final class LayoutWrappingMiddlewareFactoryTest extends TestCase -{ - #[Test] - public function buildsTheMiddleware(): void - { - $subject = new LayoutWrappingMiddlewareFactory()( - $this->createStub(ContainerInterface::class), - LayoutWrappingMiddleware::class, - ); - - static::assertInstanceOf(LayoutWrappingMiddleware::class, $subject); - } -} diff --git a/test/unit/LayoutWrappingMiddlewareTest.php b/test/unit/LayoutWrappingMiddlewareTest.php deleted file mode 100644 index 4d4e489..0000000 --- a/test/unit/LayoutWrappingMiddlewareTest.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php - -declare(strict_types=1); - -/** - * This file is part of the commondoc package. - * - * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> - * and contributors. - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace CommonDocTest; - -use CommonDoc\Command\BuildSiteCommand; -use CommonDoc\Middleware\LayoutWrappingMiddleware; -use PHPUnit\Framework\Attributes\CoversClass; -use PHPUnit\Framework\Attributes\CoversMethod; -use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\TestCase; -use Webware\MessageBus\Command\CommandResult; -use Webware\MessageBus\MessageStatus; -use Webware\MessageBus\PipelineHandlerInterface; - -#[CoversClass(LayoutWrappingMiddleware::class)] -#[CoversMethod(LayoutWrappingMiddleware::class, 'process')] -final class LayoutWrappingMiddlewareTest extends TestCase -{ - #[Test] - public function forwardsTheMessageAndReturnsTheHandlerResult(): void - { - $message = new BuildSiteCommand( - source: 'docs', - output: 'build', - ); - $result = new CommandResult( - command: $message, - status : MessageStatus::Success, - result : [], - ); - - $next = $this->createMock(PipelineHandlerInterface::class); - $next - ->expects($this->once()) - ->method('handle') - ->with($message) - ->willReturn($result); - - static::assertSame($result, new LayoutWrappingMiddleware()->process($message, $next)); - } -} diff --git a/test/unit/PageContextFactoryTest.php b/test/unit/PageContextFactoryTest.php new file mode 100644 index 0000000..84fab5a --- /dev/null +++ b/test/unit/PageContextFactoryTest.php @@ -0,0 +1,49 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the commondoc package. + * + * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest; + +use CommonDoc\Container\PageContextFactory; +use CommonDoc\View\PageContext; +use Laminas\ServiceManager\ServiceManager; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +#[CoversClass(PageContextFactory::class)] +#[CoversMethod(PageContextFactory::class, '__invoke')] +final class PageContextFactoryTest extends TestCase +{ + #[Test] + public function buildsAPageContext(): void + { + static::assertInstanceOf(PageContext::class, $this->container()->get(PageContext::class)); + } + + #[Test] + public function sharesOneContextPerContainer(): void + { + $container = $this->container(); + + static::assertSame($container->get(PageContext::class), $container->get(PageContext::class)); + } + + private function container(): ServiceManager + { + return new ServiceManager([ + 'factories' => [PageContext::class => PageContextFactory::class], + ]); + } +} diff --git a/test/unit/PageContextListenerFactoryTest.php b/test/unit/PageContextListenerFactoryTest.php new file mode 100644 index 0000000..1371186 --- /dev/null +++ b/test/unit/PageContextListenerFactoryTest.php @@ -0,0 +1,63 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the commondoc package. + * + * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest; + +use CommonDoc\Container\PageContextListenerFactory; +use CommonDoc\View\Page; +use CommonDoc\View\PageContext; +use CommonDoc\View\PageContextListener; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Node\Block\Document; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerInterface; + +#[CoversClass(PageContextListenerFactory::class)] +#[CoversMethod(PageContextListenerFactory::class, '__invoke')] +final class PageContextListenerFactoryTest extends TestCase +{ + #[Test] + public function buildsAListenerBoundToTheResolvedContext(): void + { + $page = new Page( + label : 'Reference page', + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/page.md', + url : '/page', + versionLabel: '1.0', + ); + $context = new PageContext(); + $container = $this->createStub(ContainerInterface::class); + + $context->set($page); + $container + ->method('get') + ->willReturnCallback( + static fn(string $id): mixed => PageContext::class === $id ? $context : null, + ); + + /** @var PageContextListener $listener */ + $listener = new PageContextListenerFactory()($container, PageContextListener::class); + + $document = new Document(); + + $listener(new DocumentPreRenderEvent($document, 'html')); + + static::assertSame($page, $document->data->get('commondoc.page', null)); + } +} diff --git a/test/unit/PageContextListenerTest.php b/test/unit/PageContextListenerTest.php new file mode 100644 index 0000000..43b633b --- /dev/null +++ b/test/unit/PageContextListenerTest.php @@ -0,0 +1,94 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the commondoc package. + * + * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest; + +use CommonDoc\View\Page; +use CommonDoc\View\PageContext; +use CommonDoc\View\PageContextListener; +use League\CommonMark\Event\DocumentPreRenderEvent; +use League\CommonMark\Node\Block\Document; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +#[CoversClass(PageContextListener::class)] +#[CoversMethod(PageContextListener::class, '__invoke')] +final class PageContextListenerTest extends TestCase +{ + private static function page(string $label): Page + { + return new Page( + label : $label, + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/page.md', + url : '/page', + versionLabel: '1.0', + ); + } + + #[Test] + public function keepsAPageTheDocumentAlreadyCarries(): void + { + $page = self::page('Reference page'); + $document = new Document(); + + $document->data->set('commondoc.page', $page); + + new PageContextListener(new PageContext())(new DocumentPreRenderEvent($document, 'html')); + + static::assertSame($page, $document->data->get('commondoc.page', null)); + } + + #[Test] + public function readsTheContextAtEventTimeNotConstructionTime(): void + { + $page = self::page('Reference page'); + $context = new PageContext(); + $listener = new PageContextListener($context); + $document = new Document(); + + $context->set($page); + + $listener(new DocumentPreRenderEvent($document, 'html')); + + static::assertSame($page, $document->data->get('commondoc.page', null)); + } + + #[Test] + public function writesNothingWhenNoPageIsCurrent(): void + { + $document = new Document(); + + new PageContextListener(new PageContext())(new DocumentPreRenderEvent($document, 'html')); + + static::assertFalse($document->data->has('commondoc.page')); + } + + #[Test] + public function writesTheCurrentPageIntoTheDocument(): void + { + $page = self::page('Reference page'); + $context = new PageContext(); + $document = new Document(); + + $context->set($page); + + new PageContextListener($context)(new DocumentPreRenderEvent($document, 'html')); + + static::assertSame($page, $document->data->get('commondoc.page', null)); + } +} diff --git a/test/unit/PageContextTest.php b/test/unit/PageContextTest.php new file mode 100644 index 0000000..472fd66 --- /dev/null +++ b/test/unit/PageContextTest.php @@ -0,0 +1,92 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the commondoc package. + * + * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest; + +use CommonDoc\View\Page; +use CommonDoc\View\PageContext; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +#[CoversClass(PageContext::class)] +#[CoversMethod(PageContext::class, 'set')] +#[CoversMethod(PageContext::class, 'clear')] +#[CoversMethod(PageContext::class, 'current')] +final class PageContextTest extends TestCase +{ + private static function page(string $label): Page + { + return new Page( + label : $label, + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/page.md', + url : '/page', + versionLabel: '1.0', + ); + } + + #[Test] + public function emptiesTheSlotOnClear(): void + { + $context = new PageContext(); + $context->set(self::page('Reference page')); + + $context->clear(); + + static::assertNull($context->current()); + } + + #[Test] + public function holdsThePageItWasGiven(): void + { + $page = self::page('Reference page'); + $context = new PageContext(); + + $context->set($page); + + static::assertSame($page, $context->current()); + } + + #[Test] + public function replacesTheHeldPageInsteadOfAccumulating(): void + { + $first = self::page('First page'); + $second = self::page('Second page'); + $context = new PageContext(); + + $context->set($first); + $context->set($second); + + static::assertSame($second, $context->current()); + } + + #[Test] + public function reportsNoPageWhenNothingIsSet(): void + { + static::assertNull(new PageContext()->current()); + } + + #[Test] + public function toleratesAClearOnAnEmptyContext(): void + { + $context = new PageContext(); + + $context->clear(); + + static::assertNull($context->current()); + } +} diff --git a/test/unit/PageTest.php b/test/unit/PageTest.php new file mode 100644 index 0000000..f53d048 --- /dev/null +++ b/test/unit/PageTest.php @@ -0,0 +1,200 @@ +<?php + +declare(strict_types=1); + +/** + * This file is part of the commondoc package. + * + * Copyright (c) 2026 Joey Smith <jsmith@webinertia.net> + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest; + +use Closure; +use CommonDoc\View\Page; +use Laminas\View\Model\ModelInterface; +use LogicException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +use function iterator_count; + +#[CoversClass(Page::class)] +#[CoversMethod(Page::class, 'getTemplate')] +#[CoversMethod(Page::class, 'getVariables')] +#[CoversMethod(Page::class, 'getVariable')] +#[CoversMethod(Page::class, 'getChildren')] +#[CoversMethod(Page::class, 'hasChildren')] +#[CoversMethod(Page::class, 'captureTo')] +#[CoversMethod(Page::class, 'isAppend')] +#[CoversMethod(Page::class, 'terminate')] +#[CoversMethod(Page::class, 'count')] +#[CoversMethod(Page::class, 'getIterator')] +#[CoversMethod(Page::class, 'setVariable')] +#[CoversMethod(Page::class, 'setVariables')] +#[CoversMethod(Page::class, 'setTemplate')] +#[CoversMethod(Page::class, 'addChild')] +#[CoversMethod(Page::class, 'setCaptureTo')] +#[CoversMethod(Page::class, 'setTerminal')] +#[CoversMethod(Page::class, 'setAppend')] +final class PageTest extends TestCase +{ + /** + * @return array<string, array{Closure(Page): mixed}> + */ + public static function mutators(): array + { + return [ + 'setVariable' => [static fn(Page $page): mixed => $page->setVariable('extra', 'value')], + 'setVariables' => [static fn(Page $page): mixed => $page->setVariables(['extra' => 'value'])], + 'setTemplate' => [static fn(Page $page): mixed => $page->setTemplate('other::template')], + 'addChild' => [static fn(Page $page): mixed => $page->addChild(self::leaf())], + 'setCaptureTo' => [static fn(Page $page): mixed => $page->setCaptureTo('other')], + 'setTerminal' => [static fn(Page $page): mixed => $page->setTerminal(true)], + 'setAppend' => [static fn(Page $page): mixed => $page->setAppend(append: true)], + ]; + } + + private static function leaf(string $template = 'commondoc::page'): Page + { + return new Page( + label : 'Reference page', + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/reference/page.md', + url : '/reference/page', + versionLabel: '1.0', + template : $template, + ); + } + + #[Test] + public function countsAndIteratesTheSameChildren(): void + { + $children = [self::leaf(), self::leaf()]; + $page = new Page( + label : 'Parent', + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/parent.md', + url : '/parent', + versionLabel: '1.0', + children : $children, + ); + + static::assertTrue($page->hasChildren()); + static::assertSame($children, $page->getChildren()); + static::assertSame(2, $page->count()); + static::assertSame($page->count(), iterator_count($page->getIterator())); + } + + #[Test] + public function neverProjectsTheLayoutReservedContentVariable(): void + { + static::assertArrayNotHasKey('content', self::leaf()->getVariables()); + } + + #[Test] + public function projectsThePageFieldsIntoTheVariables(): void + { + static::assertSame( + [ + 'label' => 'Reference page', + 'url' => '/reference/page', + 'projectSlug' => 'commondoc', + 'projectName' => 'CommonDoc', + 'versionLabel' => '1.0', + 'sourcePath' => 'docs/reference/page.md', + 'captureTo' => 'page', + 'append' => false, + 'terminal' => false, + 'children' => [], + ], + self::leaf()->getVariables(), + ); + } + + #[Test] + public function readsASingleVariableFromTheProjection(): void + { + $page = self::leaf(); + + static::assertSame('Reference page', $page->getVariable('label')); + static::assertSame('/reference/page', $page->getVariable('url')); + } + + /** + * @param Closure(Page): mixed $mutate + */ + #[Test] + #[DataProvider('mutators')] + public function rejectsEveryMutation(Closure $mutate): void + { + $page = self::leaf(); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot modify page "Reference page": a Page is immutable.'); + + $mutate($page); + } + + #[Test] + public function reportsNoChildrenForALeafPage(): void + { + $page = self::leaf(); + + static::assertFalse($page->hasChildren()); + static::assertSame([], $page->getChildren()); + static::assertSame(0, $page->count()); + static::assertSame(0, iterator_count($page->getIterator())); + } + + #[Test] + public function reportsTheCaptureTargetAndTheFlags(): void + { + $page = new Page( + label : 'Parent', + projectName : 'CommonDoc', + projectSlug : 'commondoc', + sourcePath : 'docs/parent.md', + url : '/parent', + versionLabel: '1.0', + append : true, + captureTo : 'sidebar', + terminal : true, + ); + + static::assertSame('sidebar', $page->captureTo()); + static::assertTrue($page->isAppend()); + static::assertTrue($page->terminate()); + } + + #[Test] + public function returnsTheConfiguredTemplateName(): void + { + static::assertSame('commondoc::page', self::leaf()->getTemplate()); + static::assertSame('site::document', self::leaf(template: 'site::document')->getTemplate()); + } + + #[Test] + public function returnsTheGivenDefaultForAnUnknownVariable(): void + { + $page = self::leaf(); + + static::assertNull($page->getVariable('missing')); + static::assertSame('fallback', $page->getVariable('missing', 'fallback')); + } + + #[Test] + public function satisfiesTheViewModelContract(): void + { + static::assertInstanceOf(ModelInterface::class, self::leaf()); + } +}
1