Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:<id>` 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.
Expand Down
8 changes: 8 additions & 0 deletions config/headless.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
],
];
38 changes: 38 additions & 0 deletions src/Domain/Exceptions/InvalidRedirectException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Exceptions;

use InvalidArgumentException;

/**
* Raised when a redirect rule cannot be kept: an address that is not one, a status that is not a redirect, a pattern that does not compile.
*/
final class InvalidRedirectException extends InvalidArgumentException
{
public static function badSource(string $from): self
{
return new self(sprintf('"%s" is not a path to redirect: it must start with "/" and hold no space.', $from));
}

public static function badTarget(string $to): self
{
return new self(sprintf('"%s" is not a destination: use a path starting with "/" or an absolute http(s) URL.', $to));
}

public static function badStatus(int $status): self
{
return new self(sprintf('%d is not a redirect status (use 301, 302, 307, 308, or 410 for a page that is gone).', $status));
}

public static function badPattern(string $from): self
{
return new self(sprintf('"%s" is not a valid pattern.', $from));
}

public static function loop(string $from): self
{
return new self(sprintf('"%s" redirects to itself.', $from));
}
}
18 changes: 18 additions & 0 deletions src/Domain/Front/UrlPath.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Front;

/**
* The path of an address, with its query when it has one: `https://www.example.com/a/?b=1` gives `/a/?b=1`.
*/
final class UrlPath
{
public static function of(string $url): string
{
$query = parse_url($url, PHP_URL_QUERY);

return ((string) parse_url($url, PHP_URL_PATH) ?: '/').(is_string($query) ? '?'.$query : '');
}
}
121 changes: 121 additions & 0 deletions src/Domain/Redirect/Redirect.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Redirect;

use Pollora\Headless\Domain\Exceptions\InvalidRedirectException;

/**
* A rule that sends a visitor of one path to another: `/old/` to `/new/` with a 301, or a pattern such as
* `/blog/(.*)` to `/news/$1`. A 410 says the page is gone and has no destination.
*
* The rule is checked when it is made: a front end that reads a list of redirects must be able to trust it.
*/
final readonly class Redirect
{
private const array STATUSES = [301, 302, 307, 308, 410];

private const int MAX_LENGTH = 2000;

public function __construct(
public string $from,
public string $to,
public int $status = 301,
public bool $regex = false,
public string $source = 'manual',
) {
if (! str_starts_with($from, '/') || preg_match('/\s/', $from) === 1 || strlen($from) > 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<mixed> $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;
}
}
58 changes: 58 additions & 0 deletions src/Domain/Redirect/RedirectRules.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Redirect;

/**
* The redirects of the site, from every source, asked "where does this path go?".
*
* An exact rule wins over a pattern, and between rules of the same kind the first one listed wins: the sources
* are listed from the most deliberate (what an editor typed) to the least (the old slugs WordPress remembers).
*/
final readonly class RedirectRules
{
/** @var list<Redirect> */
private array $exact;

/** @var list<Redirect> */
private array $patterns;

/**
* @param list<Redirect> $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<Redirect>
*/
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;
}
}
16 changes: 16 additions & 0 deletions src/Domain/Redirect/RedirectSource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Redirect;

/**
* Where redirects come from: the ones an editor wrote, the old addresses of renamed posts, a SEO plugin's manager.
*/
interface RedirectSource
{
/**
* @return list<Redirect>
*/
public function redirects(): array;
}
17 changes: 17 additions & 0 deletions src/Domain/Redirect/RedirectStore.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Redirect;

/**
* The redirects an editor manages: stored by the package, read and written one rule at a time.
*/
interface RedirectStore extends RedirectSource
{
/** Adds a rule, or replaces the one for the same source path. */
public function save(Redirect $redirect): void;

/** Removes the rule for a path; returns whether there was one. */
public function remove(string $from): bool;
}
4 changes: 4 additions & 0 deletions src/Infrastructure/Config/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ private function __construct(
public int $revalidationAttempts,
public array $revalidationOptions,
public bool $manifest,
public bool $redirects,
public bool $oldSlugRedirects,
) {}

/**
Expand Down Expand Up @@ -118,6 +120,8 @@ public static function fromArray(array $config, string $backendUrl): self
revalidationAttempts: min(5, max(1, self::int($revalidation, 'max_attempts', 5))),
revalidationOptions: array_values(array_unique([...ChangeWatcher::defaultOptions(), ...self::strings($revalidation, 'options')])),
manifest: $front instanceof Origin && self::bool(is_array($config['manifest'] ?? null) ? $config['manifest'] : [], 'enabled', true),
redirects: $front instanceof Origin && self::bool(is_array($config['redirects'] ?? null) ? $config['redirects'] : [], 'enabled', true),
oldSlugRedirects: self::bool(is_array($config['redirects'] ?? null) ? $config['redirects'] : [], 'old_slugs', true),
);
}

Expand Down
Loading
Loading