diff --git a/CHANGELOG.md b/CHANGELOG.md index 8558797..9334d40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,4 +21,5 @@ All notable changes are listed here. The format follows [Keep a Changelog](https - API tokens with scopes, routes, expiry and rotation (`wp headless token`). - Preview of drafts, scheduled and private posts from the front end: one-time link token, session, `GET /wp-json/headless/v1/preview/posts/{id}` (autosave, live or revision). - Revalidation: signed notifications of changes (posts, terms, menus, site options, files) to the front end, merged, off the request (Action Scheduler or WP-Cron), with retries; `wp headless revalidate ping`. +- Site manifest: `GET /wp-json/headless/v1/site` (site, languages, menus as trees, locations, front page, content types and taxonomies). - mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer. diff --git a/README.md b/README.md index 2e6849b..c6aeea1 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo | API tokens | `wp headless token create --scopes=read --routes=/wp/v2/posts --expires=90d`: `Authorization: Bearer hl.…`, as the user, limited to read or write and to route prefixes. Only a hash is stored; a wrong token answers 401, a request outside the scopes 403. `rotate` keeps the old token alive for a grace period. | | Preview | The editor's Preview button opens your front end with a one-time token; the front end trades it for a session and reads the draft, scheduled or private post, with the editor's latest autosave laid over it. See [Preview](#preview-from-your-front-end). | | Revalidation | When a post is published, updated, unpublished or deleted, or a term, a menu, a site option or a file changes, the front end is told: one signed POST, merged with the other changes of the last seconds, sent off the request, tried again if it fails. See [Revalidation](#telling-your-front-end-what-changed). | +| Site manifest | `GET /wp-json/headless/v1/site`: the site and its languages, the menus as trees with front-end paths, the menu locations, the front page and the content types with their REST routes, in one public, cacheable answer. | | URL mapper | `UrlMapper::toFront()` turns a URL of the WordPress site into the URL of the same page on the front end. It is the one place every URL the package hands out goes through. | Nothing changes on the public site until you set the front-end URL: a site that is not told where its front end lives is never locked. @@ -139,6 +140,17 @@ export async function POST(request) { Nuxt, Astro, SvelteKit or Express work the same way: verify, then purge whatever your framework caches by tag or by path. +## Reading the site once + +```js +const site = await (await fetch('https://cms.example.com/wp-json/headless/v1/site')).json(); +site.menus.find((m) => m.slug === 'main').items; // [{ id, title, url, path: '/about/', target, classes, type, object, object_id, children: [...] }] +site.locations; // [{ location: 'primary', description: 'Primary Menu', menu: 'main' }] +site.post_types; // [{ name: 'post', rest_base: 'posts', rest_namespace: 'wp/v2', has_archive, rewrite_slug, ... }] +``` + +`path` is the address on your front end (`null` for a link to another site). The answer is the same until the site changes, so it carries an `ETag`; revalidate it on the `menus`, `options` and `site:` tags of the [notifications](#telling-your-front-end-what-changed). + ## Roadmap `0.1` core · `0.2` CORS, REST security and speed, URL mapping, Polylang and WPML, API tokens · `0.3` content preview · `0.4` revalidation webhooks (this release) · `0.5` site manifest, media, blocks as JSON, redirects · `0.6` SEO (Yoast, Rank Math, AIOSEO, SEOPress, The SEO Framework) · `0.7` optional WPGraphQL, schema snapshots, forms and search · `0.8` doctor, end-to-end tests · `1.0` frozen contract. diff --git a/config/headless.php b/config/headless.php index 6c652fa..f0dd719 100644 --- a/config/headless.php +++ b/config/headless.php @@ -115,4 +115,10 @@ // More options whose change is announced, on top of the title, the permalinks, the front page and a few more. 'options' => [], ], + + // GET /wp-json/headless/v1/site: the site, its languages, its menus as trees (with front-end paths), the front page and the + // content types in one answer, public and cacheable. Only active once a front-end URL is set. + 'manifest' => [ + 'enabled' => true, + ], ]; diff --git a/src/Domain/Cache/RestCachePolicy.php b/src/Domain/Cache/RestCachePolicy.php index 69ffd75..5aad4ef 100644 --- a/src/Domain/Cache/RestCachePolicy.php +++ b/src/Domain/Cache/RestCachePolicy.php @@ -21,7 +21,7 @@ public function __construct( private int $maxAge = 60, private int $sharedMaxAge = 300, private int $staleWhileRevalidate = 60, - private array $namespaces = ['/wp/v2'], + private array $namespaces = ['/wp/v2', '/headless/v1/site', '/headless/v1/redirects', '/headless/v1/media'], private array $neverRoutes = ['/wp/v2/users/me', '/wp/v2/settings', '/wp/v2/block-renderer', '/wp/v2/search'], ) {} diff --git a/src/Domain/Manifest/MenuTree.php b/src/Domain/Manifest/MenuTree.php new file mode 100644 index 0000000..cb40bf8 --- /dev/null +++ b/src/Domain/Manifest/MenuTree.php @@ -0,0 +1,87 @@ +> $items + * @return list> + */ + public static function build(array $items): array + { + usort($items, static fn (array $a, array $b): int => [$a['order'], $a['id']] <=> [$b['order'], $b['id']]); + + $ids = array_column($items, 'id'); + $children = []; + + foreach ($items as $item) { + $parent = $item['parent'] !== $item['id'] && in_array($item['parent'], $ids, true) ? $item['parent'] : 0; + $children[$parent][] = $item; + } + + // Items that only point at each other (A under B under A) are reachable from no top: the first of them becomes one + while (($lost = array_values(array_diff($ids, self::reached($children)))) !== []) { + $first = array_values(array_filter($items, static fn (array $item): bool => $item['id'] === $lost[0]))[0]; + $children[$first['parent']] = array_values(array_filter($children[$first['parent']] ?? [], static fn (array $item): bool => $item['id'] !== $first['id'])); + $children[0][] = $first; + } + + return self::level($children, 0, []); + } + + /** + * @param array>> $children + * @return list + */ + private static function reached(array $children): array + { + $reached = []; + $queue = [0]; + + while ($queue !== []) { + $parent = array_shift($queue); + + foreach ($children[$parent] ?? [] as $item) { + if (! in_array($item['id'], $reached, true)) { + $reached[] = (int) $item['id']; + $queue[] = (int) $item['id']; + } + } + } + + return $reached; + } + + /** + * @param array>> $children + * @param list $path the items above this level, so that a cycle (A under B under A) ends + * @return list> + */ + private static function level(array $children, int $parent, array $path): array + { + $level = []; + + foreach ($children[$parent] ?? [] as $item) { + $id = (int) $item['id']; + + if (in_array($id, $path, true)) { + continue; + } + + unset($item['parent'], $item['order']); + $item['children'] = self::level($children, $id, [...$path, $id]); + $level[] = $item; + } + + return $level; + } +} diff --git a/src/Infrastructure/Config/Settings.php b/src/Infrastructure/Config/Settings.php index c3f07ef..59ce0be 100644 --- a/src/Infrastructure/Config/Settings.php +++ b/src/Infrastructure/Config/Settings.php @@ -59,6 +59,7 @@ private function __construct( public int $revalidationDebounce, public int $revalidationAttempts, public array $revalidationOptions, + public bool $manifest, ) {} /** @@ -116,6 +117,7 @@ public static function fromArray(array $config, string $backendUrl): self revalidationDebounce: max(0, self::int($revalidation, 'debounce', 3)), revalidationAttempts: min(5, max(1, self::int($revalidation, 'max_attempts', 5))), revalidationOptions: array_values(array_unique([...ChangeWatcher::defaultOptions(), ...self::strings($revalidation, 'options')])), + manifest: $front instanceof Origin && self::bool(is_array($config['manifest'] ?? null) ? $config['manifest'] : [], 'enabled', true), ); } diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index afef950..7b60ca2 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -12,6 +12,7 @@ use Pollora\Headless\Domain\Front\Origin; use Pollora\Headless\Domain\Front\UrlMapper; use Pollora\Headless\Domain\Language\Languages; +use Pollora\Headless\Domain\Language\LanguageUrls; use Pollora\Headless\Infrastructure\Config\Settings; use Pollora\Headless\Infrastructure\Config\SettingsLoader; use Pollora\Headless\Infrastructure\Language\LanguagesFactory; @@ -90,6 +91,13 @@ public static function modules(Settings $settings, ?Languages $languages = null) $modules[] = new RevalidationRunner($revalidator); } + if ($settings->manifest && $settings->urls instanceof UrlMapper && $settings->front instanceof Origin) { + $urls = $languages->isActive() + ? new LanguageUrls($settings->urls, $settings->backend, $settings->front, $settings->languageFronts, $languages) + : $settings->urls; + $modules[] = new ManifestRoutes(new SiteManifest($urls, $settings->front, $languages)); + } + if ($settings->restCache instanceof RestCachePolicy || $settings->perPageMax !== null) { $modules[] = new RestPerformance($settings->restCache, $settings->perPageMax); } diff --git a/src/Infrastructure/WordPress/ManifestRoutes.php b/src/Infrastructure/WordPress/ManifestRoutes.php new file mode 100644 index 0000000..327963f --- /dev/null +++ b/src/Infrastructure/WordPress/ManifestRoutes.php @@ -0,0 +1,35 @@ +addAction('rest_api_init', [$this, 'routes']); + } + + public function routes(): void + { + register_rest_route(self::NAMESPACE, '/site', [ + 'methods' => 'GET', + 'callback' => [$this, 'show'], + // Public on purpose: it holds what a visitor sees (menus, languages, addresses), and the front end reads it at build time. + 'permission_callback' => '__return_true', + ]); + } + + public function show(): \WP_REST_Response + { + return rest_ensure_response($this->manifest->build()); + } +} diff --git a/src/Infrastructure/WordPress/SiteManifest.php b/src/Infrastructure/WordPress/SiteManifest.php new file mode 100644 index 0000000..c773017 --- /dev/null +++ b/src/Infrastructure/WordPress/SiteManifest.php @@ -0,0 +1,222 @@ + + */ + public function build(): array + { + return [ + 'version' => 1, + 'site' => $this->site(), + 'languages' => $this->languageList(), + 'front_page' => [ + 'show_on_front' => (string) get_option('show_on_front', 'posts'), + 'page_on_front' => (int) get_option('page_on_front', 0), + 'page_for_posts' => (int) get_option('page_for_posts', 0), + 'posts_per_page' => (int) get_option('posts_per_page', 10), + ], + 'menus' => $this->menus(), + 'locations' => $this->locations(), + 'post_types' => $this->postTypes(), + 'taxonomies' => $this->taxonomies(), + 'permalink_structure' => (string) get_option('permalink_structure', ''), + ]; + } + + /** + * @return array + */ + private function site(): array + { + return [ + 'id' => get_current_blog_id(), + 'name' => get_bloginfo('name'), + 'description' => get_bloginfo('description'), + 'url' => $this->front->toString(), + 'wordpress_url' => home_url(), + 'locale' => get_locale(), + 'language' => $this->languages->current() ?? substr(get_locale(), 0, 2), + 'timezone' => wp_timezone_string(), + 'date_format' => (string) get_option('date_format'), + 'time_format' => (string) get_option('time_format'), + 'multisite' => is_multisite(), + ]; + } + + /** + * @return list> + */ + private function languageList(): array + { + if (! $this->languages->isActive()) { + return []; + } + + $list = []; + + foreach ($this->languages->all() as $code) { + $home = $this->languages->homeUrl($code); + $list[] = ['code' => $code, 'wordpress_url' => $home, 'url' => $home === null ? $this->front->toString() : $this->urls->toFront($home, $code)]; + } + + return $list; + } + + /** + * @return list> + */ + private function menus(): array + { + $menus = []; + + foreach (wp_get_nav_menus() as $menu) { + $items = []; + + foreach (wp_get_nav_menu_items($menu->term_id) ?: [] as $item) { + $url = $this->urls->toFront((string) $item->url); + + $items[] = [ + 'id' => (int) $item->ID, + 'parent' => (int) $item->menu_item_parent, + 'order' => (int) $item->menu_order, + 'title' => (string) $item->title, + 'url' => $url, + 'path' => $this->pathOnFront($url), + 'target' => (string) $item->target, + 'classes' => array_values(array_filter((array) $item->classes, static fn (mixed $class): bool => is_string($class) && $class !== '')), + 'type' => (string) $item->type, + 'object' => (string) $item->object, + 'object_id' => (int) $item->object_id, + ]; + } + + $menus[] = ['id' => $menu->term_id, 'slug' => $menu->slug, 'name' => $menu->name, 'items' => MenuTree::build($items)]; + } + + usort($menus, static fn (array $a, array $b): int => $a['slug'] <=> $b['slug']); + + return $menus; + } + + /** + * @return list + */ + private function locations(): array + { + $assigned = get_nav_menu_locations(); + $locations = []; + + foreach (get_registered_nav_menus() as $location => $description) { + $menu = isset($assigned[$location]) ? wp_get_nav_menu_object($assigned[$location]) : false; + $locations[] = ['location' => (string) $location, 'description' => (string) $description, 'menu' => $menu instanceof \WP_Term ? $menu->slug : null]; + } + + usort($locations, static fn (array $a, array $b): int => $a['location'] <=> $b['location']); + + return $locations; + } + + /** + * @return list> + */ + private function postTypes(): array + { + $types = []; + + foreach (get_post_types(['show_in_rest' => true, 'public' => true], 'objects') as $type) { + $types[] = [ + 'name' => $type->name, + 'label' => $type->label, + 'rest_base' => $type->rest_base ?: $type->name, + 'rest_namespace' => $type->rest_namespace ?: 'wp/v2', + 'hierarchical' => (bool) $type->hierarchical, + 'has_archive' => $type->has_archive, + 'rewrite_slug' => is_array($type->rewrite) ? (string) ($type->rewrite['slug'] ?? $type->name) : $type->name, + ]; + } + + usort($types, static fn (array $a, array $b): int => $a['name'] <=> $b['name']); + + return $types; + } + + /** + * @return list> + */ + private function taxonomies(): array + { + $taxonomies = []; + + foreach (get_taxonomies(['show_in_rest' => true, 'public' => true], 'objects') as $taxonomy) { + $taxonomies[] = [ + 'name' => $taxonomy->name, + 'label' => $taxonomy->label, + 'rest_base' => $taxonomy->rest_base ?: $taxonomy->name, + 'rest_namespace' => $taxonomy->rest_namespace ?: 'wp/v2', + 'hierarchical' => (bool) $taxonomy->hierarchical, + 'post_types' => array_values($taxonomy->object_type), + 'rewrite_slug' => is_array($taxonomy->rewrite) ? (string) ($taxonomy->rewrite['slug'] ?? $taxonomy->name) : $taxonomy->name, + ]; + } + + usort($taxonomies, static fn (array $a, array $b): int => $a['name'] <=> $b['name']); + + return $taxonomies; + } + + /** The path (and query) of an address on a front end of the site, null for another site. */ + private function pathOnFront(string $url): ?string + { + try { + $origin = Origin::fromUrl($url); + } catch (InvalidOriginException) { + return null; + } + + $known = [$this->front]; + + foreach ($this->languages->isActive() ? $this->languages->all() : [] as $code) { + $home = $this->languages->homeUrl($code); + + if ($home !== null) { + $known[] = Origin::fromUrl($this->urls->toFront($home, $code)); + } + } + + foreach ($known as $front) { + if ($front->sameHostAs($origin)) { + $query = parse_url($url, PHP_URL_QUERY); + + return ((string) parse_url($url, PHP_URL_PATH) ?: '/').(is_string($query) ? '?'.$query : ''); + } + } + + return null; + } +} diff --git a/tests/Integration/HeadlessInWordPressTest.php b/tests/Integration/HeadlessInWordPressTest.php index ed2f087..d1a6408 100644 --- a/tests/Integration/HeadlessInWordPressTest.php +++ b/tests/Integration/HeadlessInWordPressTest.php @@ -9,13 +9,16 @@ use Pollora\Headless\Domain\Front\Origin; use Pollora\Headless\Domain\Front\UrlMapper; use Pollora\Headless\Infrastructure\Config\Settings; +use Pollora\Headless\Infrastructure\Language\NoLanguages; use Pollora\Headless\Infrastructure\Status\StatusReport; use Pollora\Headless\Infrastructure\WordPress\Bootstrap; use Pollora\Headless\Infrastructure\WordPress\Cors; use Pollora\Headless\Infrastructure\WordPress\FrontLinks; +use Pollora\Headless\Infrastructure\WordPress\ManifestRoutes; use Pollora\Headless\Infrastructure\WordPress\RestPerformance; use Pollora\Headless\Infrastructure\WordPress\RestSecurity; use Pollora\Headless\Infrastructure\WordPress\SiteContext; +use Pollora\Headless\Infrastructure\WordPress\SiteManifest; use Pollora\Headless\Infrastructure\WordPress\TemplateRedirectGate; use Pollora\Headless\Infrastructure\WordPress\WordPressHooks; @@ -244,3 +247,63 @@ static function (string $line) use (&$lines): void { expect($response->get_status())->toBe(200) ->and(count($response->get_data()))->toBeLessThanOrEqual(3); }); + +function manifestRequest(): WP_REST_Response +{ + $mapper = new UrlMapper(Origin::fromUrl(home_url()), Origin::fromUrl('https://www.example.com')); + $manifest = new SiteManifest($mapper, Origin::fromUrl('https://www.example.com'), new NoLanguages); + (new ManifestRoutes($manifest))->register(new WordPressHooks); + + $GLOBALS['wp_rest_server'] = null; + rest_get_server(); + + return rest_do_request(new WP_REST_Request('GET', '/headless/v1/site')); +} + +it('serves the manifest of the site to a visitor: menus as trees with front-end paths, locations, content types', function (): void { + register_nav_menu('headless_primary', 'Primary (test)'); + $page = wp_insert_post(['post_title' => 'About Us', 'post_type' => 'page', 'post_status' => 'publish', 'post_name' => 'about-us']); + $menu = wp_create_nav_menu('Headless Main'); + $parent = wp_update_nav_menu_item($menu, 0, ['menu-item-title' => 'About', 'menu-item-object' => 'page', 'menu-item-object-id' => $page, 'menu-item-type' => 'post_type', 'menu-item-status' => 'publish', 'menu-item-position' => 1]); + wp_update_nav_menu_item($menu, 0, ['menu-item-title' => 'Docs', 'menu-item-url' => home_url('/docs/'), 'menu-item-type' => 'custom', 'menu-item-status' => 'publish', 'menu-item-parent-id' => $parent, 'menu-item-position' => 2]); + wp_update_nav_menu_item($menu, 0, ['menu-item-title' => 'Elsewhere', 'menu-item-url' => 'https://other.example.org/x', 'menu-item-type' => 'custom', 'menu-item-status' => 'publish', 'menu-item-position' => 3]); + set_theme_mod('nav_menu_locations', ['headless_primary' => $menu]); + wp_set_current_user(0); + + $response = manifestRequest(); + $data = $response->get_data(); + $main = array_values(array_filter($data['menus'], static fn (array $m): bool => $m['slug'] === 'headless-main'))[0]; + $location = array_values(array_filter($data['locations'], static fn (array $l): bool => $l['location'] === 'headless_primary'))[0]; + + set_theme_mod('nav_menu_locations', []); + wp_delete_nav_menu($menu); + wp_delete_post($page, true); + unregister_nav_menu('headless_primary'); + + expect($response->get_status())->toBe(200) + ->and($data['version'])->toBe(1) + ->and($data['site']['url'])->toBe('https://www.example.com') + ->and($data['site']['wordpress_url'])->toBe(home_url()) + ->and($data['site']['multisite'])->toBeFalse() + ->and($main['items'])->toHaveCount(2) + ->and($main['items'][0]['title'])->toBe('About') + ->and($main['items'][0]['url'])->toStartWith('https://www.example.com/') + ->and($main['items'][0]['path'])->toStartWith('/') + ->and($main['items'][0]['object_id'])->toBe($page) + ->and($main['items'][0]['children'])->toHaveCount(1) + ->and($main['items'][0]['children'][0]['url'])->toBe('https://www.example.com/docs/') + ->and($main['items'][0]['children'][0]['path'])->toBe('/docs/') + ->and($main['items'][1]['url'])->toBe('https://other.example.org/x') + ->and($main['items'][1]['path'])->toBeNull() + ->and($location)->toMatchArray(['menu' => 'headless-main', 'description' => 'Primary (test)']) + ->and(array_column($data['post_types'], 'name'))->toContain('post', 'page') + ->and(array_column($data['taxonomies'], 'name'))->toContain('category', 'post_tag') + ->and($data['post_types'][array_search('post', array_column($data['post_types'], 'name'), true)])->toMatchArray(['rest_base' => 'posts', 'rest_namespace' => 'wp/v2']); +}); + +it('answers the manifest the same twice, so that its ETag holds', function (): void { + $first = manifestRequest()->get_data(); + $second = manifestRequest()->get_data(); + + expect(json_encode($second))->toBe(json_encode($first)); +}); diff --git a/tests/Unit/Domain/MenuTreeTest.php b/tests/Unit/Domain/MenuTreeTest.php new file mode 100644 index 0000000..4f06f27 --- /dev/null +++ b/tests/Unit/Domain/MenuTreeTest.php @@ -0,0 +1,59 @@ + $id, 'parent' => $parent, 'order' => $order, 'title' => $title ?: "Item $id"]; +} + +/** @return list> */ +function titles(array $tree): array +{ + return array_map(static fn (array $node): array => $node['children'] === [] ? [$node['title']] : [$node['title'] => titles($node['children'])], $tree); +} + +it('nests the items under their parent, in the editor\'s order', function (): void { + $tree = MenuTree::build([ + menuItem(3, 1, 2, 'Team'), + menuItem(1, 0, 1, 'About'), + menuItem(2, 0, 3, 'Contact'), + menuItem(4, 1, 1, 'History'), + menuItem(5, 4, 1, 'Founders'), + ]); + + expect(titles($tree))->toBe([['About' => [['History' => [['Founders']]], ['Team']]], ['Contact']]); +}); + +it('drops the fields that only served to build the tree', function (): void { + $tree = MenuTree::build([menuItem(1, 0, 1)]); + + expect($tree[0])->toBe(['id' => 1, 'title' => 'Item 1', 'children' => []]); +}); + +it('puts an item whose parent is gone at the top', function (): void { + $tree = MenuTree::build([menuItem(1, 0, 1), menuItem(2, 99, 2)]); + + expect(array_column($tree, 'id'))->toBe([1, 2]); +}); + +it('keeps a stable order for items at the same position', function (): void { + $tree = MenuTree::build([menuItem(7, 0, 1), menuItem(5, 0, 1), menuItem(6, 0, 1)]); + + expect(array_column($tree, 'id'))->toBe([5, 6, 7]); +}); + +it('does not loop on an item that is its own parent, or on a cycle', function (): void { + $self = MenuTree::build([menuItem(1, 1, 1)]); + $cycle = MenuTree::build([menuItem(1, 2, 1), menuItem(2, 1, 2)]); + + expect(array_column($self, 'id'))->toBe([1]) + ->and($self[0]['children'])->toBe([]) + ->and(titles($cycle))->toBe([['Item 1' => [['Item 2']]]]); +}); + +it('builds an empty tree from no item', function (): void { + expect(MenuTree::build([]))->toBe([]); +}); diff --git a/tests/Unit/Infrastructure/ManifestRoutesTest.php b/tests/Unit/Infrastructure/ManifestRoutesTest.php new file mode 100644 index 0000000..1bf6d5e --- /dev/null +++ b/tests/Unit/Infrastructure/ManifestRoutesTest.php @@ -0,0 +1,70 @@ +once(); + $routes = new ManifestRoutes(manifestFor()); + $routes->register(new WordPressHooks); + + Functions\expect('register_rest_route')->once()->with('headless/v1', '/site', Mockery::on(static fn (array $args): bool => $args['methods'] === 'GET' && $args['permission_callback'] === '__return_true')); + $routes->routes(); +}); + +it('answers with the manifest', function (): void { + Functions\when('rest_ensure_response')->alias(static function (array $data): WP_REST_Response { + $response = Mockery::mock('WP_REST_Response'); + $response->shouldReceive('get_data')->andReturn($data); + + return $response; + }); + Functions\when('get_current_blog_id')->justReturn(1); + Functions\when('get_bloginfo')->alias(static fn (string $key): string => $key === 'name' ? 'My site' : 'Just another site'); + Functions\when('home_url')->justReturn('https://cms.example.com'); + Functions\when('get_locale')->justReturn('fr_FR'); + Functions\when('wp_timezone_string')->justReturn('Europe/Paris'); + Functions\when('is_multisite')->justReturn(false); + Functions\when('get_option')->alias(static fn (string $name, mixed $default = false): mixed => match ($name) { + 'show_on_front' => 'page', + 'page_on_front' => '7', + 'posts_per_page' => '12', + default => $default, + }); + Functions\when('wp_get_nav_menus')->justReturn([]); + Functions\when('get_nav_menu_locations')->justReturn([]); + Functions\when('get_registered_nav_menus')->justReturn(['primary' => 'Primary Menu']); + Functions\when('get_post_types')->justReturn([]); + Functions\when('get_taxonomies')->justReturn([]); + + $manifest = (new ManifestRoutes(manifestFor()))->show()->get_data(); + + expect($manifest['version'])->toBe(1) + ->and($manifest['site'])->toMatchArray(['id' => 1, 'name' => 'My site', 'url' => 'https://www.example.com', 'wordpress_url' => 'https://cms.example.com', 'locale' => 'fr_FR', 'language' => 'fr', 'timezone' => 'Europe/Paris']) + ->and($manifest['front_page'])->toBe(['show_on_front' => 'page', 'page_on_front' => 7, 'page_for_posts' => 0, 'posts_per_page' => 12]) + ->and($manifest['locations'])->toBe([['location' => 'primary', 'description' => 'Primary Menu', 'menu' => null]]) + ->and($manifest['languages'])->toBe([]) + ->and($manifest['menus'])->toBe([]); +}); + +it('is on once a front end is set, and can be switched off', function (): void { + expect(Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com')->manifest)->toBeTrue() + ->and(Settings::fromArray(['frontend_url' => 'https://www.example.com', 'manifest' => ['enabled' => false]], 'https://cms.example.com')->manifest)->toBeFalse() + ->and(Settings::fromArray([], 'https://cms.example.com')->manifest)->toBeFalse(); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 912bb4c..49c08b0 100644 --- a/tests/Unit/Infrastructure/ModulesTest.php +++ b/tests/Unit/Infrastructure/ModulesTest.php @@ -120,10 +120,10 @@ function gateFor(FrontMode $mode, array &$ended): TemplateRedirectGate Functions\when('wp_salt')->justReturn('salt'); $settings = Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com'); - expect(Bootstrap::modules($settings))->toHaveCount(10); + expect(Bootstrap::modules($settings))->toHaveCount(11); Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->twice(); + Actions\expectAdded('rest_api_init')->times(3); Filters\expectAdded('preview_post_link')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('rest_post_dispatch')->once();