From 91d0cdf9e3bcacedf30c0008427f415ef09e8492 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Tue, 24 Nov 2026 17:35:36 +0100 Subject: [PATCH] feat: SEO metadata in one shape (0.6) - Seo and SeoMapper: Yoast, All in One SEO, SEOPress and Rank Math (its head HTML) read into the same keys; every address moved to the front end (canonical, og, images, structured data, breadcrumbs) - Providers read each plugin's documented REST output from inside; headless_seo field on posts and terms, computed when _fields names it - RankMathRedirects joins the redirects of the site - The package's robots.txt answer runs last: Yoast adds its own lines --- .github/workflows/harness.yml | 2 +- CHANGELOG.md | 1 + README.md | 26 +- config/headless.php | 8 + src/Domain/Seo/Seo.php | 105 ++++++++ src/Domain/Seo/SeoMapper.php | 255 ++++++++++++++++++ src/Domain/Seo/SeoProvider.php | 20 ++ src/Infrastructure/Config/Settings.php | 2 + .../Redirect/RankMathRedirects.php | 54 ++++ src/Infrastructure/Seo/InternalRest.php | 38 +++ src/Infrastructure/Seo/JsonFieldProvider.php | 54 ++++ src/Infrastructure/Seo/NoSeo.php | 34 +++ src/Infrastructure/Seo/RankMathProvider.php | 50 ++++ src/Infrastructure/Seo/SeoProviders.php | 32 +++ src/Infrastructure/Seo/SeopressProvider.php | 42 +++ src/Infrastructure/WordPress/Bootstrap.php | 11 +- .../WordPress/PublicSurface.php | 3 +- src/Infrastructure/WordPress/SeoField.php | 68 +++++ tests/Integration/SeoTest.php | 77 ++++++ tests/Unit/Domain/SeoMapperTest.php | 132 +++++++++ tests/Unit/Infrastructure/ModulesTest.php | 4 +- .../Infrastructure/SeoInfrastructureTest.php | 138 ++++++++++ 22 files changed, 1149 insertions(+), 7 deletions(-) create mode 100644 src/Domain/Seo/Seo.php create mode 100644 src/Domain/Seo/SeoMapper.php create mode 100644 src/Domain/Seo/SeoProvider.php create mode 100644 src/Infrastructure/Redirect/RankMathRedirects.php create mode 100644 src/Infrastructure/Seo/InternalRest.php create mode 100644 src/Infrastructure/Seo/JsonFieldProvider.php create mode 100644 src/Infrastructure/Seo/NoSeo.php create mode 100644 src/Infrastructure/Seo/RankMathProvider.php create mode 100644 src/Infrastructure/Seo/SeoProviders.php create mode 100644 src/Infrastructure/Seo/SeopressProvider.php create mode 100644 src/Infrastructure/WordPress/SeoField.php create mode 100644 tests/Integration/SeoTest.php create mode 100644 tests/Unit/Domain/SeoMapperTest.php create mode 100644 tests/Unit/Infrastructure/SeoInfrastructureTest.php diff --git a/.github/workflows/harness.yml b/.github/workflows/harness.yml index af7724d..68ca0e3 100644 --- a/.github/workflows/harness.yml +++ b/.github/workflows/harness.yml @@ -17,6 +17,6 @@ jobs: uses: Pollora/harness/.github/workflows/php-package.yml@v0.1.35 with: wordpress-integration: tests/Integration - wordpress-plugins: polylang,action-scheduler + wordpress-plugins: polylang,action-scheduler,wordpress-seo permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index 021f4be..c175cd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,4 +25,5 @@ All notable changes are listed here. The format follows [Keep a Changelog](https - Redirects: rules managed with `wp headless redirect`, the old slugs of renamed posts, `GET /wp-json/headless/v1/redirects` and `/redirects/resolve`. - Media: `GET /wp-json/headless/v1/media/{id}` (one shape for every kind, with the focal point of `pollora/media`), the `headless_featured_media` field, and `media.cdn_url` to serve the uploads from a CDN. - Blocks as stable JSON: the field `headless_blocks` of a post, when `_fields` names it. +- SEO metadata in one shape (`headless_seo` on posts and terms) from Yoast SEO, Rank Math, All in One SEO and SEOPress, with every address on the front end; the redirections of Rank Math join the site's redirects. - mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer. diff --git a/README.md b/README.md index d7f7870..2dbf91c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Prepare WordPress for headless mode: lock the public front, remove what a headless site does not use, and (in the releases to come) secure and speed up the API, preview drafts from a JS front end and tell it when content changes. -> **Status: `0.5`, not released.** The front gate and clean-up (0.1), CORS, REST security and speed, front-end links, multilingual sites and API tokens (0.2), the preview of drafts (0.3), the notifications of changes (0.4) and the normalised content (site manifest, redirects, media, blocks: 0.5) are in. The API may change until `1.0`. The roadmap below says what comes next; the API may change until `1.0`. +> **Status: `0.6`, not released.** The front gate and clean-up (0.1), CORS, REST security and speed, front-end links, multilingual sites and API tokens (0.2), the preview of drafts (0.3), the notifications of changes (0.4) the normalised content (site manifest, redirects, media, blocks: 0.5) and the SEO metadata (0.6) are in. The API may change until `1.0`. The roadmap below says what comes next; the API may change until `1.0`. It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollora.dev) project, with the same core. Any Node application can use it: the contract is plain HTTP, no client library is needed. @@ -27,6 +27,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo | Redirects | The redirects of the site for a front end: the ones you manage (`wp headless redirect add /old/ /new/`, patterns, 410 for a page that is gone) and the old addresses WordPress remembers for renamed posts, at `GET /wp-json/headless/v1/redirects` (every rule) and `/redirects/resolve?path=/old/` (one path). | | Media | A file of the library in one shape whatever its kind (`GET /wp-json/headless/v1/media/{id}`: url, sizes, srcset, alt, caption, the focal point set with `pollora/media`), the featured image of a post in full without a second request, and the uploads served from a CDN. | | Blocks | The blocks of a post as JSON that does not change shape: `?_fields=id,headless_blocks`. See [Blocks](#blocks-as-json). | +| SEO | The search and social metadata of a post or a term in one shape whichever plugin runs (Yoast SEO, Rank Math, All in One SEO, SEOPress), with every address on the front end: `?_fields=id,headless_seo`. See [SEO](#seo-metadata). | | 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. @@ -200,9 +201,30 @@ post.headless_blocks; Every block has the same keys in the same order. `id` is its position (`1.0` is the first block inside the second): a key for a list. `attributes` are those of the block comment, completed with the defaults of the block type, `{}` when there are none; a value a block takes from its HTML (the text of a paragraph) is in `html`. `html` is the block's own HTML; `rendered` is what WordPress prints for it, inner blocks included, and is present on top-level blocks and on dynamic blocks (a list of posts has no HTML of its own). Text outside blocks (classic content) is one `core/freeform` block. A post with a password gives `null`. The field is computed only when `_fields` names it. It is not in the preview answer. +## SEO metadata + +```js +const post = await (await fetch('https://cms.example.com/wp-json/wp/v2/posts/12?_fields=id,headless_seo')).json(); +post.headless_seo; +// { source: 'yoast', title, description, robots: { index: true, follow: true, directives: ['max-image-preview:large'] }, canonical, +// open_graph: { type, title, description, url, site_name, locale, images: [{ url, width, height, alt }] }, +// twitter: { card, title, description, image, site, creator }, json_ld: [ …nodes of the structured data graph ], breadcrumbs: [{ label, url }] } +``` + +The keys are the same whichever plugin gave them, and `null` when it has nothing. Every address (canonical, `og:url`, images, the `@id` and `url` of the structured data, the breadcrumbs) is moved from the WordPress host to your front end, which the plugins do not do. The same field is on terms (`/wp/v2/categories/5?_fields=id,headless_seo`). It is computed only when `_fields` names it. + +| Plugin | Read from | Verified | +| --- | --- | --- | +| Yoast SEO | its `yoast_head_json` REST field | against the real plugin, in CI | +| Rank Math | its `/rankmath/v1/getHead` route (turn on *Headless Support* in its general settings) | not run against the plugin: unit tests on the head it prints | +| All in One SEO | its `aioseo_head_json` REST field | not run against the plugin: unit tests, read from its documentation | +| SEOPress | its `/seopress/v1/posts/{id}` and `/terms/{id}` routes | not run against the plugin: unit tests | + +The Rank Math redirections of its manager (exact and pattern ones) join the [redirects](#redirects) of the site. The redirections of Yoast Premium, All in One SEO Pro and SEOPress are not read yet, and The SEO Framework is not supported yet. + ## 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 · `0.5` site manifest, redirects, media, blocks as JSON (this release) · `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. +`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 · `0.5` site manifest, redirects, media, blocks as JSON · `0.6` SEO: Yoast, Rank Math, AIOSEO, SEOPress (this release) · `0.7` optional WPGraphQL, schema snapshots, forms and search · `0.8` doctor, end-to-end tests · `1.0` frozen contract. ## Quality diff --git a/config/headless.php b/config/headless.php index fb5799d..85bd3e6 100644 --- a/config/headless.php +++ b/config/headless.php @@ -144,4 +144,12 @@ 'blocks' => [ 'enabled' => true, ], + + // The search and social metadata of a post or a term in one shape whichever SEO plugin runs (Yoast SEO, Rank Math, All in One SEO, + // SEOPress), in the field `headless_seo` of its REST answer when _fields names it, with every address on the front end: + // /wp-json/wp/v2/posts/12?_fields=id,headless_seo. Rank Math needs "Headless Support" on in its general settings; its redirections + // join the redirects of the site. Only active once a front-end URL is set. + 'seo' => [ + 'enabled' => true, + ], ]; diff --git a/src/Domain/Seo/Seo.php b/src/Domain/Seo/Seo.php new file mode 100644 index 0000000..0554fe9 --- /dev/null +++ b/src/Domain/Seo/Seo.php @@ -0,0 +1,105 @@ + $directives robots directives other than index and follow, such as `max-image-preview:large` + * @param array{type: ?string, title: ?string, description: ?string, url: ?string, site_name: ?string, locale: ?string, images: list} $openGraph + * @param array{card: ?string, title: ?string, description: ?string, image: ?string, site: ?string, creator: ?string} $twitter + * @param list> $jsonLd the nodes of the structured data graph + * @param list $breadcrumbs + */ + public function __construct( + public string $source, + public ?string $title = null, + public ?string $description = null, + public bool $index = true, + public bool $follow = true, + public array $directives = [], + public ?string $canonical = null, + public array $openGraph = ['type' => null, 'title' => null, 'description' => null, 'url' => null, 'site_name' => null, 'locale' => null, 'images' => []], + public array $twitter = ['card' => null, 'title' => null, 'description' => null, 'image' => null, 'site' => null, 'creator' => null], + public array $jsonLd = [], + public array $breadcrumbs = [], + ) {} + + /** + * @param Closure(string): string $map moves an address of the WordPress host to the front end + */ + public function withUrls(Closure $map): self + { + $url = static fn (?string $value): ?string => $value === null ? null : $map($value); + $openGraph = $this->openGraph; + $openGraph['url'] = $url($openGraph['url']); + $openGraph['images'] = array_map(static fn (array $image): array => [...$image, 'url' => $map($image['url'])], $openGraph['images']); + $twitter = $this->twitter; + $twitter['image'] = $url($twitter['image']); + + return new self( + $this->source, + $this->title, + $this->description, + $this->index, + $this->follow, + $this->directives, + $url($this->canonical), + $openGraph, + $twitter, + self::walk($this->jsonLd, $map), + array_map(static fn (array $crumb): array => ['label' => $crumb['label'], 'url' => $url($crumb['url'])], $this->breadcrumbs), + ); + } + + /** + * @return array + */ + public function toArray(): array + { + return [ + 'source' => $this->source, + 'title' => $this->title, + 'description' => $this->description, + 'robots' => ['index' => $this->index, 'follow' => $this->follow, 'directives' => $this->directives], + 'canonical' => $this->canonical, + 'open_graph' => $this->openGraph, + 'twitter' => $this->twitter, + 'json_ld' => $this->jsonLd, + 'breadcrumbs' => $this->breadcrumbs, + ]; + } + + /** + * Applies the mapping to every string of the structured data that is an address. + * + * @param array $value + * @param Closure(string): string $map + * @return array + */ + private static function walk(array $value, Closure $map): array + { + foreach ($value as $key => $item) { + if (is_array($item)) { + $value[$key] = self::walk($item, $map); + } elseif (is_string($item) && preg_match('#\Ahttps?://#i', $item) === 1) { + $value[$key] = $map($item); + } elseif ($item instanceof stdClass) { + $value[$key] = $item; + } + } + + return $value; + } +} diff --git a/src/Domain/Seo/SeoMapper.php b/src/Domain/Seo/SeoMapper.php new file mode 100644 index 0000000..20423b6 --- /dev/null +++ b/src/Domain/Seo/SeoMapper.php @@ -0,0 +1,255 @@ + $json + */ + public static function yoast(array $json): Seo + { + $robots = is_array($json['robots'] ?? null) ? $json['robots'] : []; + $directives = []; + + foreach ($robots as $key => $value) { + if ($key !== 'index' && $key !== 'follow' && is_string($value) && $value !== '') { + $directives[] = $value; + } + } + + $schema = is_array($json['schema'] ?? null) ? $json['schema'] : []; + $graph = is_array($schema['@graph'] ?? null) ? array_values(array_filter($schema['@graph'], is_array(...))) : []; + + return new Seo( + 'yoast', + // Yoast leaves `title` out when the page has the default one: the title of the social card is then the page's + self::text($json['title'] ?? null) ?? self::text($json['og_title'] ?? null), + self::text($json['description'] ?? null), + ($robots['index'] ?? 'index') !== 'noindex', + ($robots['follow'] ?? 'follow') !== 'nofollow', + $directives, + self::text($json['canonical'] ?? null), + self::openGraph($json, 'og_', is_array($json['og_image'] ?? null) ? $json['og_image'] : []), + self::twitter($json, 'twitter_', self::first($json['twitter_misc'] ?? null)), + $graph, + self::yoastBreadcrumbs($graph), + ); + } + + /** + * All in One SEO: its `aioseo_head_json`. Read from its documentation: every key is optional. + * + * @param array $json + */ + public static function aioseo(array $json): Seo + { + $robots = $json['robots'] ?? []; + $robots = is_array($robots) ? implode(',', array_map(strval(...), array_filter($robots, is_scalar(...)))) : (string) $robots; + + $directives = array_values(array_filter(array_map(trim(...), explode(',', $robots)), static fn (string $d): bool => $d !== '' && ! in_array($d, ['index', 'follow', 'noindex', 'nofollow'], true))); + $schema = is_array($json['schema'] ?? null) ? $json['schema'] : []; + $graph = is_array($schema['@graph'] ?? null) ? array_values(array_filter($schema['@graph'], is_array(...))) : []; + $image = self::text($json['og_image_url'] ?? null); + + return new Seo( + 'aioseo', + self::text($json['title'] ?? null), + self::text($json['description'] ?? null), + ! str_contains($robots, 'noindex'), + ! str_contains($robots, 'nofollow'), + $directives, + self::text($json['canonical_url'] ?? null), + self::openGraph($json, 'og_', $image === null ? [] : [['url' => $image, 'width' => $json['og_image_width'] ?? null, 'height' => $json['og_image_height'] ?? null]]), + self::twitter($json, 'twitter_', self::text($json['twitter_image_url'] ?? null)), + $graph, + self::yoastBreadcrumbs($graph), + ); + } + + /** + * SEOPress: the `data` of its `/seopress/v1/posts/{id}` route. + * + * @param array $data + */ + public static function seopress(array $data): Seo + { + $robots = is_array($data['robots'] ?? null) ? $data['robots'] : []; + $og = is_array($data['og'] ?? null) ? $data['og'] : []; + $tw = is_array($data['twitter'] ?? null) ? $data['twitter'] : []; + $image = self::text($og['image'] ?? null); + $crumbs = []; + + foreach (is_array($data['breadcrumbs'] ?? null) ? $data['breadcrumbs'] : [] as $crumb) { + if (is_array($crumb) && is_string($crumb['name'] ?? $crumb['label'] ?? null)) { + $crumbs[] = ['label' => (string) ($crumb['name'] ?? $crumb['label']), 'url' => self::text($crumb['url'] ?? null)]; + } + } + + return new Seo( + 'seopress', + self::text($data['title'] ?? null), + self::text($data['description'] ?? null), + ! self::truthy($robots['noindex'] ?? null), + ! self::truthy($robots['nofollow'] ?? null), + [], + self::text($data['canonical'] ?? null), + ['type' => self::text($og['type'] ?? null), 'title' => self::text($og['title'] ?? null), 'description' => self::text($og['description'] ?? null), 'url' => self::text($og['url'] ?? null), 'site_name' => self::text($og['site_name'] ?? null), 'locale' => null, 'images' => $image === null ? [] : [['url' => $image, 'width' => null, 'height' => null, 'alt' => null]]], + ['card' => self::text($tw['card'] ?? null), 'title' => self::text($tw['title'] ?? null), 'description' => self::text($tw['description'] ?? null), 'image' => self::text($tw['image'] ?? null), 'site' => null, 'creator' => null], + [], + $crumbs, + ); + } + + /** + * Rank Math: the head it prints (its `/rankmath/v1/getHead` route gives HTML only). + */ + public static function headHtml(string $html, string $source = 'rankmath'): Seo + { + $meta = []; + + if (preg_match_all('#]*?)/?>#is', $html, $tags) > 0) { + foreach ($tags[1] as $attributes) { + $name = self::attribute($attributes, 'name') ?? self::attribute($attributes, 'property'); + $content = self::attribute($attributes, 'content'); + + if ($name !== null && $content !== null) { + $meta[$name][] = html_entity_decode($content, ENT_QUOTES | ENT_HTML5); + } + } + } + + $canonical = preg_match('#]*rel=["\']canonical["\'][^>]*href=["\']([^"\']+)["\']#i', $html, $c) === 1 ? html_entity_decode($c[1]) : null; + $title = preg_match('#]*>(.*?)#is', $html, $t) === 1 ? trim(html_entity_decode($t[1], ENT_QUOTES | ENT_HTML5)) : null; + $robots = strtolower($meta['robots'][0] ?? ''); + $directives = array_values(array_filter(array_map(trim(...), explode(',', $robots)), static fn (string $d): bool => $d !== '' && ! in_array($d, ['index', 'follow', 'noindex', 'nofollow'], true))); + $graph = []; + + if (preg_match_all('#]*type=["\']application/ld\+json["\'][^>]*>(.*?)#is', $html, $scripts) > 0) { + foreach ($scripts[1] as $script) { + $decoded = json_decode(trim($script), true); + $nodes = is_array($decoded['@graph'] ?? null) ? $decoded['@graph'] : (is_array($decoded) ? [$decoded] : []); + array_push($graph, ...array_values(array_filter($nodes, is_array(...)))); + } + } + + $images = []; + + foreach ($meta['og:image'] ?? [] as $i => $url) { + $images[] = ['url' => $url, 'width' => isset($meta['og:image:width'][$i]) ? (int) $meta['og:image:width'][$i] : null, 'height' => isset($meta['og:image:height'][$i]) ? (int) $meta['og:image:height'][$i] : null, 'alt' => $meta['og:image:alt'][$i] ?? null]; + } + + return new Seo( + $source, + $title !== '' ? $title : null, + $meta['description'][0] ?? null, + ! str_contains($robots, 'noindex'), + ! str_contains($robots, 'nofollow'), + $directives, + $canonical, + ['type' => $meta['og:type'][0] ?? null, 'title' => $meta['og:title'][0] ?? null, 'description' => $meta['og:description'][0] ?? null, 'url' => $meta['og:url'][0] ?? null, 'site_name' => $meta['og:site_name'][0] ?? null, 'locale' => $meta['og:locale'][0] ?? null, 'images' => $images], + ['card' => $meta['twitter:card'][0] ?? null, 'title' => $meta['twitter:title'][0] ?? null, 'description' => $meta['twitter:description'][0] ?? null, 'image' => $meta['twitter:image'][0] ?? null, 'site' => $meta['twitter:site'][0] ?? null, 'creator' => $meta['twitter:creator'][0] ?? null], + $graph, + self::yoastBreadcrumbs($graph), + ); + } + + /** + * @param array $json + * @param array $images + * @return array{type: ?string, title: ?string, description: ?string, url: ?string, site_name: ?string, locale: ?string, images: list} + */ + private static function openGraph(array $json, string $prefix, array $images): array + { + $list = []; + + foreach ($images as $image) { + if (is_array($image) && is_string($image['url'] ?? null) && $image['url'] !== '') { + $list[] = ['url' => $image['url'], 'width' => is_numeric($image['width'] ?? null) ? (int) $image['width'] : null, 'height' => is_numeric($image['height'] ?? null) ? (int) $image['height'] : null, 'alt' => self::text($image['alt'] ?? null)]; + } + } + + return [ + 'type' => self::text($json[$prefix.'type'] ?? null), + 'title' => self::text($json[$prefix.'title'] ?? null), + 'description' => self::text($json[$prefix.'description'] ?? null), + 'url' => self::text($json[$prefix.'url'] ?? null), + 'site_name' => self::text($json[$prefix.'site_name'] ?? null), + 'locale' => self::text($json[$prefix.'locale'] ?? null), + 'images' => $list, + ]; + } + + /** + * @param array $json + * @return array{card: ?string, title: ?string, description: ?string, image: ?string, site: ?string, creator: ?string} + */ + private static function twitter(array $json, string $prefix, mixed $image): array + { + $image ??= $json[$prefix.'image'] ?? null; + + return [ + 'card' => self::text($json[$prefix.'card'] ?? null), + 'title' => self::text($json[$prefix.'title'] ?? null), + 'description' => self::text($json[$prefix.'description'] ?? null), + 'image' => self::text(is_array($image) ? ($image['url'] ?? null) : $image), + 'site' => self::text($json[$prefix.'site'] ?? null), + 'creator' => self::text($json[$prefix.'creator'] ?? null), + ]; + } + + /** + * @param list> $graph + * @return list + */ + private static function yoastBreadcrumbs(array $graph): array + { + foreach ($graph as $node) { + $types = (array) ($node['@type'] ?? []); + + if (in_array('BreadcrumbList', $types, true) && is_array($node['itemListElement'] ?? null)) { + $crumbs = []; + + foreach ($node['itemListElement'] as $item) { + $thing = is_array($item['item'] ?? null) ? $item['item'] : []; + $label = $item['name'] ?? $thing['name'] ?? null; + + if (is_string($label)) { + $crumbs[] = ['label' => $label, 'url' => self::text(is_string($item['item'] ?? null) ? $item['item'] : ($thing['@id'] ?? null))]; + } + } + + return $crumbs; + } + } + + return []; + } + + private static function attribute(string $attributes, string $name): ?string + { + return preg_match('#(?:^|\s)'.preg_quote($name, '#').'=(["\'])(.*?)\1#is', $attributes, $m) === 1 ? $m[2] : null; + } + + private static function text(mixed $value): ?string + { + return is_string($value) && trim($value) !== '' ? $value : null; + } + + private static function truthy(mixed $value): bool + { + return in_array($value, [true, 1, '1', 'yes', 'true'], true); + } + + private static function first(mixed $value): mixed + { + return is_array($value) ? ($value[0] ?? null) : null; + } +} diff --git a/src/Domain/Seo/SeoProvider.php b/src/Domain/Seo/SeoProvider.php new file mode 100644 index 0000000..88fb1d3 --- /dev/null +++ b/src/Domain/Seo/SeoProvider.php @@ -0,0 +1,20 @@ +prefix.'rank_math_redirections'; + + if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table))) !== $table) { + return []; + } + + $rows = $wpdb->get_results($wpdb->prepare("SELECT sources, url_to, header_code FROM `{$table}` WHERE status = %s ORDER BY id ASC LIMIT %d", 'active', self::LIMIT)); + $rules = []; + + foreach (is_array($rows) ? $rows : [] as $row) { + $sources = maybe_unserialize($row->sources); + + foreach (is_array($sources) ? $sources : [] as $source) { + $comparison = is_array($source) ? ($source['comparison'] ?? '') : ''; + $pattern = is_array($source) ? (string) ($source['pattern'] ?? '') : ''; + + if (($comparison !== 'exact' && $comparison !== 'regex') || $pattern === '') { + continue; + } + + try { + $rules[] = new Redirect('/'.ltrim($pattern, '/'), (string) $row->url_to, (int) $row->header_code, $comparison === 'regex', 'rankmath'); + } catch (\InvalidArgumentException) { + // A rule that cannot be one here (a destination that is not an address, a status that is not a redirect): left out + continue; + } + } + } + + return $rules; + } +} diff --git a/src/Infrastructure/Seo/InternalRest.php b/src/Infrastructure/Seo/InternalRest.php new file mode 100644 index 0000000..993ffff --- /dev/null +++ b/src/Infrastructure/Seo/InternalRest.php @@ -0,0 +1,38 @@ + $params + * @return array|null null when the route answers an error or something that is not an object + */ + public static function get(string $route, array $params = []): ?array + { + $request = new \WP_REST_Request('GET', $route); + + foreach ($params as $key => $value) { + $request->set_param($key, $value); + } + + $response = rest_do_request($request); + $data = $response->get_data(); + + return ! $response->is_error() && is_array($data) ? $data : null; + } + + /** + * One field of the REST answer for a post or a term. + */ + public static function field(string $route, string $field): mixed + { + return self::get($route, ['_fields' => $field])[$field] ?? null; + } +} diff --git a/src/Infrastructure/Seo/JsonFieldProvider.php b/src/Infrastructure/Seo/JsonFieldProvider.php new file mode 100644 index 0000000..b15cb7d --- /dev/null +++ b/src/Infrastructure/Seo/JsonFieldProvider.php @@ -0,0 +1,54 @@ +): Seo $map + */ + public function __construct( + private string $name, + private string $field, + private Closure $map, + ) {} + + public function name(): string + { + return $this->name; + } + + public function isActive(): bool + { + return true; + } + + public function forPost(int $postId): ?Seo + { + $post = get_post($postId); + + return $post instanceof \WP_Post ? $this->read(rest_get_route_for_post($post)) : null; + } + + public function forTerm(int $termId, string $taxonomy): ?Seo + { + return $this->read(rest_get_route_for_term($termId)); + } + + private function read(string $route): ?Seo + { + $json = $route === '' ? null : InternalRest::field($route, $this->field); + + return is_array($json) ? ($this->map)($json) : null; + } +} diff --git a/src/Infrastructure/Seo/NoSeo.php b/src/Infrastructure/Seo/NoSeo.php new file mode 100644 index 0000000..7624c8b --- /dev/null +++ b/src/Infrastructure/Seo/NoSeo.php @@ -0,0 +1,34 @@ +read($permalink) : null; + } + + public function forTerm(int $termId, string $taxonomy): ?Seo + { + $link = get_term_link($termId, $taxonomy); + + return is_string($link) ? $this->read($link) : null; + } + + private function read(string $address): ?Seo + { + $head = InternalRest::get('/rankmath/v1/getHead', ['url' => home_url(UrlPath::of($address))])['head'] ?? null; + + return is_string($head) && $head !== '' ? SeoMapper::headHtml($head) : null; + } +} diff --git a/src/Infrastructure/Seo/SeoProviders.php b/src/Infrastructure/Seo/SeoProviders.php new file mode 100644 index 0000000..9672fc5 --- /dev/null +++ b/src/Infrastructure/Seo/SeoProviders.php @@ -0,0 +1,32 @@ + new JsonFieldProvider('yoast', 'yoast_head_json', SeoMapper::yoast(...)), + $rankMath => new RankMathProvider, + $aioseo => new JsonFieldProvider('aioseo', 'aioseo_head_json', SeoMapper::aioseo(...)), + $seopress => new SeopressProvider, + default => new NoSeo, + }; + } +} diff --git a/src/Infrastructure/Seo/SeopressProvider.php b/src/Infrastructure/Seo/SeopressProvider.php new file mode 100644 index 0000000..a32372b --- /dev/null +++ b/src/Infrastructure/Seo/SeopressProvider.php @@ -0,0 +1,42 @@ +read('/seopress/v1/posts/'.$postId); + } + + public function forTerm(int $termId, string $taxonomy): ?Seo + { + return $this->read('/seopress/v1/terms/'.$termId); + } + + private function read(string $route): ?Seo + { + $data = InternalRest::get($route)['data'] ?? null; + + return is_array($data) ? SeoMapper::seopress($data) : null; + } +} diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index b9c42e9..57ef007 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -20,8 +20,10 @@ use Pollora\Headless\Infrastructure\Language\NoLanguages; use Pollora\Headless\Infrastructure\Redirect\OldSlugRedirects; use Pollora\Headless\Infrastructure\Redirect\OptionRedirectStore; +use Pollora\Headless\Infrastructure\Redirect\RankMathRedirects; use Pollora\Headless\Infrastructure\Redirect\RedirectCatalog; use Pollora\Headless\Infrastructure\Revalidation\RevalidatorFactory; +use Pollora\Headless\Infrastructure\Seo\SeoProviders; /** * Starts the package: builds the modules the settings ask for and attaches them. @@ -106,7 +108,14 @@ public static function modules(Settings $settings, ?Languages $languages = null) $urls ??= $languages->isActive() ? new LanguageUrls($settings->urls, $settings->backend, $settings->front, $settings->languageFronts, $languages) : $settings->urls; - $modules[] = new RedirectRoutes(new RedirectCatalog([new OptionRedirectStore, ...($settings->oldSlugRedirects ? [new OldSlugRedirects($urls)] : [])])); + $modules[] = new RedirectRoutes(new RedirectCatalog([new OptionRedirectStore, ...(defined('RANK_MATH_VERSION') ? [new RankMathRedirects] : []), ...($settings->oldSlugRedirects ? [new OldSlugRedirects($urls)] : [])])); + } + + if ($settings->seo && $settings->urls instanceof UrlMapper && $settings->front instanceof Origin) { + $seoUrls = $languages->isActive() + ? new LanguageUrls($settings->urls, $settings->backend, $settings->front, $settings->languageFronts, $languages) + : $settings->urls; + $modules[] = new SeoField(SeoProviders::detect(), $seoUrls); } if ($settings->blocks) { diff --git a/src/Infrastructure/WordPress/PublicSurface.php b/src/Infrastructure/WordPress/PublicSurface.php index 43e4d9a..2708b21 100644 --- a/src/Infrastructure/WordPress/PublicSurface.php +++ b/src/Infrastructure/WordPress/PublicSurface.php @@ -35,7 +35,8 @@ public function register(HookRegistrar $hooks): void if ($this->noindexOrigin) { $hooks->addFilter('wp_headers', [$this, 'withNoindexHeader']); - $hooks->addFilter('robots_txt', [$this, 'robotsTxt']); + // Last: a SEO plugin adds its own lines (a sitemap, rules) to robots.txt, and an origin that is not to be indexed says only this + $hooks->addFilter('robots_txt', [$this, 'robotsTxt'], PHP_INT_MAX); $hooks->addFilter('wp_robots', [$this, 'robots']); } } diff --git a/src/Infrastructure/WordPress/SeoField.php b/src/Infrastructure/WordPress/SeoField.php new file mode 100644 index 0000000..aa08ba3 --- /dev/null +++ b/src/Infrastructure/WordPress/SeoField.php @@ -0,0 +1,68 @@ +addAction('rest_api_init', [$this, 'fields']); + } + + public function fields(): void + { + $schema = ['description' => 'Search and social metadata in one shape (ask for it in _fields).', 'type' => ['object', 'null'], 'context' => ['view', 'edit']]; + + foreach (get_post_types(['show_in_rest' => true, 'public' => true]) as $type) { + register_rest_field($type, self::FIELD, ['get_callback' => [$this, 'forPost'], 'schema' => $schema]); + } + + foreach (get_taxonomies(['show_in_rest' => true, 'public' => true]) as $taxonomy) { + register_rest_field($taxonomy, self::FIELD, ['get_callback' => [$this, 'forTerm'], 'schema' => $schema]); + } + } + + /** + * @param array $post + * @param \WP_REST_Request> $request + * @return array|null + */ + public function forPost(array $post, string $field, \WP_REST_Request $request): ?array + { + if (! OptInField::requested($request, self::FIELD)) { + return null; + } + + return $this->provider->forPost((int) ($post['id'] ?? 0))?->withUrls(fn (string $url): string => $this->urls->toFront($url))->toArray(); + } + + /** + * @param array $term + * @param \WP_REST_Request> $request + * @return array|null + */ + public function forTerm(array $term, string $field, \WP_REST_Request $request): ?array + { + if (! OptInField::requested($request, self::FIELD)) { + return null; + } + + return $this->provider->forTerm((int) ($term['id'] ?? 0), (string) ($term['taxonomy'] ?? ''))?->withUrls(fn (string $url): string => $this->urls->toFront($url))->toArray(); + } +} diff --git a/tests/Integration/SeoTest.php b/tests/Integration/SeoTest.php new file mode 100644 index 0000000..b78522b --- /dev/null +++ b/tests/Integration/SeoTest.php @@ -0,0 +1,77 @@ +register(new WordPressHooks); + + $GLOBALS['wp_rest_server'] = null; + rest_get_server(); +} + +afterEach(function (): void { + foreach (array_keys($GLOBALS['wp_filter']) as $hook) { + foreach ($GLOBALS['wp_filter'][$hook]->callbacks as $priority => $callbacks) { + foreach ($callbacks as $callback) { + $function = $callback['function']; + + if (is_array($function) && is_object($function[0]) && str_starts_with($function[0]::class, 'Pollora\\Headless\\')) { + remove_filter($hook, $function, $priority); + } + } + } + } +}); + +it('detects the SEO plugin the site runs', function (): void { + expect(SeoProviders::detect()->name())->toBe('yoast'); +}); + +it('gives the metadata of a post in the common shape, with its addresses on the front end', function (): void { + seoServer(); + $id = wp_insert_post(['post_title' => 'A page about SEO', 'post_content' => 'Some content about it.', 'post_status' => 'publish']); + + $request = new WP_REST_Request('GET', "/wp/v2/posts/$id"); + $request->set_param('_fields', 'id,headless_seo'); + $data = rest_do_request($request)->get_data(); + $without = rest_do_request(new WP_REST_Request('GET', "/wp/v2/posts/$id"))->get_data(); + wp_delete_post($id, true); + $seo = $data['headless_seo']; + + expect($seo['source'])->toBe('yoast') + ->and(array_keys($seo))->toBe(['source', 'title', 'description', 'robots', 'canonical', 'open_graph', 'twitter', 'json_ld', 'breadcrumbs']) + ->and($seo['title'])->toContain('A page about SEO') + ->and($seo['robots']['index'])->toBeTrue() + ->and($seo['canonical'])->toStartWith('https://www.example.com/') + ->and($seo['open_graph']['url'])->toStartWith('https://www.example.com/') + ->and($seo['open_graph']['title'])->not->toBeNull() + ->and($seo['json_ld'])->not->toBeEmpty() + ->and(json_encode($seo['json_ld']))->not->toContain(home_url()) + ->and($without['headless_seo'])->toBeNull(); +}); + +it('gives the metadata of a term', function (): void { + seoServer(); + $term = wp_insert_term('SEO Category', 'category'); + + $request = new WP_REST_Request('GET', '/wp/v2/categories/'.$term['term_id']); + $request->set_param('_fields', 'id,headless_seo'); + $seo = rest_do_request($request)->get_data()['headless_seo']; + wp_delete_term($term['term_id'], 'category'); + + expect($seo['source'])->toBe('yoast') + ->and($seo['title'])->toContain('SEO Category') + ->and($seo['canonical'])->toStartWith('https://www.example.com/'); +}); diff --git a/tests/Unit/Domain/SeoMapperTest.php b/tests/Unit/Domain/SeoMapperTest.php new file mode 100644 index 0000000..147c644 --- /dev/null +++ b/tests/Unit/Domain/SeoMapperTest.php @@ -0,0 +1,132 @@ + 'Hello - My site', + 'description' => 'A description', + 'robots' => ['index' => 'index', 'follow' => 'follow', 'max-snippet' => 'max-snippet:-1', 'max-image-preview' => 'max-image-preview:large'], + 'canonical' => 'https://cms.example.com/hello/', + 'og_locale' => 'en_US', 'og_type' => 'article', 'og_title' => 'Hello', 'og_description' => 'OG description', 'og_url' => 'https://cms.example.com/hello/', 'og_site_name' => 'My site', + 'og_image' => [['url' => 'https://cms.example.com/wp-content/uploads/a.jpg', 'width' => 1200, 'height' => 630, 'type' => 'image/jpeg']], + 'twitter_card' => 'summary_large_image', 'twitter_title' => 'Hello T', 'twitter_site' => '@site', 'twitter_misc' => ['Written by' => 'x'], + 'schema' => ['@graph' => [ + ['@type' => 'WebPage', '@id' => 'https://cms.example.com/hello/#webpage', 'url' => 'https://cms.example.com/hello/'], + ['@type' => 'BreadcrumbList', 'itemListElement' => [ + ['@type' => 'ListItem', 'position' => 1, 'name' => 'Home', 'item' => 'https://cms.example.com/'], + ['@type' => 'ListItem', 'position' => 2, 'name' => 'Hello'], + ]], + ]], + ]; +} + +it('reads the head JSON of Yoast SEO', function (): void { + $seo = SeoMapper::yoast(yoastJson())->toArray(); + + expect($seo['source'])->toBe('yoast') + ->and($seo['title'])->toBe('Hello - My site') + ->and($seo['robots'])->toBe(['index' => true, 'follow' => true, 'directives' => ['max-snippet:-1', 'max-image-preview:large']]) + ->and($seo['canonical'])->toBe('https://cms.example.com/hello/') + ->and($seo['open_graph'])->toMatchArray(['type' => 'article', 'title' => 'Hello', 'site_name' => 'My site', 'locale' => 'en_US']) + ->and($seo['open_graph']['images'])->toBe([['url' => 'https://cms.example.com/wp-content/uploads/a.jpg', 'width' => 1200, 'height' => 630, 'alt' => null]]) + ->and($seo['twitter'])->toMatchArray(['card' => 'summary_large_image', 'title' => 'Hello T', 'site' => '@site']) + ->and($seo['json_ld'])->toHaveCount(2) + ->and($seo['breadcrumbs'])->toBe([['label' => 'Home', 'url' => 'https://cms.example.com/'], ['label' => 'Hello', 'url' => null]]); +}); + +it('reads noindex and nofollow from Yoast', function (): void { + $seo = SeoMapper::yoast(['robots' => ['index' => 'noindex', 'follow' => 'nofollow']]); + + expect($seo->index)->toBeFalse()->and($seo->follow)->toBeFalse()->and($seo->directives)->toBe([]); +}); + +it('reads an empty answer as a page with nothing to say, and no field as null', function (): void { + $seo = SeoMapper::yoast([]); + + expect($seo->index)->toBeTrue()->and($seo->title)->toBeNull()->and($seo->canonical)->toBeNull() + ->and($seo->jsonLd)->toBe([])->and($seo->breadcrumbs)->toBe([])->and($seo->openGraph['images'])->toBe([]); +}); + +it('reads the head JSON of All in One SEO, whatever keys are there', function (): void { + $seo = SeoMapper::aioseo([ + 'title' => 'A', 'description' => 'D', 'canonical_url' => 'https://cms.example.com/a/', 'robots' => 'noindex, max-image-preview:large', + 'og_title' => 'OG', 'og_type' => 'article', 'og_image_url' => 'https://cms.example.com/i.jpg', 'og_image_width' => '800', 'twitter_card' => 'summary', 'twitter_image_url' => 'https://cms.example.com/t.jpg', + 'schema' => ['@graph' => [['@type' => 'WebPage']]], + ]); + + expect($seo->source)->toBe('aioseo') + ->and($seo->index)->toBeFalse()->and($seo->follow)->toBeTrue()->and($seo->directives)->toBe(['max-image-preview:large']) + ->and($seo->canonical)->toBe('https://cms.example.com/a/') + ->and($seo->openGraph['images'][0])->toBe(['url' => 'https://cms.example.com/i.jpg', 'width' => 800, 'height' => null, 'alt' => null]) + ->and($seo->twitter['image'])->toBe('https://cms.example.com/t.jpg') + ->and($seo->jsonLd)->toBe([['@type' => 'WebPage']]) + ->and(SeoMapper::aioseo(['robots' => ['noindex', 'nofollow']])->follow)->toBeFalse() + ->and(SeoMapper::aioseo([])->index)->toBeTrue(); +}); + +it('reads the answer of SEOPress', function (): void { + $seo = SeoMapper::seopress([ + 'title' => 'S', 'description' => 'D', 'canonical' => 'https://cms.example.com/s/', 'robots' => ['noindex' => 'yes', 'nofollow' => false], + 'og' => ['title' => 'OT', 'image' => 'https://cms.example.com/o.jpg', 'type' => 'website'], 'twitter' => ['card' => 'summary', 'image' => 'https://cms.example.com/t.jpg'], + 'breadcrumbs' => [['name' => 'Home', 'url' => 'https://cms.example.com/'], ['label' => 'S'], 'junk'], + ]); + + expect($seo->source)->toBe('seopress') + ->and($seo->index)->toBeFalse()->and($seo->follow)->toBeTrue() + ->and($seo->openGraph)->toMatchArray(['title' => 'OT', 'type' => 'website']) + ->and($seo->openGraph['images'][0]['url'])->toBe('https://cms.example.com/o.jpg') + ->and($seo->breadcrumbs)->toBe([['label' => 'Home', 'url' => 'https://cms.example.com/'], ['label' => 'S', 'url' => null]]); +}); + +it('reads the head Rank Math prints', function (): void { + $head = 'Rank & Hello' + .'' + .'' + .''; + $seo = SeoMapper::headHtml($head); + + expect($seo->source)->toBe('rankmath') + ->and($seo->title)->toBe('Rank & Hello') + ->and($seo->description)->toBe('Desc "quoted"') + ->and($seo->index)->toBeFalse()->and($seo->follow)->toBeTrue()->and($seo->directives)->toBe(['max-snippet:-1']) + ->and($seo->canonical)->toBe('https://cms.example.com/r/') + ->and($seo->openGraph['images'])->toBe([['url' => 'https://cms.example.com/a.jpg', 'width' => 640, 'height' => null, 'alt' => null]]) + ->and($seo->twitter['card'])->toBe('summary_large_image') + ->and($seo->jsonLd)->toBe([['@type' => 'WebPage', 'url' => 'https://cms.example.com/r/']]); +}); + +it('reads a head with nothing in it', function (): void { + $seo = SeoMapper::headHtml('

No head

'); + + expect($seo->title)->toBeNull()->and($seo->canonical)->toBeNull()->and($seo->jsonLd)->toBe([])->and($seo->index)->toBeTrue(); +}); + +it('moves every address to the front end: canonical, og, images, structured data, breadcrumbs', function (): void { + $map = static fn (string $url): string => str_replace('https://cms.example.com', 'https://www.example.com', $url); + $seo = SeoMapper::yoast(yoastJson())->withUrls($map)->toArray(); + + expect($seo['canonical'])->toBe('https://www.example.com/hello/') + ->and($seo['open_graph']['url'])->toBe('https://www.example.com/hello/') + ->and($seo['open_graph']['images'][0]['url'])->toBe('https://www.example.com/wp-content/uploads/a.jpg') + ->and($seo['json_ld'][0]['@id'])->toBe('https://www.example.com/hello/#webpage') + ->and($seo['json_ld'][1]['itemListElement'][0]['item'])->toBe('https://www.example.com/') + ->and($seo['breadcrumbs'][0]['url'])->toBe('https://www.example.com/') + ->and($seo['breadcrumbs'][1]['url'])->toBeNull() + ->and($seo['title'])->toBe('Hello - My site'); +}); + +it('has the same keys whichever plugin gave it', function (): void { + $keys = static fn (Seo $seo): array => array_keys($seo->toArray()); + + expect($keys(SeoMapper::yoast([])))->toBe($keys(SeoMapper::aioseo([])))->and($keys(SeoMapper::seopress([])))->toBe($keys(SeoMapper::headHtml('')))->and($keys(SeoMapper::yoast([])))->toBe(['source', 'title', 'description', 'robots', 'canonical', 'open_graph', 'twitter', 'json_ld', 'breadcrumbs']); +}); + +it('takes the title of Yoast\'s social card when it leaves the title out', function (): void { + expect(SeoMapper::yoast(['og_title' => 'Hello - My site'])->title)->toBe('Hello - My site') + ->and(SeoMapper::yoast(['title' => 'Real', 'og_title' => 'Other'])->title)->toBe('Real'); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 2e8e83e..8b1489a 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(14); + expect(Bootstrap::modules($settings))->toHaveCount(15); Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->times(6); + Actions\expectAdded('rest_api_init')->times(7); Filters\expectAdded('preview_post_link')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('rest_post_dispatch')->once(); diff --git a/tests/Unit/Infrastructure/SeoInfrastructureTest.php b/tests/Unit/Infrastructure/SeoInfrastructureTest.php new file mode 100644 index 0000000..28a2bae --- /dev/null +++ b/tests/Unit/Infrastructure/SeoInfrastructureTest.php @@ -0,0 +1,138 @@ +name())->toBe('yoast') + ->and(SeoProviders::from(false, true, true, true))->toBeInstanceOf(RankMathProvider::class) + ->and(SeoProviders::from(false, false, true, true)->name())->toBe('aioseo') + ->and(SeoProviders::from(false, false, false, true))->toBeInstanceOf(SeopressProvider::class) + ->and(SeoProviders::from(false, false, false, false))->toBeInstanceOf(NoSeo::class) + ->and(SeoProviders::from(true, false, false, false))->toBeInstanceOf(JsonFieldProvider::class); +}); + +it('has nothing to give without a SEO plugin', function (): void { + $none = new NoSeo; + + expect($none->name())->toBe('none')->and($none->isActive())->toBeFalse()->and($none->forPost(1))->toBeNull()->and($none->forTerm(1, 'category'))->toBeNull(); +}); + +function fakeSeoProvider(): SeoProvider +{ + return new class implements SeoProvider + { + public function name(): string + { + return 'fake'; + } + + public function isActive(): bool + { + return true; + } + + public function forPost(int $postId): ?Seo + { + return $postId === 12 ? new Seo('fake', 'Title', canonical: 'https://cms.example.com/hello/') : null; + } + + public function forTerm(int $termId, string $taxonomy): ?Seo + { + return $termId === 5 && $taxonomy === 'category' ? new Seo('fake', 'Category', canonical: 'https://cms.example.com/category/news/') : null; + } + }; +} + +function seoField(): SeoField +{ + return new SeoField(fakeSeoProvider(), new UrlMapper(Origin::fromUrl('https://cms.example.com'), Origin::fromUrl('https://www.example.com'))); +} + +function seoRequest(?string $fields): WP_REST_Request +{ + $request = Mockery::mock('WP_REST_Request'); + $request->shouldReceive('get_param')->with('_fields')->andReturn($fields); + + return $request; +} + +it('registers the field on public post types and taxonomies', function (): void { + Actions\expectAdded('rest_api_init')->once(); + $module = seoField(); + $module->register(new WordPressHooks); + + Functions\when('get_post_types')->justReturn(['post', 'page']); + Functions\when('get_taxonomies')->justReturn(['category']); + Functions\expect('register_rest_field')->times(3)->with(Mockery::anyOf('post', 'page', 'category'), 'headless_seo', Mockery::type('array')); + + $module->fields(); +}); + +it('gives the metadata of a post or a term on the front end, only when asked for it', function (): void { + $module = seoField(); + + expect($module->forPost(['id' => 12], 'headless_seo', seoRequest('id,headless_seo'))['canonical'])->toBe('https://www.example.com/hello/') + ->and($module->forPost(['id' => 12], 'headless_seo', seoRequest('id,title')))->toBeNull() + ->and($module->forPost(['id' => 99], 'headless_seo', seoRequest('headless_seo')))->toBeNull() + ->and($module->forTerm(['id' => 5, 'taxonomy' => 'category'], 'headless_seo', seoRequest('headless_seo'))['canonical'])->toBe('https://www.example.com/category/news/') + ->and($module->forTerm(['id' => 5, 'taxonomy' => 'category'], 'headless_seo', seoRequest(null)))->toBeNull(); +}); + +it('reads the SEO setting', function (): void { + expect(Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com')->seo)->toBeTrue() + ->and(Settings::fromArray(['frontend_url' => 'https://www.example.com', 'seo' => ['enabled' => false]], 'https://cms.example.com')->seo)->toBeFalse() + ->and(Settings::fromArray([], 'https://cms.example.com')->seo)->toBeFalse(); +}); + +function rankMathDatabase(bool $tableExists, array $rows): void +{ + $wpdb = Mockery::mock('wpdb'); + $wpdb->prefix = 'wp_'; + $wpdb->shouldReceive('esc_like')->andReturnArg(0); + $wpdb->shouldReceive('prepare')->andReturnUsing(static fn (string $sql, mixed ...$args): string => $sql); + $wpdb->shouldReceive('get_var')->andReturn($tableExists ? 'wp_rank_math_redirections' : null); + $wpdb->shouldReceive('get_results')->andReturn($rows); + $GLOBALS['wpdb'] = $wpdb; + Functions\when('maybe_unserialize')->alias(static fn (mixed $value): mixed => is_string($value) && str_starts_with($value, 'a:') ? unserialize($value) : $value); +} + +it('reads the exact and pattern redirections of Rank Math, with their status', function (): void { + rankMathDatabase(true, [ + (object) ['sources' => serialize([['pattern' => 'old-page', 'comparison' => 'exact'], ['pattern' => 'blog/(.*)', 'comparison' => 'regex'], ['pattern' => 'shop', 'comparison' => 'contains'], ['pattern' => '', 'comparison' => 'exact']]), 'url_to' => '/new-page/', 'header_code' => '301'], + (object) ['sources' => serialize([['pattern' => '/bad', 'comparison' => 'exact']]), 'url_to' => 'not a destination', 'header_code' => '301'], + (object) ['sources' => 'broken', 'url_to' => '/x/', 'header_code' => '301'], + (object) ['sources' => serialize([['pattern' => '/gone/', 'comparison' => 'exact']]), 'url_to' => '', 'header_code' => '410'], + ]); + + $rules = (new RankMathRedirects)->redirects(); + + expect(array_map(static fn ($rule): string => $rule->from.($rule->regex ? ' (regex)' : '').' → '.$rule->to.' '.$rule->status.' '.$rule->source, $rules))->toBe([ + '/old-page → /new-page/ 301 rankmath', + '/blog/(.*) (regex) → /new-page/ 301 rankmath', + '/gone/ → 410 rankmath', + ]); + unset($GLOBALS['wpdb']); +}); + +it('reads no redirection from a Rank Math whose table is not there', function (): void { + rankMathDatabase(false, []); + + expect((new RankMathRedirects)->redirects())->toBe([]); + unset($GLOBALS['wpdb']); +});