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
2 changes: 1 addition & 1 deletion .github/workflows/harness.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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-seo
wordpress-plugins: polylang,action-scheduler,wordpress-seo,wp-graphql,contact-form-7
permissions:
contents: read
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,9 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- 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.
- Optional WPGraphQL support: its settings imposed in code (introspection, debug, batch size, depth), CORS from the package policy, API tokens with scopes (a read token cannot run a mutation).
- `wp headless schema openapi` and `wp headless schema graphql`: the schema of the API as files for a client generator.
- `GET /wp-json/headless/v1/search`: the site search in one shape, with front-end addresses (`headless/search/args` filter).
- `GET /wp-json/headless/v1/forms` and `/forms/{provider}/{id}`: forms and how to send them, from Contact Form 7 (`headless/forms/providers` filter for other plugins).
- `X-GraphQL-Preview` among the request headers CORS allows.
- mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer.
41 changes: 40 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo
| 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). |
| GraphQL | WPGraphQL made safe for a public site: its settings imposed in code, CORS, API tokens with scopes. See [GraphQL](#graphql-optional). |
| Schema, search, forms | `wp headless schema` (openapi or graphql), `GET /headless/v1/search`, `GET /headless/v1/forms` (Contact Form 7). |
| 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 @@ -222,9 +224,46 @@ The keys are the same whichever plugin gave them, and `null` when it has nothing

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.

## GraphQL (optional)

REST is the contract; if you also run [WPGraphQL](https://wordpress.org/plugins/wp-graphql/), the package makes it safe for a public site. Nothing happens while the plugin is not active, and the package never ships its code.

- Its settings are **imposed in code** (the `graphql` section of the settings), not written to the database: no public introspection, no debug output, batches of five at most and a depth limit of 15, because WPGraphQL has no query cost limit. Set a key to `null` to leave that setting to WPGraphQL.
- Its `Access-Control-Allow-Origin: *` is replaced by the [CORS](#install) policy of the package.
- An API token (`Authorization: Bearer hl.…`) may call it. A token without the `write` scope cannot run a mutation, and a token limited to routes needs `/graphql` among them.
- **Preview**: a server-side client sends its API token and `X-GraphQL-Preview: database_id=12`, which WPGraphQL handles itself. The preview *session* (`hlp.…`) is not accepted on GraphQL on purpose: it is made for one post, and WPGraphQL would run the request with all the rights of the editor.
- With introspection closed, a client generator reads the schema with a token, or from the file `wp headless schema graphql --file=schema.graphql`.

## Schema files

`wp headless schema openapi --namespace=wp/v2,headless/v1 --file=openapi.json` writes an OpenAPI 3.0 document of the REST API (routes, path and query parameters, request bodies), and `wp headless schema graphql` the GraphQL schema as SDL. Feed them to your client generator. WordPress does not describe what an endpoint returns, so every answer is a plain `200`.

## Search

```js
const found = await (await fetch('https://cms.example.com/wp-json/headless/v1/search?q=finch&type=post,page&lang=fr&page=1&per_page=10')).json();
// { query, page, per_page, total, pages, results: [{ id, type, title, excerpt, url, language, date, image }] }
```

It looks in the public content types (or the ones in `type`), leaves out what a password protects, and gives each result its address on the front end. `per_page` is capped by `per_page_max`. The filter `headless/search/args` changes the `WP_Query` arguments, to bring in a search plugin. Only active once a front-end URL is set.

## Forms

`GET /wp-json/headless/v1/forms` lists the forms of the site, and `/forms/cf7/12` describes one: its fields (`name`, `type`, `required`, `multiple`, choices) and where to post them.

```js
const form = await (await fetch('https://cms.example.com/wp-json/headless/v1/forms/cf7/12')).json();
const body = new FormData();
for (const [name, value] of Object.entries(form.submit.extra)) body.append(name, value); // Contact Form 7 needs its unit tag
body.append('your-email', 'a@example.com');
await fetch(form.submit.url, { method: 'POST', body }); // multipart/form-data, taken by the form plugin itself
```

Contact Form 7 is supported and verified against the real plugin in CI. A checkbox group is posted as `name[]`. Gravity Forms, WPForms and the others are not supported yet; `add_filter('headless/forms/providers', …)` adds an adapter (a `FormProvider`).

## 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 · `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.
`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 · `0.7` optional WPGraphQL, schema files, search and forms (this release) · `0.8` doctor, end-to-end tests · `1.0` frozen contract.

## Quality

Expand Down
6 changes: 3 additions & 3 deletions composer-dependency-analyser.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@

return (new Configuration)
->disableReportingUnmatchedIgnores()
->ignoreUnknownClassesRegex('~^(WP_|Walker_|Requests_|wpdb$)~')
// Action Scheduler is a plugin, loaded by WordPress or by another package: the code checks it exists before it uses it
->ignoreUnknownClasses(['ActionScheduler', 'ActionScheduler_Store'])
->ignoreUnknownClassesRegex('~^(WP_|WPCF7_|Walker_|Requests_|wpdb$)~')
// Action Scheduler and WPGraphQL are plugins, loaded by WordPress or by another package: the code checks it exists before it uses it
->ignoreUnknownClasses(['ActionScheduler', 'ActionScheduler_Store', 'GraphQL\\Error\\UserError', 'GraphQL\\Utils\\SchemaPrinter', 'WPGraphQL'])
->ignoreUnknownFunctionsRegex('~.*~')
->ignoreErrorsOnExtensions(['ext-ctype', 'ext-filter', 'ext-json', 'ext-mbstring'], [ErrorType::SHADOW_DEPENDENCY])
->ignoreErrorsOnPackage('illuminate/support', [ErrorType::DEV_DEPENDENCY_IN_PROD])
Expand Down
29 changes: 29 additions & 0 deletions config/headless.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,33 @@
'seo' => [
'enabled' => true,
],

// WPGraphQL, when the plugin is active (nothing happens otherwise). Its settings live in the database, where an editor can change
// them; these are imposed in code instead. Set a key to null to leave that setting to WPGraphQL. Introspection stays closed to
// visitors (a logged-in API token can still read the schema, and `wp headless schema graphql` writes it to a file); WPGraphQL has no
// query cost limit, so the batch size and the depth are capped. The CORS answer comes from the `cors` section above.
// An API token may call GraphQL: a token without the write scope cannot run a mutation. Preview with a token and `X-GraphQL-Preview`.
'graphql' => [
'enabled' => true,
'introspection' => false,
'debug' => false,
'batch_limit' => 5, // 0 turns batching off
'max_depth' => 15, // 0 turns the depth limit off
'graphiql' => null,
'restrict_to_logged_in' => null,
],

// The search of the site in one shape: GET /wp-json/headless/v1/search?q=word&type=post,page&lang=fr&page=1&per_page=10, with each
// result's address on the front end, its language, a short text and its image. Public content types only, no protected post. The
// filter `headless/search/args` changes the WP_Query arguments. Only active once a front-end URL is set.
'search' => [
'enabled' => true,
],

// The forms of the site and how to send them: GET /wp-json/headless/v1/forms, then /forms/cf7/12 for the fields (name, type, required,
// choices) and where to post them. Contact Form 7 is supported; the plugin itself takes the submission. The filter
// `headless/forms/providers` adds an adapter for another form plugin.
'forms' => [
'enabled' => true,
],
];
4 changes: 4 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,9 @@ parameters:
ignoreErrors:
# Action Scheduler is a plugin, not part of the WordPress stubs: the package uses its functions only after checking they exist
- '#Function as_[a-z_]+ not found#'
# WPGraphQL is a plugin too: its error class exists only while it is active, and the guard runs from its own filter
- '#GraphQL\\Error\\UserError#'
# Contact Form 7 too: the adapter runs only once it checked the plugin is active
- '#WPCF7_(ContactForm|FormTag)#'
# Only the patterns still needed are listed: report one that no longer matches, so it is removed
reportUnmatchedIgnoredErrors: true
2 changes: 1 addition & 1 deletion src/Domain/Cors/CorsPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function __construct(
array $origins,
private bool $credentials = false,
private array $methods = ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE'],
private array $headers = ['Authorization', 'Content-Type', 'Accept', 'X-WP-Nonce', 'X-HTTP-Method-Override'],
private array $headers = ['Authorization', 'Content-Type', 'Accept', 'X-WP-Nonce', 'X-HTTP-Method-Override', 'X-GraphQL-Preview'],
private int $maxAge = 600,
private array $exposeHeaders = ['X-WP-Total', 'X-WP-TotalPages', 'Link'],
) {
Expand Down
47 changes: 47 additions & 0 deletions src/Domain/Form/Form.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Form;

/**
* A form of the site and how to send it: the fields, then where and how to post them.
*
* The submission goes to the form plugin itself (it validates, sends the mail, keeps the entry): this
* description only tells a client what to send.
*/
final readonly class Form
{
/**
* @param list<FormField> $fields
* @param array<string, string> $extra fields to send with the others, that the plugin needs
*/
public function __construct(
public string $provider,
public string $id,
public string $title,
public array $fields,
public string $submitUrl,
public string $contentType,
public array $extra = [],
) {}

/**
* @return array<string, mixed>
*/
public function summary(): array
{
return ['provider' => $this->provider, 'id' => $this->id, 'title' => $this->title];
}

/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return $this->summary() + [
'fields' => array_map(static fn (FormField $field): array => $field->toArray(), $this->fields),
'submit' => ['method' => 'POST', 'url' => $this->submitUrl, 'content_type' => $this->contentType, 'extra' => (object) $this->extra],
];
}
}
37 changes: 37 additions & 0 deletions src/Domain/Form/FormField.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Form;

/**
* One input of a form, as a client needs it to draw the input and send the value.
*/
final readonly class FormField
{
/**
* @param string $type text, email, url, tel, number, date, textarea, select, checkbox, radio, acceptance, quiz or file
* @param list<array{value: string, label: string}> $options the choices of a select, a checkbox group or a radio group
*/
public function __construct(
public string $name,
public string $type,
public bool $required = false,
public bool $multiple = false,
public array $options = [],
) {}

/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'name' => $this->name,
'type' => $this->type,
'required' => $this->required,
'multiple' => $this->multiple,
'options' => $this->options,
];
}
}
21 changes: 21 additions & 0 deletions src/Domain/Form/FormProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Form;

/**
* A form plugin the package can describe the forms of.
*/
interface FormProvider
{
/** The name a client sees in the address: `cf7`. */
public function name(): string;

/**
* @return list<Form>
*/
public function forms(): array;

public function find(string $id): ?Form;
}
91 changes: 91 additions & 0 deletions src/Domain/GraphQl/GraphQlPolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\GraphQl;

/**
* The WPGraphQL settings the package imposes in code.
*
* WPGraphQL keeps them in the database (`graphql_general_settings`), where an editor can change them
* and a staging copy can carry the wrong ones. Each field here is either a value to impose or null to
* leave the setting alone. The defaults are the cautious ones for a public API: no public introspection,
* no debug output, a short batch and a depth limit, because WPGraphQL has no query cost limit.
*
* `batchLimit` 0 turns batching off, `maxDepth` 0 turns the depth limit off.
*/
final readonly class GraphQlPolicy
{
/** The option group WPGraphQL reads its general settings from. */
public const string SECTION = 'graphql_general_settings';

public function __construct(
public ?bool $introspection = false,
public ?bool $debug = false,
public ?int $batchLimit = 5,
public ?int $maxDepth = 15,
public ?bool $graphiql = null,
public ?bool $restrictToLoggedIn = null,
) {}

/**
* The settings to impose, by WPGraphQL option name, as WPGraphQL stores them (`on`/`off`, numbers).
*
* @return array<string, string|int>
*/
public function forced(): array
{
$forced = [];

if ($this->introspection !== null) {
$forced['public_introspection_enabled'] = self::onOff($this->introspection);
}

if ($this->debug !== null) {
$forced['debug_mode_enabled'] = self::onOff($this->debug);
}

if ($this->batchLimit !== null) {
$forced['batch_queries_enabled'] = self::onOff($this->batchLimit > 0);

if ($this->batchLimit > 0) {
$forced['batch_limit'] = $this->batchLimit;
}
}

if ($this->maxDepth !== null) {
$forced['query_depth_enabled'] = self::onOff($this->maxDepth > 0);

if ($this->maxDepth > 0) {
$forced['query_depth_max'] = $this->maxDepth;
}
}

if ($this->graphiql !== null) {
$forced['graphiql_enabled'] = self::onOff($this->graphiql);
}

if ($this->restrictToLoggedIn !== null) {
$forced['restrict_endpoint_to_logged_in_users'] = self::onOff($this->restrictToLoggedIn);
}

return $forced;
}

/**
* What WPGraphQL should read for a setting: the imposed value, or the one it had.
*/
public function resolve(string $section, string $option, mixed $value): mixed
{
if ($section !== self::SECTION) {
return $value;
}

return $this->forced()[$option] ?? $value;
}

private static function onOff(bool $on): string
{
return $on ? 'on' : 'off';
}
}
Loading
Loading