diff --git a/CHANGELOG.md b/CHANGELOG.md index 9334d40..9f3c4ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,4 +22,5 @@ All notable changes are listed here. The format follows [Keep a Changelog](https - 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). +- Redirects: rules managed with `wp headless redirect`, the old slugs of renamed posts, `GET /wp-json/headless/v1/redirects` and `/redirects/resolve`. - mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer. diff --git a/README.md b/README.md index c6aeea1..302c91a 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo | 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. | +| 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). | | 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. @@ -151,6 +152,26 @@ site.post_types; // [{ name: 'post', rest_base: 'posts', rest_namespace: 'wp/v2 `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). +## Redirects + +```bash +wp headless redirect add /old-page/ /new-page/ # 301 by default +wp headless redirect add '/blog/(\d{4})/(.*)' '/news/$1/$2' --regex # a pattern, matched against the whole path +wp headless redirect add /discontinued/ --status=410 # a page that is gone +wp headless redirect list # every rule, from every source +wp headless redirect test /blog/2024/hello +``` + +```js +// at build or start time: every rule, to feed your framework's redirects +const { redirects } = await (await fetch('https://cms.example.com/wp-json/headless/v1/redirects')).json(); +// or, in a middleware, one path (a 200 either way, so a CDN can keep the answer) +const { redirect } = await (await fetch(`https://cms.example.com/wp-json/headless/v1/redirects/resolve?path=${encodeURIComponent(pathname)}`)).json(); +// redirect: null | { from, to, status, source: 'manual' | 'old-slug' } +``` + +An exact rule wins over a pattern, and the rules you write win over the old slugs. A rule is checked when it is made (a path, a destination that is a path or an absolute http(s) URL, a status of 301, 302, 307, 308 or 410, a pattern that compiles, no loop). Changing the rules is announced to the front end with the `option:headless_redirects` tag. + ## 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 f0dd719..8fda248 100644 --- a/config/headless.php +++ b/config/headless.php @@ -121,4 +121,12 @@ 'manifest' => [ 'enabled' => true, ], + + // Redirects for the front end: GET /wp-json/headless/v1/redirects (every rule) and /redirects/resolve?path=/old/ (one path). + // Manage yours with `wp headless redirect add|remove|list|test`. `old_slugs` adds the earlier addresses WordPress remembers + // for renamed posts, each to the current address. Only active once a front-end URL is set. + 'redirects' => [ + 'enabled' => true, + 'old_slugs' => true, + ], ]; diff --git a/src/Domain/Exceptions/InvalidRedirectException.php b/src/Domain/Exceptions/InvalidRedirectException.php new file mode 100644 index 0000000..b5dae04 --- /dev/null +++ b/src/Domain/Exceptions/InvalidRedirectException.php @@ -0,0 +1,38 @@ + self::MAX_LENGTH) { + throw InvalidRedirectException::badSource($from); + } + + if (! in_array($status, self::STATUSES, true)) { + throw InvalidRedirectException::badStatus($status); + } + + if ($status !== 410 && ! self::isDestination($to)) { + throw InvalidRedirectException::badTarget($to); + } + + if ($regex && ! self::compiles(self::pattern($from))) { + throw InvalidRedirectException::badPattern($from); + } + + if (! $regex && $to === $from) { + throw InvalidRedirectException::loop($from); + } + } + + /** + * The destination for a path this rule matches, or null when it does not match. + */ + public function resolve(string $path): ?string + { + if (! $this->regex) { + return self::normalise($path) === self::normalise($this->from) ? $this->to : null; + } + + if (preg_match(self::pattern($this->from), $path, $matches) !== 1) { + return null; + } + + return (string) preg_replace_callback('/\$(\d{1,2})/', static fn (array $reference): string => $matches[(int) $reference[1]] ?? '', $this->to); + } + + /** + * @return array{from: string, to: string, status: int, regex: bool, source: string} + */ + public function toArray(): array + { + return ['from' => $this->from, 'to' => $this->to, 'status' => $this->status, 'regex' => $this->regex, 'source' => $this->source]; + } + + /** + * @param array $data + */ + public static function tryFromArray(array $data): ?self + { + if (! is_string($data['from'] ?? null) || ! is_string($data['to'] ?? null)) { + return null; + } + + try { + return new self($data['from'], $data['to'], is_int($data['status'] ?? null) ? $data['status'] : 301, ($data['regex'] ?? false) === true, is_string($data['source'] ?? null) ? $data['source'] : 'manual'); + } catch (InvalidRedirectException) { + return null; + } + } + + /** A pattern is anchored at both ends: `/blog/(.*)` matches whole paths, never a part of one. */ + private static function pattern(string $from): string + { + return '#\A'.str_replace('#', '\#', $from).'\z#Du'; + } + + /** Whether a pattern is valid. PHP warns about one that is not: the warning is the answer, not noise. */ + private static function compiles(string $pattern): bool + { + set_error_handler(static fn (): bool => true); + + try { + return preg_match($pattern, '') !== false; + } finally { + restore_error_handler(); + } + } + + /** A path without its trailing slash: `/about` and `/about/` are the same page. */ + private static function normalise(string $path): string + { + return $path === '/' ? '/' : rtrim($path, '/'); + } + + private static function isDestination(string $to): bool + { + if (str_starts_with($to, '/') && ! str_starts_with($to, '//')) { + return preg_match('/\s/', $to) !== 1; + } + + return preg_match('#\Ahttps?://[^\s/]+\S*\z#i', $to) === 1; + } +} diff --git a/src/Domain/Redirect/RedirectRules.php b/src/Domain/Redirect/RedirectRules.php new file mode 100644 index 0000000..a967cf0 --- /dev/null +++ b/src/Domain/Redirect/RedirectRules.php @@ -0,0 +1,58 @@ + */ + private array $exact; + + /** @var list */ + private array $patterns; + + /** + * @param list $rules + */ + public function __construct(private array $rules) + { + $this->exact = array_values(array_filter($rules, static fn (Redirect $rule): bool => ! $rule->regex)); + $this->patterns = array_values(array_filter($rules, static fn (Redirect $rule): bool => $rule->regex)); + } + + /** + * @return list + */ + public function all(): array + { + return $this->rules; + } + + /** + * The rule that applies to a path, with the destination it gives, or null. + * + * @return array{rule: Redirect, to: string}|null + */ + public function match(string $path): ?array + { + $path = '/'.ltrim(explode('?', $path, 2)[0], '/'); + + foreach ([...$this->exact, ...$this->patterns] as $rule) { + $to = $rule->resolve($path); + + // A pattern that sends a path to itself would loop the visitor + if ($to !== null && $to !== $path) { + return ['rule' => $rule, 'to' => $to]; + } + } + + return null; + } +} diff --git a/src/Domain/Redirect/RedirectSource.php b/src/Domain/Redirect/RedirectSource.php new file mode 100644 index 0000000..1255df3 --- /dev/null +++ b/src/Domain/Redirect/RedirectSource.php @@ -0,0 +1,16 @@ + + */ + public function redirects(): array; +} diff --git a/src/Domain/Redirect/RedirectStore.php b/src/Domain/Redirect/RedirectStore.php new file mode 100644 index 0000000..cfd2a63 --- /dev/null +++ b/src/Domain/Redirect/RedirectStore.php @@ -0,0 +1,17 @@ + is_array($row) ? Redirect::tryFromArray($row) : null, $cached))); + } + + $rules = $this->read(); + set_transient(self::TRANSIENT, array_map(static fn (Redirect $rule): array => $rule->toArray(), $rules), 300); + + return $rules; + } + + public static function forget(): void + { + delete_transient(self::TRANSIENT); + } + + /** + * @return list + */ + private function read(): array + { + global $wpdb; + + $rows = $wpdb->get_results($wpdb->prepare( + "SELECT m.post_id, m.meta_value AS old_slug FROM {$wpdb->postmeta} m INNER JOIN {$wpdb->posts} p ON p.ID = m.post_id WHERE m.meta_key = %s AND p.post_status = %s AND p.post_type NOT IN ('revision', 'attachment', 'nav_menu_item') ORDER BY m.meta_id ASC LIMIT %d", + '_wp_old_slug', + 'publish', + self::LIMIT, + )); + + $rules = []; + + foreach (is_array($rows) ? $rows : [] as $row) { + $post = get_post((int) $row->post_id); + + if (! $post instanceof \WP_Post || $row->old_slug === '' || $row->old_slug === $post->post_name) { + continue; + } + + $old = clone $post; + $old->post_name = (string) $row->old_slug; + + try { + $rules[] = new Redirect( + UrlPath::of($this->urls->toFront((string) get_permalink($old))), + UrlPath::of($this->urls->toFront((string) get_permalink($post))), + 301, + false, + 'old-slug', + ); + } catch (\InvalidArgumentException) { + // A post whose address cannot be a rule (plain permalinks give "/?p=12" for both): nothing to redirect + continue; + } + } + + return $rules; + } +} diff --git a/src/Infrastructure/Redirect/OptionRedirectStore.php b/src/Infrastructure/Redirect/OptionRedirectStore.php new file mode 100644 index 0000000..3d77a70 --- /dev/null +++ b/src/Infrastructure/Redirect/OptionRedirectStore.php @@ -0,0 +1,73 @@ +read() as $stored) { + $rule = is_array($stored) ? Redirect::tryFromArray($stored) : null; + + if ($rule instanceof Redirect) { + $rules[] = $rule; + } + } + + return $rules; + } + + public function save(Redirect $redirect): void + { + $all = $this->read(); + $all[self::key($redirect->from)] = $redirect->toArray(); + + update_option(self::OPTION, array_slice($all, -self::LIMIT, null, true), false); + } + + public function remove(string $from): bool + { + $all = $this->read(); + $key = self::key($from); + + if (! isset($all[$key])) { + return false; + } + + unset($all[$key]); + update_option(self::OPTION, $all, false); + + return true; + } + + /** + * @return array + */ + private function read(): array + { + $all = get_option(self::OPTION, []); + + return is_array($all) ? $all : []; + } + + /** `/about` and `/about/` are the same rule. */ + private static function key(string $from): string + { + return $from === '/' ? '/' : rtrim($from, '/'); + } +} diff --git a/src/Infrastructure/Redirect/RedirectCatalog.php b/src/Infrastructure/Redirect/RedirectCatalog.php new file mode 100644 index 0000000..3211e94 --- /dev/null +++ b/src/Infrastructure/Redirect/RedirectCatalog.php @@ -0,0 +1,30 @@ + $sources + */ + public function __construct(private array $sources) {} + + public function rules(): RedirectRules + { + $rules = []; + + foreach ($this->sources as $source) { + array_push($rules, ...$source->redirects()); + } + + return new RedirectRules($rules); + } +} diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index 7b60ca2..d49df74 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -17,6 +17,9 @@ use Pollora\Headless\Infrastructure\Config\SettingsLoader; use Pollora\Headless\Infrastructure\Language\LanguagesFactory; use Pollora\Headless\Infrastructure\Language\NoLanguages; +use Pollora\Headless\Infrastructure\Redirect\OldSlugRedirects; +use Pollora\Headless\Infrastructure\Redirect\OptionRedirectStore; +use Pollora\Headless\Infrastructure\Redirect\RedirectCatalog; use Pollora\Headless\Infrastructure\Revalidation\RevalidatorFactory; /** @@ -98,6 +101,13 @@ public static function modules(Settings $settings, ?Languages $languages = null) $modules[] = new ManifestRoutes(new SiteManifest($urls, $settings->front, $languages)); } + if ($settings->redirects && $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 RedirectRoutes(new RedirectCatalog([new OptionRedirectStore, ...($settings->oldSlugRedirects ? [new OldSlugRedirects($urls)] : [])])); + } + if ($settings->restCache instanceof RestCachePolicy || $settings->perPageMax !== null) { $modules[] = new RestPerformance($settings->restCache, $settings->perPageMax); } diff --git a/src/Infrastructure/WordPress/ChangeWatcher.php b/src/Infrastructure/WordPress/ChangeWatcher.php index 622d7ce..8690692 100644 --- a/src/Infrastructure/WordPress/ChangeWatcher.php +++ b/src/Infrastructure/WordPress/ChangeWatcher.php @@ -38,7 +38,7 @@ public function __construct( /** @return list */ public static function defaultOptions(): array { - return ['blogname', 'blogdescription', 'home', 'siteurl', 'page_on_front', 'page_for_posts', 'show_on_front', 'permalink_structure', 'category_base', 'tag_base', 'posts_per_page', 'date_format', 'time_format', 'timezone_string', 'gmt_offset', 'WPLANG', 'site_icon', 'sidebars_widgets']; + return ['blogname', 'blogdescription', 'home', 'siteurl', 'page_on_front', 'page_for_posts', 'show_on_front', 'permalink_structure', 'category_base', 'tag_base', 'posts_per_page', 'date_format', 'time_format', 'timezone_string', 'gmt_offset', 'WPLANG', 'site_icon', 'sidebars_widgets', 'headless_redirects']; } public function register(HookRegistrar $hooks): void diff --git a/src/Infrastructure/WordPress/RedirectRoutes.php b/src/Infrastructure/WordPress/RedirectRoutes.php new file mode 100644 index 0000000..34acc57 --- /dev/null +++ b/src/Infrastructure/WordPress/RedirectRoutes.php @@ -0,0 +1,71 @@ +addAction('rest_api_init', [$this, 'routes']); + // The list of old slugs follows the posts + $hooks->addAction('post_updated', [OldSlugRedirects::class, 'forget']); + $hooks->addAction('deleted_post', [OldSlugRedirects::class, 'forget']); + } + + public function routes(): void + { + register_rest_route(self::NAMESPACE, '/redirects', [ + 'methods' => 'GET', + 'callback' => [$this, 'all'], + // Public on purpose: a redirect is an address a visitor already knows, and the front end reads the list to serve it. + 'permission_callback' => '__return_true', + ]); + + register_rest_route(self::NAMESPACE, '/redirects/resolve', [ + 'methods' => 'GET', + 'callback' => [$this, 'resolve'], + 'permission_callback' => '__return_true', + 'args' => ['path' => ['type' => 'string', 'required' => true, 'pattern' => '\A/\S{0,1999}\z']], + ]); + } + + public function all(): \WP_REST_Response + { + $rules = $this->catalog->rules()->all(); + + return rest_ensure_response([ + 'count' => count($rules), + 'redirects' => array_map(static fn (Redirect $rule): array => $rule->toArray(), array_slice($rules, 0, OptionRedirectStore::LIMIT)), + 'truncated' => count($rules) > OptionRedirectStore::LIMIT, + ]); + } + + /** + * @param \WP_REST_Request> $request + */ + public function resolve(\WP_REST_Request $request): \WP_REST_Response + { + $match = $this->catalog->rules()->match((string) $request->get_param('path')); + + return rest_ensure_response([ + 'redirect' => $match === null ? null : ['from' => $match['rule']->from, 'to' => $match['to'], 'status' => $match['rule']->status, 'source' => $match['rule']->source], + ]); + } +} diff --git a/src/Infrastructure/WpCli/RedirectCommand.php b/src/Infrastructure/WpCli/RedirectCommand.php new file mode 100644 index 0000000..1731b6b --- /dev/null +++ b/src/Infrastructure/WpCli/RedirectCommand.php @@ -0,0 +1,134 @@ + + * : The path to redirect, such as /old-page/ (or a pattern with --regex). + * + * [] + * : A path (/new-page/) or an absolute URL. Not needed with --status=410. + * + * [--status=] + * : 301 (default), 302, 307, 308, or 410 for a page that is gone. + * + * [--regex] + * : is a pattern matched against the whole path; $1, $2… in are its groups. + * + * ## EXAMPLES + * + * wp headless redirect add /old-page/ /new-page/ + * wp headless redirect add '/blog/(\d{4})/(.*)' '/news/$1/$2' --regex + * wp headless redirect add /discontinued/ --status=410 + * + * @param list $args + * @param array $assoc + */ + public function add(array $args = [], array $assoc = []): void + { + try { + $redirect = new Redirect($args[0] ?? '', $args[1] ?? '', (int) ($assoc['status'] ?? 301), ($assoc['regex'] ?? false) === true); + } catch (InvalidRedirectException $invalidRedirectException) { + $this->output->error($invalidRedirectException->getMessage()); + + return; + } + + $this->store->save($redirect); + $this->output->success(sprintf('%s → %s (%d).', $redirect->from, $redirect->status === 410 ? 'gone' : $redirect->to, $redirect->status)); + } + + /** + * Remove the redirect of a path. + * + * ## OPTIONS + * + * + * : The path, as it was added. + * + * @param list $args + * @param array $assoc + */ + public function remove(array $args = [], array $assoc = []): void + { + $from = $args[0] ?? ''; + + if (! $this->store->remove($from)) { + $this->output->error(sprintf('No redirect for "%s" among the ones you manage.', $from)); + + return; + } + + $this->output->success('Redirect removed.'); + } + + /** + * List every redirect of the site, from every source (the ones you added, the old slugs of renamed posts). + * + * @param list $args + * @param array $assoc + */ + public function list_(array $args = [], array $assoc = []): void + { + $rules = ($this->catalog)()->rules()->all(); + + foreach ($rules as $rule) { + $this->output->line(sprintf('%-9s %s %s → %s (%d)', $rule->source, $rule->regex ? '~' : ' ', $rule->from, $rule->status === 410 ? 'gone' : $rule->to, $rule->status)); + } + + if ($rules === []) { + $this->output->line('No redirect.'); + } + } + + /** + * Say where a path goes. + * + * ## OPTIONS + * + * + * : The path to try, such as /old-page/. + * + * @param list $args + * @param array $assoc + */ + public function test(array $args = [], array $assoc = []): void + { + $path = $args[0] ?? '/'; + $match = ($this->catalog)()->rules()->match($path); + + if ($match === null) { + $this->output->line(sprintf('%s is not redirected.', $path)); + + return; + } + + $this->output->success(sprintf('%s → %s (%d, from the %s rule %s).', $path, $match['rule']->status === 410 ? 'gone' : $match['to'], $match['rule']->status, $match['rule']->source, $match['rule']->from)); + } +} diff --git a/src/Infrastructure/WpCli/register.php b/src/Infrastructure/WpCli/register.php index 8360ea8..7a95e92 100644 --- a/src/Infrastructure/WpCli/register.php +++ b/src/Infrastructure/WpCli/register.php @@ -4,9 +4,13 @@ use Pollora\Headless\Application\Revalidation\Revalidator; use Pollora\Headless\Application\Token\TokenService; +use Pollora\Headless\Domain\Front\UrlMapper; use Pollora\Headless\Infrastructure\Config\Settings; use Pollora\Headless\Infrastructure\Config\SettingsLoader; use Pollora\Headless\Infrastructure\Language\LanguagesFactory; +use Pollora\Headless\Infrastructure\Redirect\OldSlugRedirects; +use Pollora\Headless\Infrastructure\Redirect\OptionRedirectStore; +use Pollora\Headless\Infrastructure\Redirect\RedirectCatalog; use Pollora\Headless\Infrastructure\Revalidation\ActionSchedulerScheduler; use Pollora\Headless\Infrastructure\Revalidation\RevalidatorFactory; use Pollora\Headless\Infrastructure\Status\StatusReport; @@ -14,6 +18,7 @@ use Pollora\Headless\Infrastructure\WordPress\StubTheme; use Pollora\Headless\Infrastructure\WordPress\UserMetaTokenStore; use Pollora\Headless\Infrastructure\WpCli\HeadlessCommand; +use Pollora\Headless\Infrastructure\WpCli\RedirectCommand; use Pollora\Headless\Infrastructure\WpCli\RevalidateCommand; use Pollora\Headless\Infrastructure\WpCli\TokenCommand; use Pollora\Headless\Infrastructure\WpCli\WpCliOutput; @@ -47,6 +52,17 @@ static function (string $slug): void { new WpCliOutput, )); + WP_CLI::add_command('headless redirect', new RedirectCommand( + new OptionRedirectStore, + static function () use ($settings): RedirectCatalog { + $config = $settings(); + $urls = $config->urls ?? new UrlMapper($config->backend, $config->backend); + + return new RedirectCatalog([new OptionRedirectStore, new OldSlugRedirects($urls)]); + }, + new WpCliOutput, + )); + WP_CLI::add_command('headless token', new TokenCommand( new TokenService(new UserMetaTokenStore), static function (string $who): ?int { diff --git a/tests/Integration/RedirectsTest.php b/tests/Integration/RedirectsTest.php new file mode 100644 index 0000000..65b8f40 --- /dev/null +++ b/tests/Integration/RedirectsTest.php @@ -0,0 +1,140 @@ +register(new WordPressHooks); + + $GLOBALS['wp_rest_server'] = null; + rest_get_server(); +} + +beforeEach(function (): void { + delete_option(OptionRedirectStore::OPTION); + OldSlugRedirects::forget(); + update_option('permalink_structure', '/%postname%/'); + $GLOBALS['wp_rewrite']->set_permalink_structure('/%postname%/'); +}); + +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); + } + } + } + } + + delete_option(OptionRedirectStore::OPTION); + OldSlugRedirects::forget(); + update_option('permalink_structure', ''); + $GLOBALS['wp_rewrite']->set_permalink_structure(''); +}); + +it('lists the rules an editor manages, to a visitor', function (): void { + $store = new OptionRedirectStore; + $store->save(new Redirect('/old-page/', '/new-page/')); + $store->save(new Redirect('/blog/(.*)', '/news/$1', 308, true)); + redirectsServer(); + wp_set_current_user(0); + + $response = rest_do_request(new WP_REST_Request('GET', '/headless/v1/redirects')); + $data = $response->get_data(); + + expect($response->get_status())->toBe(200) + ->and($data['count'])->toBe(2) + ->and($data['truncated'])->toBeFalse() + ->and(array_column($data['redirects'], 'from'))->toBe(['/old-page/', '/blog/(.*)']) + ->and($data['redirects'][1])->toMatchArray(['to' => '/news/$1', 'status' => 308, 'regex' => true, 'source' => 'manual']); +}); + +it('resolves a path, and answers 200 with null for one that goes nowhere', function (): void { + (new OptionRedirectStore)->save(new Redirect('/blog/(.*)', '/news/$1', 308, true)); + redirectsServer(); + + $ask = static function (string $path): WP_REST_Response { + $request = new WP_REST_Request('GET', '/headless/v1/redirects/resolve'); + $request->set_param('path', $path); + + return rest_do_request($request); + }; + + expect($ask('/blog/hello')->get_data()['redirect'])->toBe(['from' => '/blog/(.*)', 'to' => '/news/hello', 'status' => 308, 'source' => 'manual']) + ->and($ask('/elsewhere')->get_status())->toBe(200) + ->and($ask('/elsewhere')->get_data())->toBe(['redirect' => null]) + ->and($ask('no-leading-slash')->get_status())->toBe(400) + ->and($ask('/has space')->get_status())->toBe(400); +}); + +it('lists the old addresses WordPress remembers for a renamed post, each to the current one', function (): void { + $id = wp_insert_post(['post_title' => 'First Title', 'post_status' => 'publish']); + wp_update_post(['ID' => $id, 'post_name' => 'second-title']); + wp_update_post(['ID' => $id, 'post_name' => 'third-title']); + redirectsServer(); + + $data = rest_do_request(new WP_REST_Request('GET', '/headless/v1/redirects'))->get_data(); + wp_delete_post($id, true); + $old = array_values(array_filter($data['redirects'], static fn (array $rule): bool => $rule['source'] === 'old-slug')); + + expect(array_column($old, 'from'))->toContain('/first-title/', '/second-title/') + ->and(array_unique(array_column($old, 'to')))->toBe(['/third-title/']) + ->and($old[0]['status'])->toBe(301); +}); + +it('does not list the old address of a post that is not published', function (): void { + $id = wp_insert_post(['post_title' => 'Draft Title', 'post_status' => 'publish']); + wp_update_post(['ID' => $id, 'post_name' => 'renamed-draft']); + wp_update_post(['ID' => $id, 'post_status' => 'draft']); + OldSlugRedirects::forget(); + redirectsServer(); + + $data = rest_do_request(new WP_REST_Request('GET', '/headless/v1/redirects'))->get_data(); + wp_delete_post($id, true); + + expect(array_column($data['redirects'], 'source'))->not->toContain('old-slug'); +}); + +it('puts what an editor wrote before what WordPress remembers', function (): void { + $id = wp_insert_post(['post_title' => 'Before', 'post_status' => 'publish']); + wp_update_post(['ID' => $id, 'post_name' => 'after']); + (new OptionRedirectStore)->save(new Redirect('/before/', '/somewhere-else/')); + redirectsServer(); + + $request = new WP_REST_Request('GET', '/headless/v1/redirects/resolve'); + $request->set_param('path', '/before/'); + $data = rest_do_request($request)->get_data(); + wp_delete_post($id, true); + + expect($data['redirect']['to'])->toBe('/somewhere-else/')->and($data['redirect']['source'])->toBe('manual'); +}); + +it('forgets the list of old slugs when a post is saved', function (): void { + $id = wp_insert_post(['post_title' => 'Cached', 'post_status' => 'publish']); + redirectsServer(); + rest_do_request(new WP_REST_Request('GET', '/headless/v1/redirects')); + $cached = get_transient(OldSlugRedirects::TRANSIENT); + + wp_update_post(['ID' => $id, 'post_title' => 'Cached again']); + $afterSave = get_transient(OldSlugRedirects::TRANSIENT); + wp_delete_post($id, true); + + expect($cached)->toBeArray()->and($afterSave)->toBeFalse(); +}); diff --git a/tests/Unit/Domain/RedirectTest.php b/tests/Unit/Domain/RedirectTest.php new file mode 100644 index 0000000..f56a3f2 --- /dev/null +++ b/tests/Unit/Domain/RedirectTest.php @@ -0,0 +1,92 @@ +resolve($path))->toBe('/new-page/'); +})->with(['/old-page/', '/old-page']); + +it('does not match another path', function (): void { + expect((new Redirect('/old', '/new'))->resolve('/old/child'))->toBeNull() + ->and((new Redirect('/old', '/new'))->resolve('/older'))->toBeNull(); +}); + +it('matches a pattern against the whole path and fills the groups of the destination', function (): void { + $rule = new Redirect('/blog/(\d{4})/(.*)', '/news/$1/$2', 301, true); + + expect($rule->resolve('/blog/2024/hello-world'))->toBe('/news/2024/hello-world') + ->and($rule->resolve('/blog/24/hello'))->toBeNull() + ->and($rule->resolve('/x/blog/2024/hello'))->toBeNull() + ->and($rule->resolve('/blog/2024/hello'."\n"))->toBeNull(); +}); + +it('leaves a group the pattern did not capture empty', function (): void { + expect((new Redirect('/a/(b)?', '/c/$1/$2', 302, true))->resolve('/a/'))->toBe('/c//'); +}); + +it('takes a destination that is a path or an absolute URL, and no destination for a 410', function (): void { + expect((new Redirect('/a', '/b'))->to)->toBe('/b') + ->and((new Redirect('/a', 'https://www.example.org/b?x=1'))->to)->toBe('https://www.example.org/b?x=1') + ->and((new Redirect('/gone', '', 410))->status)->toBe(410); +}); + +it('refuses what cannot be a rule', function (callable $make, string $message): void { + expect($make)->toThrow(InvalidRedirectException::class, $message); +})->with([ + 'no leading slash' => [fn () => new Redirect('old', '/new'), 'is not a path to redirect'], + 'a space in the source' => [fn () => new Redirect('/old page', '/new'), 'is not a path to redirect'], + 'a source that is too long' => [fn () => new Redirect('/'.str_repeat('a', 2000), '/new'), 'is not a path to redirect'], + 'a relative destination' => [fn () => new Redirect('/a', 'new'), 'is not a destination'], + 'a protocol-relative destination' => [fn () => new Redirect('/a', '//evil.example.org'), 'is not a destination'], + 'a javascript destination' => [fn () => new Redirect('/a', 'javascript:alert(1)'), 'is not a destination'], + 'a destination with a space' => [fn () => new Redirect('/a', '/b c'), 'is not a destination'], + 'an empty destination' => [fn () => new Redirect('/a', ''), 'is not a destination'], + 'a status that is not a redirect' => [fn () => new Redirect('/a', '/b', 200), 'is not a redirect status'], + 'a pattern that does not compile' => [fn () => new Redirect('/a/(', '/b', 301, true), 'is not a valid pattern'], + 'a rule that loops' => [fn () => new Redirect('/a', '/a'), 'redirects to itself'], +]); + +it('goes to an array and back, and does not read a rule that is not valid', function (): void { + $rule = new Redirect('/a/(.*)', '/b/$1', 308, true, 'seo'); + + expect(Redirect::tryFromArray($rule->toArray()))->toEqual($rule) + ->and(Redirect::tryFromArray(['from' => 'bad', 'to' => '/x']))->toBeNull() + ->and(Redirect::tryFromArray(['from' => '/a']))->toBeNull() + ->and(Redirect::tryFromArray([]))->toBeNull() + ->and(Redirect::tryFromArray(['from' => '/a', 'to' => '/b'])?->status)->toBe(301); +}); + +it('prefers an exact rule to a pattern, and the first of equals', function (): void { + $rules = new RedirectRules([ + new Redirect('/blog/(.*)', '/news/$1', 301, true), + new Redirect('/blog/special', '/special', 302), + new Redirect('/dup', '/first'), + new Redirect('/dup', '/second'), + ]); + + expect($rules->match('/blog/special')['to'])->toBe('/special') + ->and($rules->match('/blog/other')['to'])->toBe('/news/other') + ->and($rules->match('/dup')['to'])->toBe('/first') + ->and($rules->match('/dup?utm=1')['to'])->toBe('/first') + ->and($rules->match('/nothing'))->toBeNull() + ->and($rules->all())->toHaveCount(4); +}); + +it('tells the rule that matched', function (): void { + $match = (new RedirectRules([new Redirect('/a', '/b', 308, false, 'manual')]))->match('/a'); + + expect($match['rule']->status)->toBe(308)->and($match['rule']->source)->toBe('manual'); +}); + +it('does not send a path to itself with a pattern', function (): void { + $rules = new RedirectRules([new Redirect('/loop/(.*)', '/loop/$1', 301, true), new Redirect('/loop/x', '/y')]); + + expect($rules->match('/loop/x')['to'])->toBe('/y') + ->and($rules->match('/loop/z'))->toBeNull(); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 49c08b0..2fb7af6 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(11); + expect(Bootstrap::modules($settings))->toHaveCount(12); Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->times(3); + Actions\expectAdded('rest_api_init')->times(4); Filters\expectAdded('preview_post_link')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('rest_post_dispatch')->once(); diff --git a/tests/Unit/Infrastructure/RedirectInfrastructureTest.php b/tests/Unit/Infrastructure/RedirectInfrastructureTest.php new file mode 100644 index 0000000..e4943f3 --- /dev/null +++ b/tests/Unit/Infrastructure/RedirectInfrastructureTest.php @@ -0,0 +1,309 @@ +alias(static fn (string $name, mixed $default = false): mixed => $options[$name] ?? $default); + Functions\when('update_option')->alias(function (string $name, mixed $value) use ($options): bool { + $options[$name] = $value; + + return true; + }); + + return $options; +} + +it('keeps the rules of an editor in one option that is not autoloaded, one per source path', function (): void { + $options = redirectOptions(); + Functions\expect('update_option')->never(); + redirectOptions(); + + $store = new OptionRedirectStore; + $store->save(new Redirect('/old/', '/new/')); + $store->save(new Redirect('/old', '/newer/', 302)); + $store->save(new Redirect('/gone/', '', 410)); + + $stored = $store->redirects(); + + expect($stored)->toHaveCount(2) + ->and(array_map(static fn (Redirect $rule): string => $rule->from.'→'.$rule->to, $stored))->toBe(['/old→/newer/', '/gone/→']); +}); + +it('asks for the option not to be autoloaded', function (): void { + Functions\when('get_option')->justReturn([]); + Functions\expect('update_option')->once()->with('headless_redirects', Mockery::type('array'), false); + + (new OptionRedirectStore)->save(new Redirect('/a', '/b')); +}); + +it('removes a rule, with or without its trailing slash, and says when there was none', function (): void { + redirectOptions(); + $store = new OptionRedirectStore; + $store->save(new Redirect('/old/', '/new/')); + + expect($store->remove('/old'))->toBeTrue() + ->and($store->remove('/old/'))->toBeFalse() + ->and($store->redirects())->toBe([]); +}); + +it('ignores what the option holds that is not a rule', function (): void { + $options = redirectOptions(); + $options['headless_redirects'] = ['x' => 'junk', 'y' => ['from' => 'bad', 'to' => '/x'], '/ok' => ['from' => '/ok', 'to' => '/fine']]; + $store = new OptionRedirectStore; + + expect(array_map(static fn (Redirect $rule): string => $rule->from, $store->redirects()))->toBe(['/ok']); + + $options['headless_redirects'] = 'broken'; + + expect($store->redirects())->toBe([]); +}); + +it('lists the sources in order, so that the first one wins', function (): void { + $source = static fn (Redirect ...$rules): RedirectSource => new class($rules) implements RedirectSource + { + /** @param list $rules */ + public function __construct(private array $rules) {} + + public function redirects(): array + { + return $this->rules; + } + }; + + $rules = (new RedirectCatalog([$source(new Redirect('/a', '/manual')), $source(new Redirect('/a', '/old-slug', 301, false, 'old-slug'), new Redirect('/b', '/c'))]))->rules(); + + expect($rules->all())->toHaveCount(3)->and($rules->match('/a')['to'])->toBe('/manual'); +}); + +it('registers its routes, and drops the old slugs when a post changes', function (): void { + Actions\expectAdded('rest_api_init')->once(); + Actions\expectAdded('post_updated')->once(); + Actions\expectAdded('deleted_post')->once(); + $routes = new RedirectRoutes(new RedirectCatalog([])); + $routes->register(new WordPressHooks); + + Functions\expect('register_rest_route')->twice()->with('headless/v1', Mockery::pattern('#^/redirects#'), Mockery::on(static fn (array $args): bool => $args['methods'] === 'GET' && $args['permission_callback'] === '__return_true')); + $routes->routes(); +}); + +function wpResponse(): 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; + }); +} + +it('lists the rules, and says when the list was cut', function (): void { + wpResponse(); + $catalog = new RedirectCatalog([new class implements RedirectSource + { + public function redirects(): array + { + return [new Redirect('/a', '/b'), new Redirect('/g', '', 410, false, 'manual')]; + } + }]); + + $data = (new RedirectRoutes($catalog))->all()->get_data(); + + expect($data['count'])->toBe(2) + ->and($data['truncated'])->toBeFalse() + ->and($data['redirects'][0])->toBe(['from' => '/a', 'to' => '/b', 'status' => 301, 'regex' => false, 'source' => 'manual']) + ->and($data['redirects'][1]['status'])->toBe(410); +}); + +it('resolves one path, with a 200 and null when it goes nowhere', function (): void { + wpResponse(); + $routes = new RedirectRoutes(new RedirectCatalog([new class implements RedirectSource + { + public function redirects(): array + { + return [new Redirect('/blog/(.*)', '/news/$1', 308, true, 'manual')]; + } + }])); + $ask = static function (string $path): WP_REST_Request { + $request = Mockery::mock('WP_REST_Request'); + $request->shouldReceive('get_param')->with('path')->andReturn($path); + + return $request; + }; + + expect($routes->resolve($ask('/blog/hello'))->get_data())->toBe(['redirect' => ['from' => '/blog/(.*)', 'to' => '/news/hello', 'status' => 308, 'source' => 'manual']]) + ->and($routes->resolve($ask('/elsewhere'))->get_data())->toBe(['redirect' => null]); +}); + +it('keeps the list of old slugs for five minutes and drops it on demand', function (): void { + $transients = new ArrayObject; + Functions\when('get_transient')->alias(static fn (string $key): mixed => $transients[$key] ?? false); + Functions\when('set_transient')->alias(function (string $key, mixed $value, int $seconds) use ($transients): bool { + $transients[$key] = $value; + expect($seconds)->toBe(300); + + return true; + }); + Functions\when('delete_transient')->alias(function (string $key) use ($transients): bool { + unset($transients[$key]); + + return true; + }); + $wpdb = Mockery::mock('wpdb'); + $wpdb->postmeta = 'wp_postmeta'; + $wpdb->posts = 'wp_posts'; + $wpdb->shouldReceive('prepare')->andReturn('SQL'); + $wpdb->shouldReceive('get_results')->once()->andReturn([(object) ['post_id' => 7, 'old_slug' => 'before'], (object) ['post_id' => 7, 'old_slug' => 'hello'], (object) ['post_id' => 99, 'old_slug' => 'ghost'], (object) ['post_id' => 7, 'old_slug' => '']]); + $GLOBALS['wpdb'] = $wpdb; + + $post = Mockery::mock('WP_Post'); + $post->post_name = 'hello'; + Functions\when('get_post')->alias(static fn (int $id): ?WP_Post => $id === 7 ? $post : null); + Functions\when('get_permalink')->alias(static fn (WP_Post $p): string => 'https://cms.example.com/'.$p->post_name.'/'); + + $source = new OldSlugRedirects(new UrlMapper(Origin::fromUrl('https://cms.example.com'), Origin::fromUrl('https://www.example.com'))); + $first = $source->redirects(); + $second = $source->redirects(); + + expect($first)->toHaveCount(1) + ->and($first[0]->from)->toBe('/before/') + ->and($first[0]->to)->toBe('/hello/') + ->and($first[0]->source)->toBe('old-slug') + ->and($second)->toEqual($first) + ->and($transients)->toHaveCount(1); + + OldSlugRedirects::forget(); + + expect($transients)->toHaveCount(0); + unset($GLOBALS['wpdb']); +}); + +it('skips a post whose old and current addresses are the same (plain permalinks)', function (): void { + Functions\when('get_transient')->justReturn(false); + Functions\when('set_transient')->justReturn(true); + $wpdb = Mockery::mock('wpdb'); + $wpdb->postmeta = 'wp_postmeta'; + $wpdb->posts = 'wp_posts'; + $wpdb->shouldReceive('prepare')->andReturn('SQL'); + $wpdb->shouldReceive('get_results')->andReturn([(object) ['post_id' => 7, 'old_slug' => 'before']]); + $GLOBALS['wpdb'] = $wpdb; + $post = Mockery::mock('WP_Post'); + $post->post_name = 'hello'; + Functions\when('get_post')->justReturn($post); + Functions\when('get_permalink')->justReturn('https://cms.example.com/?p=7'); + + $source = new OldSlugRedirects(new UrlMapper(Origin::fromUrl('https://cms.example.com'), Origin::fromUrl('https://www.example.com'))); + + expect($source->redirects())->toBe([]); + unset($GLOBALS['wpdb']); +}); + +function redirectOutput(): object +{ + return new class implements Output + { + /** @var list */ + public array $messages = []; + + public function line(string $message): void + { + $this->messages[] = 'line: '.$message; + } + + public function success(string $message): void + { + $this->messages[] = 'success: '.$message; + } + + public function warning(string $message): void + { + $this->messages[] = 'warning: '.$message; + } + + public function error(string $message): void + { + $this->messages[] = 'error: '.$message; + } + }; +} + +function redirectCommand(Output $output): RedirectCommand +{ + redirectOptions(); + $store = new OptionRedirectStore; + + return new RedirectCommand($store, fn (): RedirectCatalog => new RedirectCatalog([$store]), $output); +} + +it('adds, lists, tests and removes a redirect from the command line', function (): void { + $output = redirectOutput(); + $command = redirectCommand($output); + + $command->add(['/old/', '/new/']); + $command->add(['/blog/(.*)', '/news/$1'], ['regex' => true, 'status' => '308']); + $command->add(['/discontinued/'], ['status' => '410']); + $command->list_(); + $command->test(['/old']); + $command->test(['/blog/hello']); + $command->test(['/discontinued/']); + $command->test(['/nothing']); + $command->remove(['/old/']); + $command->remove(['/old/']); + + expect($output->messages)->toBe([ + 'success: /old/ → /new/ (301).', + 'success: /blog/(.*) → /news/$1 (308).', + 'success: /discontinued/ → gone (410).', + 'line: manual /old/ → /new/ (301)', + 'line: manual ~ /blog/(.*) → /news/$1 (308)', + 'line: manual /discontinued/ → gone (410)', + 'success: /old → /new/ (301, from the manual rule /old/).', + 'success: /blog/hello → /news/hello (308, from the manual rule /blog/(.*)).', + 'success: /discontinued/ → gone (410, from the manual rule /discontinued/).', + 'line: /nothing is not redirected.', + 'success: Redirect removed.', + 'error: No redirect for "/old/" among the ones you manage.', + ]); +}); + +it('says what is wrong with a rule, and when there is none to list', function (): void { + $output = redirectOutput(); + $command = redirectCommand($output); + + $command->list_(); + $command->add(['old', '/new']); + $command->add(['/a', '/a']); + $command->add(['/a', '/b'], ['status' => '200']); + $command->add([]); + + expect($output->messages[0])->toBe('line: No redirect.') + ->and($output->messages[1])->toContain('error:')->toContain('is not a path to redirect') + ->and($output->messages[2])->toContain('redirects to itself') + ->and($output->messages[3])->toContain('is not a redirect status') + ->and($output->messages[4])->toContain('error:'); +}); + +it('reads the redirect settings', function (): void { + $on = Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com'); + $off = Settings::fromArray(['frontend_url' => 'https://www.example.com', 'redirects' => ['enabled' => false, 'old_slugs' => false]], 'https://cms.example.com'); + + expect($on->redirects)->toBeTrue()->and($on->oldSlugRedirects)->toBeTrue() + ->and($off->redirects)->toBeFalse()->and($off->oldSlugRedirects)->toBeFalse() + ->and(Settings::fromArray([], 'https://cms.example.com')->redirects)->toBeFalse(); +});