From 1839591747c58a9ef0af17254ce983c530802416 Mon Sep 17 00:00:00 2001 From: Olivier Gorzalka Date: Tue, 24 Nov 2026 17:53:07 +0100 Subject: [PATCH 1/6] feat(graphql): impose WPGraphQL settings in code, CORS and API tokens on the GraphQL endpoint --- composer-dependency-analyser.php | 4 +- config/headless.php | 15 ++ phpstan.neon | 2 + src/Domain/Cors/CorsPolicy.php | 2 +- src/Domain/GraphQl/GraphQlPolicy.php | 91 +++++++++ src/Infrastructure/Config/Settings.php | 28 +++ src/Infrastructure/WordPress/Bootstrap.php | 10 +- src/Infrastructure/WordPress/GraphQl.php | 110 +++++++++++ .../WordPress/TokenAuthentication.php | 10 +- tests/Unit/Domain/CorsPolicyTest.php | 2 +- tests/Unit/GraphQlTest.php | 180 ++++++++++++++++++ tests/Unit/Infrastructure/ModulesTest.php | 4 +- 12 files changed, 449 insertions(+), 9 deletions(-) create mode 100644 src/Domain/GraphQl/GraphQlPolicy.php create mode 100644 src/Infrastructure/WordPress/GraphQl.php create mode 100644 tests/Unit/GraphQlTest.php diff --git a/composer-dependency-analyser.php b/composer-dependency-analyser.php index 1cb7db4..2eeee4b 100644 --- a/composer-dependency-analyser.php +++ b/composer-dependency-analyser.php @@ -17,8 +17,8 @@ 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']) + // 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']) ->ignoreUnknownFunctionsRegex('~.*~') ->ignoreErrorsOnExtensions(['ext-ctype', 'ext-filter', 'ext-json', 'ext-mbstring'], [ErrorType::SHADOW_DEPENDENCY]) ->ignoreErrorsOnPackage('illuminate/support', [ErrorType::DEV_DEPENDENCY_IN_PROD]) diff --git a/config/headless.php b/config/headless.php index 85bd3e6..f7dec7d 100644 --- a/config/headless.php +++ b/config/headless.php @@ -152,4 +152,19 @@ '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, + ], ]; diff --git a/phpstan.neon b/phpstan.neon index 636e410..1618d39 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -16,5 +16,7 @@ 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#' # Only the patterns still needed are listed: report one that no longer matches, so it is removed reportUnmatchedIgnoredErrors: true diff --git a/src/Domain/Cors/CorsPolicy.php b/src/Domain/Cors/CorsPolicy.php index 500bc85..247050e 100644 --- a/src/Domain/Cors/CorsPolicy.php +++ b/src/Domain/Cors/CorsPolicy.php @@ -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'], ) { diff --git a/src/Domain/GraphQl/GraphQlPolicy.php b/src/Domain/GraphQl/GraphQlPolicy.php new file mode 100644 index 0000000..b25c0a5 --- /dev/null +++ b/src/Domain/GraphQl/GraphQlPolicy.php @@ -0,0 +1,91 @@ + + */ + 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'; + } +} diff --git a/src/Infrastructure/Config/Settings.php b/src/Infrastructure/Config/Settings.php index cd6ba0c..790e6df 100644 --- a/src/Infrastructure/Config/Settings.php +++ b/src/Infrastructure/Config/Settings.php @@ -12,6 +12,7 @@ use Pollora\Headless\Domain\Front\Origin; use Pollora\Headless\Domain\Front\RedirectStatus; use Pollora\Headless\Domain\Front\UrlMapper; +use Pollora\Headless\Domain\GraphQl\GraphQlPolicy; use Pollora\Headless\Domain\Revalidation\Target; use Pollora\Headless\Infrastructure\Exceptions\InvalidSettingsException; use Pollora\Headless\Infrastructure\WordPress\ChangeWatcher; @@ -66,6 +67,7 @@ private function __construct( public ?string $mediaCdn, public bool $blocks, public bool $seo, + public ?GraphQlPolicy $graphql, ) {} /** @@ -131,6 +133,32 @@ public static function fromArray(array $config, string $backendUrl): self mediaCdn: self::mediaCdn($media), blocks: $front instanceof Origin && self::bool(is_array($config['blocks'] ?? null) ? $config['blocks'] : [], 'enabled', true), seo: $front instanceof Origin && self::bool(is_array($config['seo'] ?? null) ? $config['seo'] : [], 'enabled', true), + graphql: self::graphql($config['graphql'] ?? null), + ); + } + + /** + * The WPGraphQL settings to impose, or null when the module is off. A key set to null leaves that setting to WPGraphQL. + */ + private static function graphql(mixed $config): ?GraphQlPolicy + { + $config = is_array($config) ? $config : []; + + if (! self::bool($config, 'enabled', true)) { + return null; + } + + $defaults = new GraphQlPolicy; + $flag = static fn (string $key, ?bool $default): ?bool => array_key_exists($key, $config) ? ($config[$key] === null ? null : self::bool($config, $key, (bool) $default)) : $default; + $number = static fn (string $key, ?int $default): ?int => array_key_exists($key, $config) ? ($config[$key] === null ? null : max(0, self::int($config, $key, (int) $default))) : $default; + + return new GraphQlPolicy( + introspection: $flag('introspection', $defaults->introspection), + debug: $flag('debug', $defaults->debug), + batchLimit: $number('batch_limit', $defaults->batchLimit), + maxDepth: $number('max_depth', $defaults->maxDepth), + graphiql: $flag('graphiql', $defaults->graphiql), + restrictToLoggedIn: $flag('restrict_to_logged_in', $defaults->restrictToLoggedIn), ); } diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index 57ef007..df6ab95 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -11,6 +11,7 @@ use Pollora\Headless\Domain\Cors\CorsPolicy; use Pollora\Headless\Domain\Front\Origin; use Pollora\Headless\Domain\Front\UrlMapper; +use Pollora\Headless\Domain\GraphQl\GraphQlPolicy; use Pollora\Headless\Domain\Language\Languages; use Pollora\Headless\Domain\Language\LanguageUrls; use Pollora\Headless\Domain\Media\MediaUrls; @@ -74,8 +75,15 @@ public static function modules(Settings $settings, ?Languages $languages = null) $modules[] = new Cors($settings->cors); } + $tokens = null; + if ($settings->apiTokens) { - $modules[] = new TokenAuthentication(new TokenService(new UserMetaTokenStore)); + $tokens = new TokenAuthentication(new TokenService(new UserMetaTokenStore)); + $modules[] = $tokens; + } + + if ($settings->graphql instanceof GraphQlPolicy) { + $modules[] = new GraphQl($settings->graphql, $settings->cors, $tokens); } if ($settings->previewUrl !== null && $settings->front instanceof Origin) { diff --git a/src/Infrastructure/WordPress/GraphQl.php b/src/Infrastructure/WordPress/GraphQl.php new file mode 100644 index 0000000..a75fe44 --- /dev/null +++ b/src/Infrastructure/WordPress/GraphQl.php @@ -0,0 +1,110 @@ + 'GET', 'RootMutation' => 'POST']; + + public function __construct( + private readonly GraphQlPolicy $policy, + private readonly ?CorsPolicy $cors = null, + private readonly ?TokenAuthentication $tokens = null, + ) {} + + public function register(HookRegistrar $hooks): void + { + $hooks->addFilter('graphql_get_setting_section_field_value', [$this, 'setting'], 20, 5); + + if ($this->cors instanceof CorsPolicy) { + $hooks->addFilter('graphql_response_headers_to_send', [$this, 'headers'], 20); + } + + if ($this->tokens instanceof TokenAuthentication) { + $hooks->addFilter('graphql_pre_resolve_field', [$this, 'guard'], 5, 6); + } + } + + /** + * @param array $fields + */ + public function setting(mixed $value, mixed $default, string $option, array $fields, string $section): mixed + { + return $this->policy->resolve($section, $option, $value); + } + + /** + * @param array $headers + * @return array + */ + public function headers(array $headers): array + { + if (! $this->cors instanceof CorsPolicy) { + return $headers; + } + + $decision = $this->cors->decide(new CorsRequest( + self::server('HTTP_ORIGIN'), + self::server('REQUEST_METHOD') ?? 'POST', + self::server('HTTP_ACCESS_CONTROL_REQUEST_METHOD'), + self::server('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'), + )); + + $vary = array_filter(array_map(trim(...), explode(',', ($headers['Vary'] ?? '').','.($decision->headers['Vary'] ?? ''))), static fn (string $name): bool => $name !== ''); + + unset($headers['Access-Control-Allow-Origin'], $headers['Access-Control-Allow-Headers'], $headers['Access-Control-Max-Age']); + + $headers = [...$headers, ...$decision->headers]; + $headers['Vary'] = implode(', ', array_values(array_unique($vary))); + + return $headers; + } + + /** + * Stops a root field a token is not allowed to run: the pre-resolve filter runs before any resolver. + * + * @param mixed $result what an earlier filter resolved, null when nothing did + */ + public function guard(mixed $result, mixed $source, mixed $args, mixed $context, mixed $info, string $typeName = ''): mixed + { + $token = $this->tokens?->token(); + + if (! $token instanceof Token || ! isset(self::ROOT_TYPES[$typeName])) { + return $result; + } + + if (! ScopePolicy::allows($token, self::ROOT_TYPES[$typeName], '/graphql')) { + throw new UserError('This API token is not allowed to make this request.'); + } + + return $result; + } + + private static function server(string $key): ?string + { + $value = $_SERVER[$key] ?? null; + + return is_string($value) && $value !== '' ? $value : null; + } +} diff --git a/src/Infrastructure/WordPress/TokenAuthentication.php b/src/Infrastructure/WordPress/TokenAuthentication.php index fe806d7..90bfc3a 100644 --- a/src/Infrastructure/WordPress/TokenAuthentication.php +++ b/src/Infrastructure/WordPress/TokenAuthentication.php @@ -30,13 +30,13 @@ final class TokenAuthentication implements Module private readonly Closure $isRestRequest; /** - * @param (callable(): bool)|null $isRestRequest whether this is a REST request; replaced in tests + * @param (callable(): bool)|null $isRestRequest whether this is a REST or a GraphQL request; replaced in tests */ public function __construct( private readonly TokenService $tokens, ?callable $isRestRequest = null, ) { - $this->isRestRequest = $isRestRequest !== null ? Closure::fromCallable($isRestRequest) : static fn (): bool => defined('REST_REQUEST') && REST_REQUEST; + $this->isRestRequest = $isRestRequest !== null ? Closure::fromCallable($isRestRequest) : static fn (): bool => (defined('REST_REQUEST') && REST_REQUEST) || (function_exists('is_graphql_http_request') && is_graphql_http_request()); } public function register(HookRegistrar $hooks): void @@ -92,6 +92,12 @@ public function enforceScopes(mixed $response, mixed $handler, \WP_REST_Request return new \WP_Error('headless_token_scope', 'This API token is not allowed to make this request.', ['status' => 403]); } + /** The token the request is made with, when it is one. */ + public function token(): ?Token + { + return $this->token; + } + private static function bearer(): ?string { $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? null; diff --git a/tests/Unit/Domain/CorsPolicyTest.php b/tests/Unit/Domain/CorsPolicyTest.php index aeee618..63bb695 100644 --- a/tests/Unit/Domain/CorsPolicyTest.php +++ b/tests/Unit/Domain/CorsPolicyTest.php @@ -65,7 +65,7 @@ function cors(array $origins = ['https://www.example.com'], bool $credentials = it('lists its own headers when a preflight asks for one it does not allow', function (): void { $decision = cors()->decide(new CorsRequest('https://www.example.com', 'OPTIONS', 'GET', 'x-evil')); - expect($decision->headers['Access-Control-Allow-Headers'])->toBe('Authorization, Content-Type, Accept, X-WP-Nonce, X-HTTP-Method-Override'); + expect($decision->headers['Access-Control-Allow-Headers'])->toBe('Authorization, Content-Type, Accept, X-WP-Nonce, X-HTTP-Method-Override, X-GraphQL-Preview'); }); it('knows what a preflight is', function (): void { diff --git a/tests/Unit/GraphQlTest.php b/tests/Unit/GraphQlTest.php new file mode 100644 index 0000000..f04c3fb --- /dev/null +++ b/tests/Unit/GraphQlTest.php @@ -0,0 +1,180 @@ +forced())->toBe([ + 'public_introspection_enabled' => 'off', + 'debug_mode_enabled' => 'off', + 'batch_queries_enabled' => 'on', + 'batch_limit' => 5, + 'query_depth_enabled' => 'on', + 'query_depth_max' => 15, + ]); +}); + +it('leaves alone a setting set to null and turns off batch and depth with 0', function (): void { + $policy = new GraphQlPolicy(introspection: null, debug: null, batchLimit: 0, maxDepth: 0, graphiql: false, restrictToLoggedIn: true); + + expect($policy->forced())->toBe([ + 'batch_queries_enabled' => 'off', + 'query_depth_enabled' => 'off', + 'graphiql_enabled' => 'off', + 'restrict_endpoint_to_logged_in_users' => 'on', + ]) + ->and((new GraphQlPolicy(null, null, null, null))->forced())->toBe([]); +}); + +it('resolves a setting only in the general section', function (): void { + $policy = new GraphQlPolicy; + + expect($policy->resolve('graphql_general_settings', 'public_introspection_enabled', 'on'))->toBe('off') + ->and($policy->resolve('graphql_general_settings', 'graphql_endpoint', 'api'))->toBe('api') + ->and($policy->resolve('another_section', 'public_introspection_enabled', 'on'))->toBe('on'); +}); + +it('reads the graphql section of the settings', function (): void { + $default = Settings::fromArray([], 'https://cms.example.com'); + $custom = Settings::fromArray(['graphql' => ['introspection' => true, 'batch_limit' => '3', 'max_depth' => null, 'graphiql' => false]], 'https://cms.example.com'); + $off = Settings::fromArray(['graphql' => ['enabled' => false]], 'https://cms.example.com'); + + expect($default->graphql)->toEqual(new GraphQlPolicy) + ->and($custom->graphql)->toEqual(new GraphQlPolicy(introspection: true, batchLimit: 3, maxDepth: null, graphiql: false)) + ->and($off->graphql)->toBeNull(); +}); + +it('is one of the modules', function (): void { + $modules = Bootstrap::modules(Settings::fromArray(['tokens' => ['enabled' => true]], 'https://cms.example.com')); + + expect(array_filter($modules, static fn ($module): bool => $module instanceof GraphQl))->toHaveCount(1); +}); + +it('hooks the settings, the headers and the guard', function (): void { + Filters\expectAdded('graphql_get_setting_section_field_value')->once()->with(Mockery::type('array'), 20, 5); + Filters\expectAdded('graphql_response_headers_to_send')->once()->with(Mockery::type('array'), 20); + Filters\expectAdded('graphql_pre_resolve_field')->once()->with(Mockery::type('array'), 5, 6); + + (new GraphQl(new GraphQlPolicy, new CorsPolicy(['https://www.example.com']), new TokenAuthentication(new TokenService(new InMemoryTokenStore))))->register(new WordPressHooks); +}); + +it('hooks only the settings without CORS or tokens', function (): void { + Filters\expectAdded('graphql_get_setting_section_field_value')->once(); + Filters\expectAdded('graphql_response_headers_to_send')->never(); + Filters\expectAdded('graphql_pre_resolve_field')->never(); + + (new GraphQl(new GraphQlPolicy))->register(new WordPressHooks); +}); + +it('imposes a setting', function (): void { + $module = new GraphQl(new GraphQlPolicy); + + expect($module->setting('on', 'off', 'public_introspection_enabled', [], 'graphql_general_settings'))->toBe('off'); +}); + +it('replaces the wildcard origin with the policy', function (): void { + $_SERVER['HTTP_ORIGIN'] = 'https://www.example.com'; + $module = new GraphQl(new GraphQlPolicy, new CorsPolicy(['https://www.example.com'])); + + $headers = $module->headers([ + 'Access-Control-Allow-Origin' => '*', + 'Access-Control-Allow-Headers' => 'Authorization, Content-Type', + 'Access-Control-Max-Age' => '600', + 'Content-Type' => 'application/json', + 'Vary' => 'X-GraphQL-Preview', + ]); + + expect($headers['Access-Control-Allow-Origin'])->toBe('https://www.example.com') + ->and($headers['Vary'])->toBe('X-GraphQL-Preview, Origin') + ->and($headers['Content-Type'])->toBe('application/json') + ->and($headers)->not->toHaveKey('Access-Control-Allow-Headers'); +}); + +it('answers a preflight with the headers a client may send, including the preview one', function (): void { + $_SERVER['HTTP_ORIGIN'] = 'https://www.example.com'; + $_SERVER['REQUEST_METHOD'] = 'OPTIONS'; + $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] = 'POST'; + $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] = 'content-type, x-graphql-preview'; + + $headers = (new GraphQl(new GraphQlPolicy, new CorsPolicy(['https://www.example.com'])))->headers(['Access-Control-Allow-Origin' => '*']); + + expect($headers['Access-Control-Allow-Headers'])->toBe('content-type, x-graphql-preview') + ->and($headers['Vary'])->toBe('Origin'); +}); + +it('gives no origin to a site that is not listed', function (): void { + $_SERVER['HTTP_ORIGIN'] = 'https://evil.example.net'; + + $headers = (new GraphQl(new GraphQlPolicy, new CorsPolicy(['https://www.example.com'])))->headers(['Access-Control-Allow-Origin' => '*']); + + expect($headers)->not->toHaveKey('Access-Control-Allow-Origin')->and($headers['Vary'])->toBe('Origin'); +}); + +it('leaves the headers alone without a CORS policy', function (): void { + expect((new GraphQl(new GraphQlPolicy))->headers(['Access-Control-Allow-Origin' => '*']))->toBe(['Access-Control-Allow-Origin' => '*']); +}); + +/** + * @param list $scopes + * @param list $routes + */ +function graphQlGuard(array $scopes, array $routes = []): GraphQl +{ + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer hl.7.0123456789ab.'.str_repeat('A', 43); + $service = new TokenService(new InMemoryTokenStore); + $auth = new TokenAuthentication($service, fn (): bool => true); + + $token = new Token('0123456789ab', 7, 'next', 'hash', $scopes, $routes, 1); + (new ReflectionProperty($auth, 'token'))->setValue($auth, $token); + + return new GraphQl(new GraphQlPolicy, null, $auth); +} + +it('lets a read token run queries and refuses its mutations', function (): void { + $guard = graphQlGuard([TokenScope::Read]); + + expect($guard->guard(null, null, [], null, null, 'RootQuery'))->toBeNull(); + $guard->guard(null, null, [], null, null, 'RootMutation'); +})->throws(UserError::class); + +it('lets a write token run mutations', function (): void { + expect(graphQlGuard([TokenScope::Write])->guard(null, null, [], null, null, 'RootMutation'))->toBeNull(); +}); + +it('refuses a token limited to other routes', function (): void { + graphQlGuard([TokenScope::Read], ['/wp/v2'])->guard(null, null, [], null, null, 'RootQuery'); +})->throws(UserError::class); + +it('accepts a token limited to the graphql route', function (): void { + expect(graphQlGuard([TokenScope::Read], ['/graphql'])->guard('x', null, [], null, null, 'RootQuery'))->toBe('x'); +}); + +it('ignores fields that are not at the root, and requests without a token', function (): void { + $withToken = graphQlGuard([TokenScope::Read]); + $without = new GraphQl(new GraphQlPolicy, null, new TokenAuthentication(new TokenService(new InMemoryTokenStore), fn (): bool => true)); + + expect($withToken->guard(null, null, [], null, null, 'Post'))->toBeNull() + ->and($without->guard(null, null, [], null, null, 'RootMutation'))->toBeNull(); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 8b1489a..4b40a1d 100644 --- a/tests/Unit/Infrastructure/ModulesTest.php +++ b/tests/Unit/Infrastructure/ModulesTest.php @@ -120,7 +120,7 @@ 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(15); + expect(Bootstrap::modules($settings))->toHaveCount(16); Actions\expectAdded('template_redirect')->once(); Actions\expectAdded('rest_api_init')->times(7); @@ -141,7 +141,7 @@ function gateFor(FrontMode $mode, array &$ended): TemplateRedirectGate it('hooks no gate when the front is left as it is', function (): void { $settings = Settings::fromArray([], 'https://cms.example.com'); - expect(Bootstrap::modules($settings))->toHaveCount(4); + expect(Bootstrap::modules($settings))->toHaveCount(5); Actions\expectAdded('template_redirect')->never(); Actions\expectAdded('rest_api_init')->never(); From 2e3fa25cd321349bbaa00bcb16b79f5b6cc85166 Mon Sep 17 00:00:00 2001 From: Olivier Gorzalka Date: Tue, 24 Nov 2026 17:54:49 +0100 Subject: [PATCH 2/6] test(graphql): integration tests against a real WPGraphQL --- .github/workflows/harness.yml | 2 +- tests/Integration/GraphQlTest.php | 131 ++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 tests/Integration/GraphQlTest.php diff --git a/.github/workflows/harness.yml b/.github/workflows/harness.yml index 68ca0e3..e6ff2b3 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-seo + wordpress-plugins: polylang,action-scheduler,wordpress-seo,wp-graphql permissions: contents: read diff --git a/tests/Integration/GraphQlTest.php b/tests/Integration/GraphQlTest.php new file mode 100644 index 0000000..315317c --- /dev/null +++ b/tests/Integration/GraphQlTest.php @@ -0,0 +1,131 @@ + true) : null; + + if ($auth instanceof TokenAuthentication) { + $auth->register(new WordPressHooks); + } + + (new GraphQl($policy, new CorsPolicy(['https://www.example.com']), $auth))->register(new WordPressHooks); + + return $auth; +} + +/** + * @return array + */ +function runGraphQl(string $query): array +{ + return graphql(['query' => $query]); +} + +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('graphql_general_settings'); + unset($_SERVER['HTTP_ORIGIN'], $_SERVER['HTTP_AUTHORIZATION']); + wp_set_current_user(0); +}); + +it('runs against a real WPGraphQL', function (): void { + expect(function_exists('graphql'))->toBeTrue(); +}); + +it('imposes its settings over the ones in the database', function (): void { + update_option('graphql_general_settings', ['public_introspection_enabled' => 'on', 'debug_mode_enabled' => 'on', 'batch_limit' => 50]); + graphQlSite(); + + expect(get_graphql_setting('public_introspection_enabled'))->toBe('off') + ->and(get_graphql_setting('debug_mode_enabled'))->toBe('off') + ->and((int) get_graphql_setting('batch_limit'))->toBe(5) + ->and(get_graphql_setting('graphql_endpoint', 'graphql'))->toBe('graphql'); +}); + +it('closes introspection to visitors and keeps it for a logged-in user', function (): void { + graphQlSite(); + $query = '{ __schema { queryType { name } } }'; + + $visitor = runGraphQl($query); + wp_set_current_user(1); + $admin = runGraphQl($query); + + expect($visitor['errors'][0]['message'] ?? '')->toContain('ntrospection') + ->and($admin['data']['__schema']['queryType']['name'] ?? null)->toBe('RootQuery'); +}); + +it('refuses a query deeper than the limit', function (): void { + graphQlSite(new GraphQlPolicy(maxDepth: 2)); + + $result = runGraphQl('{ posts { nodes { author { node { name } } } } }'); + + expect($result['errors'][0]['message'] ?? '')->toContain('depth'); +}); + +it('answers with the CORS policy instead of the wildcard', function (): void { + graphQlSite(); + $_SERVER['HTTP_ORIGIN'] = 'https://www.example.com'; + + $allowed = apply_filters('graphql_response_headers_to_send', ['Access-Control-Allow-Origin' => '*', 'Vary' => 'X-GraphQL-Preview']); + $_SERVER['HTTP_ORIGIN'] = 'https://evil.example.net'; + $refused = apply_filters('graphql_response_headers_to_send', ['Access-Control-Allow-Origin' => '*']); + + expect($allowed['Access-Control-Allow-Origin'])->toBe('https://www.example.com') + ->and($allowed['Vary'])->toContain('Origin') + ->and($refused)->not->toHaveKey('Access-Control-Allow-Origin'); +}); + +it('logs an API token in on GraphQL and keeps a read token from running a mutation', function (): void { + $auth = graphQlSite(tokens: true); + $service = new TokenService(new UserMetaTokenStore); + $read = $service->create(1, 'read', [TokenScope::Read], [], null); + $write = $service->create(1, 'write', [TokenScope::Write], [], null); + + $mutation = 'mutation { createPost(input: { title: "From a token", status: DRAFT }) { post { databaseId } } }'; + $created = []; + + foreach ([$read, $write] as $issued) { + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer '.$issued->secret; + wp_set_current_user(0); + wp_set_current_user((int) $auth->authenticate(false)); + $viewer = runGraphQl('{ viewer { databaseId } }'); + $result = runGraphQl($mutation); + $created[] = [$viewer['data']['viewer']['databaseId'] ?? null, $result]; + } + + foreach (get_posts(['post_status' => 'draft', 'title' => 'From a token', 'numberposts' => -1]) as $post) { + wp_delete_post($post->ID, true); + } + $service->revoke(1, $read->token->id); + $service->revoke(1, $write->token->id); + + expect($created[0][0])->toBe(1) + ->and($created[0][1]['errors'][0]['message'] ?? '')->toContain('not allowed') + ->and($created[1][1]['data']['createPost']['post']['databaseId'] ?? null)->not->toBeNull(); +}); From 03401a854fcb158e70f70d789af65a0ddfcaa2b1 Mon Sep 17 00:00:00 2001 From: Olivier Gorzalka Date: Tue, 24 Nov 2026 18:01:17 +0100 Subject: [PATCH 3/6] feat(schema): wp headless schema openapi|graphql --- composer-dependency-analyser.php | 2 +- src/Domain/Schema/OpenApiBuilder.php | 227 +++++++++++++++++++++ src/Infrastructure/WpCli/SchemaCommand.php | 113 ++++++++++ src/Infrastructure/WpCli/register.php | 16 ++ tests/Integration/GraphQlTest.php | 17 ++ tests/Unit/OpenApiBuilderTest.php | 85 ++++++++ tests/Unit/SchemaCommandTest.php | 107 ++++++++++ 7 files changed, 566 insertions(+), 1 deletion(-) create mode 100644 src/Domain/Schema/OpenApiBuilder.php create mode 100644 src/Infrastructure/WpCli/SchemaCommand.php create mode 100644 tests/Unit/OpenApiBuilderTest.php create mode 100644 tests/Unit/SchemaCommandTest.php diff --git a/composer-dependency-analyser.php b/composer-dependency-analyser.php index 2eeee4b..db1d2ce 100644 --- a/composer-dependency-analyser.php +++ b/composer-dependency-analyser.php @@ -18,7 +18,7 @@ ->disableReportingUnmatchedIgnores() ->ignoreUnknownClassesRegex('~^(WP_|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']) + ->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]) diff --git a/src/Domain/Schema/OpenApiBuilder.php b/src/Domain/Schema/OpenApiBuilder.php new file mode 100644 index 0000000..43a486a --- /dev/null +++ b/src/Domain/Schema/OpenApiBuilder.php @@ -0,0 +1,227 @@ +get_routes()` returns, so that it needs no WordPress function: + * each route is a pattern with named groups, and each of its endpoints lists its methods and its arguments. + * The result is meant for a client generator, not for a reader: every answer is a plain `200`, since + * WordPress does not describe what an endpoint returns outside of the schema of its resources. + * + * @phpstan-type Endpoint array{methods?: array|string, args?: mixed} + */ +final readonly class OpenApiBuilder +{ + private const array METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']; + + /** + * @param list $namespaces the namespaces to keep, such as `wp/v2`; none keeps every one + */ + public function __construct( + private string $title, + private string $version, + private string $server, + private array $namespaces = [], + ) {} + + /** + * @param array>> $routes the route patterns and their endpoints + * @return array + */ + public function build(array $routes): array + { + $paths = []; + + foreach ($routes as $pattern => $endpoints) { + $path = self::path($pattern); + + if (! $this->wanted($path)) { + continue; + } + + $names = self::pathParameters($pattern); + + foreach ($endpoints as $endpoint) { + foreach (self::methods($endpoint['methods'] ?? []) as $method) { + $paths[$path][strtolower($method)] = $this->operation($method, $path, $names, self::args($endpoint['args'] ?? [])); + } + } + } + + ksort($paths); + + return [ + 'openapi' => '3.0.3', + 'info' => ['title' => $this->title, 'version' => $this->version], + 'servers' => [['url' => rtrim($this->server, '/')]], + 'paths' => $paths, + 'components' => ['securitySchemes' => ['bearer' => ['type' => 'http', 'scheme' => 'bearer', 'description' => 'An API token of the site (hl.…), or an application password with Basic authentication.']]], + ]; + } + + /** + * `/wp/v2/posts/(?P[\d]+)` becomes `/wp/v2/posts/{id}`. + */ + public static function path(string $pattern): string + { + $path = preg_replace('/\(\?P<(\w+)>(?:[^()]|\([^()]*\))*\)/', '{$1}', $pattern) ?? $pattern; + + return '/'.trim($path, '/'); + } + + /** + * @return list + */ + private static function pathParameters(string $pattern): array + { + preg_match_all('/\(\?P<(\w+)>/', $pattern, $matches); + + return array_values(array_unique($matches[1])); + } + + private function wanted(string $path): bool + { + if ($path === '/') { + return false; + } + + if ($this->namespaces === []) { + return true; + } + + foreach ($this->namespaces as $namespace) { + $namespace = '/'.trim($namespace, '/'); + + if ($path === $namespace || str_starts_with($path, $namespace.'/')) { + return true; + } + } + + return false; + } + + /** + * @return list + */ + private static function methods(mixed $methods): array + { + $names = is_array($methods) ? array_keys(array_filter($methods)) : explode(',', (string) $methods); + $names = array_map(static fn (mixed $name): string => strtoupper(trim((string) $name)), $names); + + return array_values(array_intersect(self::METHODS, $names)); + } + + /** + * @return array> + */ + private static function args(mixed $args): array + { + if (! is_array($args)) { + return []; + } + + return array_filter($args, static fn (mixed $arg, mixed $name): bool => is_string($name) && is_array($arg), ARRAY_FILTER_USE_BOTH); + } + + /** + * @param list $pathNames + * @param array> $args + * @return array + */ + private function operation(string $method, string $path, array $pathNames, array $args): array + { + $parameters = []; + $body = []; + $required = []; + + foreach ($pathNames as $name) { + $parameters[] = ['name' => $name, 'in' => 'path', 'required' => true, 'schema' => self::schema($args[$name] ?? [])]; + } + + foreach ($args as $name => $arg) { + if (in_array($name, $pathNames, true)) { + continue; + } + + if (in_array($method, ['GET', 'DELETE'], true)) { + $parameters[] = array_filter([ + 'name' => $name, + 'in' => 'query', + 'required' => ($arg['required'] ?? false) === true ? true : null, + 'description' => is_string($arg['description'] ?? null) ? $arg['description'] : null, + 'schema' => self::schema($arg), + ], static fn (mixed $value): bool => $value !== null); + + continue; + } + + $body[$name] = self::schema($arg) + (is_string($arg['description'] ?? null) ? ['description' => $arg['description']] : []); + + if (($arg['required'] ?? false) === true) { + $required[] = $name; + } + } + + $operation = [ + 'operationId' => self::operationId($method, $path), + 'tags' => [self::tag($path)], + 'responses' => ['200' => ['description' => 'OK']], + ]; + + if ($parameters !== []) { + $operation['parameters'] = $parameters; + } + + if ($body !== []) { + $operation['requestBody'] = ['content' => ['application/json' => ['schema' => array_filter(['type' => 'object', 'properties' => $body, 'required' => $required], static fn (mixed $value): bool => $value !== [])]]]; + } + + return $operation; + } + + /** + * The JSON schema of an argument: its type, and the limits WordPress states. + * + * @param array $arg + * @return array + */ + private static function schema(array $arg): array + { + $type = $arg['type'] ?? 'string'; + $type = is_array($type) ? (array_values(array_diff($type, ['null']))[0] ?? 'string') : $type; + $type = is_string($type) && in_array($type, ['string', 'integer', 'number', 'boolean', 'array', 'object'], true) ? $type : 'string'; + + $schema = ['type' => $type]; + + if ($type === 'array') { + $items = is_array($arg['items'] ?? null) ? $arg['items'] : []; + $schema['items'] = self::schema($items); + } + + foreach (['enum', 'default', 'minimum', 'maximum', 'format', 'minLength', 'maxLength'] as $key) { + if (array_key_exists($key, $arg) && $arg[$key] !== null) { + $schema[$key] = $arg[$key]; + } + } + + return $schema; + } + + private static function operationId(string $method, string $path): string + { + $words = preg_split('/[^A-Za-z0-9]+/', $path, -1, PREG_SPLIT_NO_EMPTY) ?: []; + + return strtolower($method).implode('', array_map(ucfirst(...), $words)); + } + + private static function tag(string $path): string + { + $parts = explode('/', trim($path, '/')); + + return implode('/', array_slice($parts, 0, 2)); + } +} diff --git a/src/Infrastructure/WpCli/SchemaCommand.php b/src/Infrastructure/WpCli/SchemaCommand.php new file mode 100644 index 0000000..e1b8ccd --- /dev/null +++ b/src/Infrastructure/WpCli/SchemaCommand.php @@ -0,0 +1,113 @@ +>> $routes the REST routes of the site + * @param Closure(): array{title: string, version: string, server: string} $site what the OpenAPI document says of the site + * @param Closure(): ?string $graphql the GraphQL schema as SDL, or null when WPGraphQL is not active + * @param Closure(string, string): bool $write saves a file; replaced in tests + */ + public function __construct( + private Closure $routes, + private Closure $site, + private Closure $graphql, + private Output $output, + private Closure $write, + ) {} + + /** + * The REST API as an OpenAPI 3.0 document (JSON). + * + * ## OPTIONS + * + * [--namespace=] + * : Comma-separated REST namespaces to keep, such as wp/v2,headless/v1. Every namespace by default. + * + * [--file=] + * : Write to this file instead of printing. + * + * ## EXAMPLES + * + * wp headless schema openapi --namespace=wp/v2,headless/v1 --file=openapi.json + * + * @param list $args + * @param array $assoc + */ + public function openapi(array $args = [], array $assoc = []): void + { + $namespaces = array_values(array_filter(array_map(trim(...), explode(',', (string) ($assoc['namespace'] ?? ''))), static fn (string $namespace): bool => $namespace !== '')); + $site = ($this->site)(); + + $document = (new OpenApiBuilder($site['title'], $site['version'], $site['server'], $namespaces))->build(($this->routes)()); + + $this->emit(json_encode($document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)."\n", $assoc, sprintf('%d paths', count($document['paths']))); + } + + /** + * The GraphQL schema as SDL. Needs WPGraphQL. + * + * ## OPTIONS + * + * [--file=] + * : Write to this file instead of printing. + * + * ## EXAMPLES + * + * wp headless schema graphql --file=schema.graphql + * + * @param list $args + * @param array $assoc + */ + public function graphql(array $args = [], array $assoc = []): void + { + try { + $schema = ($this->graphql)(); + } catch (Throwable $throwable) { + $this->output->error('The GraphQL schema could not be printed: '.$throwable->getMessage()); + + return; + } + + if ($schema === null) { + $this->output->error('WPGraphQL is not active.'); + + return; + } + + $this->emit($schema."\n", $assoc, 'the GraphQL schema'); + } + + /** + * @param array $assoc + */ + private function emit(string $content, array $assoc, string $what): void + { + $file = $assoc['file'] ?? null; + + if (! is_string($file) || $file === '') { + $this->output->line(rtrim($content)); + + return; + } + + if (! ($this->write)($file, $content)) { + $this->output->error(sprintf('%s could not be written.', $file)); + + return; + } + + $this->output->success(sprintf('%s written to %s.', ucfirst($what), $file)); + } +} diff --git a/src/Infrastructure/WpCli/register.php b/src/Infrastructure/WpCli/register.php index 7a95e92..bceca82 100644 --- a/src/Infrastructure/WpCli/register.php +++ b/src/Infrastructure/WpCli/register.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use GraphQL\Utils\SchemaPrinter; use Pollora\Headless\Application\Revalidation\Revalidator; use Pollora\Headless\Application\Token\TokenService; use Pollora\Headless\Domain\Front\UrlMapper; @@ -20,6 +21,7 @@ use Pollora\Headless\Infrastructure\WpCli\HeadlessCommand; use Pollora\Headless\Infrastructure\WpCli\RedirectCommand; use Pollora\Headless\Infrastructure\WpCli\RevalidateCommand; +use Pollora\Headless\Infrastructure\WpCli\SchemaCommand; use Pollora\Headless\Infrastructure\WpCli\TokenCommand; use Pollora\Headless\Infrastructure\WpCli\WpCliOutput; @@ -73,6 +75,20 @@ static function (string $who): ?int { static fn (): int => time(), new WpCliOutput, )); + + WP_CLI::add_command('headless schema', new SchemaCommand( + static fn (): array => rest_get_server()->get_routes(), + static fn (): array => ['title' => (string) get_bloginfo('name'), 'version' => (string) get_bloginfo('version'), 'server' => rest_url()], + static function (): ?string { + if (! class_exists('WPGraphQL') || ! class_exists('GraphQL\\Utils\\SchemaPrinter')) { + return null; + } + + return SchemaPrinter::doPrint(WPGraphQL::get_schema()); + }, + new WpCliOutput, + static fn (string $file, string $content): bool => file_put_contents($file, $content) !== false, + )); } // @codeCoverageIgnoreEnd diff --git a/tests/Integration/GraphQlTest.php b/tests/Integration/GraphQlTest.php index 315317c..0fedafb 100644 --- a/tests/Integration/GraphQlTest.php +++ b/tests/Integration/GraphQlTest.php @@ -2,9 +2,11 @@ declare(strict_types=1); +use GraphQL\Utils\SchemaPrinter; use Pollora\Headless\Application\Token\TokenService; use Pollora\Headless\Domain\Cors\CorsPolicy; use Pollora\Headless\Domain\GraphQl\GraphQlPolicy; +use Pollora\Headless\Domain\Schema\OpenApiBuilder; use Pollora\Headless\Domain\Token\TokenScope; use Pollora\Headless\Infrastructure\WordPress\GraphQl; use Pollora\Headless\Infrastructure\WordPress\TokenAuthentication; @@ -129,3 +131,18 @@ function runGraphQl(string $query): array ->and($created[0][1]['errors'][0]['message'] ?? '')->toContain('not allowed') ->and($created[1][1]['data']['createPost']['post']['databaseId'] ?? null)->not->toBeNull(); }); + +it('describes the real REST API as an OpenAPI document', function (): void { + $document = (new OpenApiBuilder('Site', '1', rest_url(), ['wp/v2']))->build(rest_get_server()->get_routes()); + + expect($document['paths'])->toHaveKey('/wp/v2/posts/{id}') + ->and($document['paths']['/wp/v2/posts']['get']['parameters'])->not->toBeEmpty() + ->and($document['paths']['/wp/v2/posts']['post']['requestBody'])->toHaveKey('content') + ->and(json_encode($document))->toBeString(); +}); + +it('prints the real GraphQL schema as SDL', function (): void { + $sdl = SchemaPrinter::doPrint(WPGraphQL::get_schema()); + + expect($sdl)->toContain('type RootQuery')->and($sdl)->toContain('type Post '); +}); diff --git a/tests/Unit/OpenApiBuilderTest.php b/tests/Unit/OpenApiBuilderTest.php new file mode 100644 index 0000000..bd03d9a --- /dev/null +++ b/tests/Unit/OpenApiBuilderTest.php @@ -0,0 +1,85 @@ +>> + */ +function wordPressRoutes(): array +{ + return [ + '/' => [['methods' => ['GET' => true], 'args' => ['context' => ['type' => 'string']]]], + '/wp/v2/posts' => [ + ['methods' => ['GET' => true], 'args' => ['per_page' => ['type' => 'integer', 'default' => 10, 'minimum' => 1, 'maximum' => 100, 'description' => 'How many.'], 'status' => ['type' => ['string', 'null'], 'enum' => ['publish', 'draft']]]], + ['methods' => ['POST' => true], 'args' => ['title' => ['type' => 'string', 'required' => true, 'description' => 'The title.'], 'categories' => ['type' => 'array', 'items' => ['type' => 'integer']]]], + ], + '/wp/v2/posts/(?P[\d]+)' => [ + ['methods' => ['GET' => true, 'HEAD' => true], 'args' => ['id' => ['type' => 'integer', 'description' => 'Unique identifier.'], 'context' => ['type' => 'string', 'enum' => ['view', 'edit']]]], + ['methods' => ['PUT' => true, 'PATCH' => true], 'args' => ['id' => ['type' => 'integer']]], + ['methods' => ['DELETE' => true], 'args' => ['force' => ['type' => 'boolean', 'default' => false]]], + ], + '/headless/v1/site' => [['methods' => 'GET', 'args' => []]], + '/oembed/1.0/embed' => [['methods' => ['GET' => true], 'args' => ['url' => ['type' => 'string', 'format' => 'uri', 'required' => true]]]], + ]; +} + +it('turns a route pattern into an OpenAPI path', function (): void { + expect(OpenApiBuilder::path('/wp/v2/posts/(?P[\d]+)'))->toBe('/wp/v2/posts/{id}') + ->and(OpenApiBuilder::path('/wp/v2/(?P[\d]+)/revisions/(?P[\d]+)'))->toBe('/wp/v2/{parent}/revisions/{id}') + ->and(OpenApiBuilder::path('/headless/v1/site'))->toBe('/headless/v1/site') + ->and(OpenApiBuilder::path('/x/(?P(?:a|b)+)'))->toBe('/x/{slug}'); +}); + +it('builds a document with every route but the index', function (): void { + $document = (new OpenApiBuilder('The site', '1.0', 'https://cms.example.com/wp-json/'))->build(wordPressRoutes()); + + expect($document['openapi'])->toBe('3.0.3') + ->and($document['info'])->toBe(['title' => 'The site', 'version' => '1.0']) + ->and($document['servers'])->toBe([['url' => 'https://cms.example.com/wp-json']]) + ->and(array_keys($document['paths']))->toBe(['/headless/v1/site', '/oembed/1.0/embed', '/wp/v2/posts', '/wp/v2/posts/{id}']) + ->and($document['components']['securitySchemes']['bearer']['scheme'])->toBe('bearer'); +}); + +it('keeps only the namespaces asked for', function (): void { + $document = (new OpenApiBuilder('t', '1', 'https://x.test', ['wp/v2', '/headless/v1/']))->build(wordPressRoutes()); + + expect(array_keys($document['paths']))->toBe(['/headless/v1/site', '/wp/v2/posts', '/wp/v2/posts/{id}']); +}); + +it('describes the query of a read and the body of a write', function (): void { + $paths = (new OpenApiBuilder('t', '1', 'https://x.test'))->build(wordPressRoutes())['paths']; + + $list = $paths['/wp/v2/posts']['get']; + $create = $paths['/wp/v2/posts']['post']; + + expect($list['operationId'])->toBe('getWpV2Posts') + ->and($list['tags'])->toBe(['wp/v2']) + ->and($list['parameters'][0])->toBe(['name' => 'per_page', 'in' => 'query', 'description' => 'How many.', 'schema' => ['type' => 'integer', 'default' => 10, 'minimum' => 1, 'maximum' => 100]]) + ->and($list['parameters'][1]['schema'])->toBe(['type' => 'string', 'enum' => ['publish', 'draft']]) + ->and($create)->not->toHaveKey('parameters') + ->and($create['requestBody']['content']['application/json']['schema'])->toBe([ + 'type' => 'object', + 'properties' => ['title' => ['type' => 'string', 'description' => 'The title.'], 'categories' => ['type' => 'array', 'items' => ['type' => 'integer']]], + 'required' => ['title'], + ]); +}); + +it('makes the path parameters required, one operation per method, and skips HEAD', function (): void { + $item = (new OpenApiBuilder('t', '1', 'https://x.test'))->build(wordPressRoutes())['paths']['/wp/v2/posts/{id}']; + + expect(array_keys($item))->toBe(['get', 'put', 'patch', 'delete']) + ->and($item['get']['parameters'][0])->toBe(['name' => 'id', 'in' => 'path', 'required' => true, 'schema' => ['type' => 'integer']]) + ->and($item['get']['parameters'][1]['name'])->toBe('context') + ->and($item['delete']['parameters'][1] ?? $item['delete']['parameters'][0])->toHaveKey('schema') + ->and($item['put']['parameters'])->toHaveCount(1); +}); + +it('reads methods given as a string, and tolerates an odd endpoint', function (): void { + $document = (new OpenApiBuilder('t', '1', 'https://x.test'))->build([ + '/a/v1/x' => [['methods' => 'GET, POST', 'args' => 'nope'], ['methods' => 12, 'args' => ['skipped' => 'not an array', 7 => ['type' => 'string']]]], + ]); + + expect(array_keys($document['paths']['/a/v1/x']))->toBe(['get', 'post']); +}); diff --git a/tests/Unit/SchemaCommandTest.php b/tests/Unit/SchemaCommandTest.php new file mode 100644 index 0000000..da22587 --- /dev/null +++ b/tests/Unit/SchemaCommandTest.php @@ -0,0 +1,107 @@ + */ + 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; + } + }; +} + +/** + * @param list $written + */ +function schemaCommand(Output $output, ?Closure $graphql = null, array &$written = [], bool $writable = true): SchemaCommand +{ + return new SchemaCommand( + static fn (): array => ['/wp/v2/posts' => [['methods' => ['GET' => true], 'args' => []]], '/headless/v1/site' => [['methods' => ['GET' => true], 'args' => []]]], + static fn (): array => ['title' => 'Site', 'version' => '6.9', 'server' => 'https://cms.example.com/wp-json/'], + $graphql ?? static fn (): ?string => null, + $output, + function (string $file, string $content) use (&$written, $writable): bool { + $written[] = [$file, $content]; + + return $writable; + }, + ); +} + +it('prints the OpenAPI document', function (): void { + $output = schemaOutput(); + + schemaCommand($output)->openapi(); + $document = json_decode(substr($output->messages[0], 6), true); + + expect($document['info']['title'])->toBe('Site')->and(array_keys($document['paths']))->toBe(['/headless/v1/site', '/wp/v2/posts']); +}); + +it('keeps the namespaces asked for and writes to a file', function (): void { + $output = schemaOutput(); + $written = []; + + schemaCommand($output, null, $written)->openapi([], ['namespace' => 'wp/v2, ', 'file' => 'openapi.json']); + + expect($written[0][0])->toBe('openapi.json') + ->and(array_keys(json_decode($written[0][1], true)['paths']))->toBe(['/wp/v2/posts']) + ->and($output->messages)->toBe(['success: 1 paths written to openapi.json.']); +}); + +it('says when a file cannot be written', function (): void { + $output = schemaOutput(); + $written = []; + + schemaCommand($output, null, $written, false)->openapi([], ['file' => '/nope/openapi.json']); + + expect($output->messages)->toBe(['error: /nope/openapi.json could not be written.']); +}); + +it('prints and writes the GraphQL schema', function (): void { + $output = schemaOutput(); + $written = []; + $command = schemaCommand($output, static fn (): string => 'type Query { a: String }', $written); + + $command->graphql(); + $command->graphql([], ['file' => 'schema.graphql']); + + expect($output->messages)->toBe(['line: type Query { a: String }', 'success: The GraphQL schema written to schema.graphql.']) + ->and($written)->toBe([['schema.graphql', "type Query { a: String }\n"]]); +}); + +it('says when WPGraphQL is missing or fails', function (): void { + $missing = schemaOutput(); + schemaCommand($missing)->graphql(); + + $broken = schemaOutput(); + schemaCommand($broken, static function (): string { + throw new RuntimeException('no schema'); + })->graphql(); + + expect($missing->messages)->toBe(['error: WPGraphQL is not active.']) + ->and($broken->messages)->toBe(['error: The GraphQL schema could not be printed: no schema']); +}); From 582b0a98ba26e48a12ad351255231552488d7f37 Mon Sep 17 00:00:00 2001 From: Olivier Gorzalka Date: Tue, 24 Nov 2026 18:05:36 +0100 Subject: [PATCH 4/6] feat(search): GET headless/v1/search in one stable shape --- config/headless.php | 7 + src/Domain/Search/SearchQuery.php | 54 +++++++ src/Infrastructure/Config/Settings.php | 2 + src/Infrastructure/WordPress/Bootstrap.php | 7 + src/Infrastructure/WordPress/SearchRoutes.php | 144 ++++++++++++++++++ tests/Integration/SearchTest.php | 103 +++++++++++++ tests/Unit/Infrastructure/ModulesTest.php | 4 +- tests/Unit/SearchQueryTest.php | 43 ++++++ 8 files changed, 362 insertions(+), 2 deletions(-) create mode 100644 src/Domain/Search/SearchQuery.php create mode 100644 src/Infrastructure/WordPress/SearchRoutes.php create mode 100644 tests/Integration/SearchTest.php create mode 100644 tests/Unit/SearchQueryTest.php diff --git a/config/headless.php b/config/headless.php index f7dec7d..42c98d8 100644 --- a/config/headless.php +++ b/config/headless.php @@ -167,4 +167,11 @@ '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, + ], ]; diff --git a/src/Domain/Search/SearchQuery.php b/src/Domain/Search/SearchQuery.php new file mode 100644 index 0000000..710fb1b --- /dev/null +++ b/src/Domain/Search/SearchQuery.php @@ -0,0 +1,54 @@ + $types the content types to look in: the ones asked for that the site exposes, or all of those it exposes + */ + private function __construct( + public string $term, + public array $types, + public ?string $language, + public int $page, + public int $perPage, + ) {} + + /** + * @param list $exposed the types the site exposes, so that a request cannot reach another one + * @param list $languages the language codes of the site, when it has languages + */ + public static function fromRequest(string $term, string $types, ?string $language, int $page, int $perPage, int $maxPerPage, array $exposed, array $languages = []): ?self + { + $term = trim((string) preg_replace('/\s+/u', ' ', $term)); + + if (mb_strlen($term) < self::MIN_LENGTH) { + return null; + } + + $asked = array_values(array_filter(array_map(trim(...), explode(',', $types)), static fn (string $type): bool => $type !== '')); + $kept = $asked === [] ? $exposed : array_values(array_intersect($asked, $exposed)); + $language = $language !== null && in_array($language, $languages, true) ? $language : null; + + return new self( + mb_substr($term, 0, self::MAX_LENGTH), + $kept, + $language, + max(1, $page), + min(max(1, $perPage > 0 ? $perPage : self::DEFAULT_PER_PAGE), max(1, $maxPerPage)), + ); + } +} diff --git a/src/Infrastructure/Config/Settings.php b/src/Infrastructure/Config/Settings.php index 790e6df..453a81a 100644 --- a/src/Infrastructure/Config/Settings.php +++ b/src/Infrastructure/Config/Settings.php @@ -68,6 +68,7 @@ private function __construct( public bool $blocks, public bool $seo, public ?GraphQlPolicy $graphql, + public bool $search, ) {} /** @@ -134,6 +135,7 @@ public static function fromArray(array $config, string $backendUrl): self blocks: $front instanceof Origin && self::bool(is_array($config['blocks'] ?? null) ? $config['blocks'] : [], 'enabled', true), seo: $front instanceof Origin && self::bool(is_array($config['seo'] ?? null) ? $config['seo'] : [], 'enabled', true), graphql: self::graphql($config['graphql'] ?? null), + search: $front instanceof Origin && self::bool(is_array($config['search'] ?? null) ? $config['search'] : [], 'enabled', true), ); } diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index df6ab95..ed4948a 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -126,6 +126,13 @@ public static function modules(Settings $settings, ?Languages $languages = null) $modules[] = new SeoField(SeoProviders::detect(), $seoUrls); } + if ($settings->search && $settings->urls instanceof UrlMapper && $settings->front instanceof Origin) { + $searchUrls = $languages->isActive() + ? new LanguageUrls($settings->urls, $settings->backend, $settings->front, $settings->languageFronts, $languages) + : $settings->urls; + $modules[] = new SearchRoutes($searchUrls, $languages, $settings->perPageMax ?? 50); + } + if ($settings->blocks) { $modules[] = new BlocksField; } diff --git a/src/Infrastructure/WordPress/SearchRoutes.php b/src/Infrastructure/WordPress/SearchRoutes.php new file mode 100644 index 0000000..54716ff --- /dev/null +++ b/src/Infrastructure/WordPress/SearchRoutes.php @@ -0,0 +1,144 @@ +addAction('rest_api_init', [$this, 'routes']); + } + + public function routes(): void + { + register_rest_route(ManifestRoutes::NAMESPACE, '/search', [ + 'methods' => 'GET', + 'callback' => [$this, 'search'], + // Public on purpose: it returns what the site search page returns + 'permission_callback' => '__return_true', + 'args' => [ + 'q' => ['type' => 'string', 'required' => true, 'description' => 'The words to search for (two characters at least).'], + 'type' => ['type' => 'string', 'description' => 'Comma-separated content types to look in; every public type by default.'], + 'lang' => ['type' => 'string', 'description' => 'A language code, when the site has languages.'], + 'page' => ['type' => 'integer', 'default' => 1, 'minimum' => 1], + 'per_page' => ['type' => 'integer', 'default' => SearchQuery::DEFAULT_PER_PAGE, 'minimum' => 1, 'description' => sprintf('Capped at %d.', $this->maxPerPage)], + ], + ]); + } + + /** + * @param \WP_REST_Request> $request + */ + public function search(\WP_REST_Request $request): \WP_REST_Response|\WP_Error + { + $query = SearchQuery::fromRequest( + (string) $request->get_param('q'), + (string) $request->get_param('type'), + is_string($request->get_param('lang')) ? $request->get_param('lang') : null, + (int) $request->get_param('page'), + (int) $request->get_param('per_page'), + $this->maxPerPage, + $this->exposedTypes(), + $this->languages->all(), + ); + + if (! $query instanceof SearchQuery) { + return new \WP_Error('headless_search_term', sprintf('Search for at least %d characters.', SearchQuery::MIN_LENGTH), ['status' => 400]); + } + + $args = [ + 's' => $query->term, + 'post_type' => $query->types === [] ? ['__none__'] : $query->types, + 'post_status' => 'publish', + 'has_password' => false, + 'posts_per_page' => $query->perPage, + 'paged' => $query->page, + 'ignore_sticky_posts' => true, + 'no_found_rows' => false, + ]; + + if ($query->language !== null) { + $args['lang'] = $query->language; + } + + $found = new \WP_Query(apply_filters('headless/search/args', $args, $query)); + $results = []; + + foreach ($found->posts as $post) { + if ($post instanceof \WP_Post) { + $results[] = $this->result($post); + } + } + + $total = (int) $found->found_posts; + $pages = (int) $found->max_num_pages; + + $response = new \WP_REST_Response([ + 'query' => $query->term, + 'page' => $query->page, + 'per_page' => $query->perPage, + 'total' => $total, + 'pages' => $pages, + 'results' => $results, + ]); + $response->header('X-WP-Total', (string) $total); + $response->header('X-WP-TotalPages', (string) $pages); + + return $response; + } + + /** + * @return array + */ + private function result(\WP_Post $post): array + { + $language = $this->languages->ofPost($post->ID); + $excerpt = wp_trim_words(wp_strip_all_tags($post->post_excerpt !== '' ? $post->post_excerpt : strip_shortcodes($post->post_content)), self::EXCERPT_WORDS); + $thumbnail = get_post_thumbnail_id($post); + + return [ + 'id' => $post->ID, + 'type' => $post->post_type, + 'title' => html_entity_decode(get_the_title($post), ENT_QUOTES, 'UTF-8'), + 'excerpt' => html_entity_decode($excerpt, ENT_QUOTES, 'UTF-8'), + 'url' => $this->urls->toFront((string) get_permalink($post), $language), + 'language' => $language, + 'date' => get_post_time('c', true, $post), + 'image' => $thumbnail > 0 ? (string) wp_get_attachment_url($thumbnail) : null, + ]; + } + + /** + * @return list + */ + private function exposedTypes(): array + { + $types = get_post_types(['public' => true, 'exclude_from_search' => false]); + unset($types['attachment']); + + return array_values(array_map(strval(...), $types)); + } +} diff --git a/tests/Integration/SearchTest.php b/tests/Integration/SearchTest.php new file mode 100644 index 0000000..93bc325 --- /dev/null +++ b/tests/Integration/SearchTest.php @@ -0,0 +1,103 @@ +register(new WordPressHooks); + + $GLOBALS['wp_rest_server'] = null; + rest_get_server(); +} + +function searchFor(string $query, array $params = []): WP_REST_Response +{ + $request = new WP_REST_Request('GET', '/headless/v1/search'); + $request->set_query_params(['q' => $query] + $params); + + return rest_do_request($request); +} + +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('finds published content and answers with a stable shape', function (): void { + searchServer(); + $post = wp_insert_post(['post_title' => 'Zebrafinch migration', 'post_content' => '

The zebrafinch flies far.

', 'post_status' => 'publish']); + $draft = wp_insert_post(['post_title' => 'Zebrafinch draft', 'post_status' => 'draft']); + $locked = wp_insert_post(['post_title' => 'Zebrafinch secret', 'post_status' => 'publish', 'post_password' => 'x']); + + $response = searchFor('zebrafinch'); + $data = $response->get_data(); + foreach ([$post, $draft, $locked] as $id) { + wp_delete_post($id, true); + } + + expect($response->get_status())->toBe(200) + ->and($data['total'])->toBe(1) + ->and($data['results'])->toHaveCount(1) + ->and(array_keys($data['results'][0]))->toBe(['id', 'type', 'title', 'excerpt', 'url', 'language', 'date', 'image']) + ->and($data['results'][0]['title'])->toBe('Zebrafinch migration') + ->and($data['results'][0]['excerpt'])->toBe('The zebrafinch flies far.') + ->and($data['results'][0]['url'])->toStartWith('https://www.example.com/') + ->and($data['results'][0]['language'])->toBeNull() + ->and($response->get_headers()['X-WP-Total'])->toBe('1'); +}); + +it('looks in the types asked for only', function (): void { + searchServer(); + $page = wp_insert_post(['post_title' => 'Quokka page', 'post_type' => 'page', 'post_status' => 'publish']); + $post = wp_insert_post(['post_title' => 'Quokka post', 'post_status' => 'publish']); + + $pages = searchFor('quokka', ['type' => 'page'])->get_data(); + $unknown = searchFor('quokka', ['type' => 'nothing'])->get_data(); + wp_delete_post($page, true); + wp_delete_post($post, true); + + expect(array_column($pages['results'], 'type'))->toBe(['page']) + ->and($unknown['total'])->toBe(0); +}); + +it('pages the results and caps their number', function (): void { + searchServer(2); + $ids = []; + foreach (range(1, 3) as $n) { + $ids[] = wp_insert_post(['post_title' => "Numbat $n", 'post_status' => 'publish']); + } + + $first = searchFor('numbat', ['per_page' => 50])->get_data(); + $second = searchFor('numbat', ['per_page' => 50, 'page' => 2])->get_data(); + array_map(static fn (int $id) => wp_delete_post($id, true), $ids); + + expect($first['per_page'])->toBe(2) + ->and($first['pages'])->toBe(2) + ->and($first['results'])->toHaveCount(2) + ->and($second['results'])->toHaveCount(1); +}); + +it('refuses a term that is too short', function (): void { + searchServer(); + + expect(searchFor('a')->get_status())->toBe(400)->and(searchFor('a')->get_data()['code'])->toBe('headless_search_term'); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 4b40a1d..3b2f52c 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(16); + expect(Bootstrap::modules($settings))->toHaveCount(17); Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->times(7); + Actions\expectAdded('rest_api_init')->times(8); Filters\expectAdded('preview_post_link')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('rest_post_dispatch')->once(); diff --git a/tests/Unit/SearchQueryTest.php b/tests/Unit/SearchQueryTest.php new file mode 100644 index 0000000..e207682 --- /dev/null +++ b/tests/Unit/SearchQueryTest.php @@ -0,0 +1,43 @@ +term)->toBe('hello world') + ->and(searchQuery('a'))->toBeNull() + ->and(searchQuery(' '))->toBeNull() + ->and(searchQuery('é'))->toBeNull() + ->and(mb_strlen(searchQuery(str_repeat('é', 300))?->term ?? ''))->toBe(SearchQuery::MAX_LENGTH); +}); + +it('looks in every exposed type unless some are named', function (): void { + expect(searchQuery()?->types)->toBe(['post', 'page', 'product']) + ->and(searchQuery(types: 'page, product')?->types)->toBe(['page', 'product']) + ->and(searchQuery(types: 'page,secret,')?->types)->toBe(['page']); +}); + +it('searches nowhere when every type asked for is unknown', function (): void { + expect(searchQuery(types: 'secret,hidden')?->types)->toBe([]); +}); + +it('keeps a language of the site only', function (): void { + expect(searchQuery(lang: 'fr')?->language)->toBe('fr') + ->and(searchQuery(lang: 'de')?->language)->toBeNull() + ->and(searchQuery()?->language)->toBeNull(); +}); + +it('bounds the page and its size', function (): void { + expect(searchQuery(page: -4)?->page)->toBe(1) + ->and(searchQuery(page: 3)?->page)->toBe(3) + ->and(searchQuery(perPage: 0)?->perPage)->toBe(SearchQuery::DEFAULT_PER_PAGE) + ->and(searchQuery(perPage: 500)?->perPage)->toBe(50) + ->and(searchQuery(perPage: 20, max: 5)?->perPage)->toBe(5) + ->and(searchQuery(perPage: 20, max: 0)?->perPage)->toBe(1); +}); From 9bf43b0d528426b4d52953f56418345fbfcb8a3f Mon Sep 17 00:00:00 2001 From: Olivier Gorzalka Date: Tue, 24 Nov 2026 18:09:17 +0100 Subject: [PATCH 5/6] wip(forms): Contact Form 7 adapter and form routes (one unit test to fix in ModulesTest) --- .github/workflows/harness.yml | 2 +- config/headless.php | 7 ++ src/Domain/Form/Form.php | 47 ++++++++ src/Domain/Form/FormField.php | 37 ++++++ src/Domain/Form/FormProvider.php | 21 ++++ src/Infrastructure/Config/Settings.php | 2 + .../Form/ContactForm7Provider.php | 99 +++++++++++++++ src/Infrastructure/WordPress/Bootstrap.php | 5 + src/Infrastructure/WordPress/FormRoutes.php | 86 +++++++++++++ tests/Integration/FormsTest.php | 98 +++++++++++++++ tests/Unit/FormTest.php | 113 ++++++++++++++++++ tests/Unit/Infrastructure/ModulesTest.php | 8 +- 12 files changed, 520 insertions(+), 5 deletions(-) create mode 100644 src/Domain/Form/Form.php create mode 100644 src/Domain/Form/FormField.php create mode 100644 src/Domain/Form/FormProvider.php create mode 100644 src/Infrastructure/Form/ContactForm7Provider.php create mode 100644 src/Infrastructure/WordPress/FormRoutes.php create mode 100644 tests/Integration/FormsTest.php create mode 100644 tests/Unit/FormTest.php diff --git a/.github/workflows/harness.yml b/.github/workflows/harness.yml index e6ff2b3..2408c29 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-seo,wp-graphql + wordpress-plugins: polylang,action-scheduler,wordpress-seo,wp-graphql,contact-form-7 permissions: contents: read diff --git a/config/headless.php b/config/headless.php index 42c98d8..abc1d79 100644 --- a/config/headless.php +++ b/config/headless.php @@ -174,4 +174,11 @@ '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, + ], ]; diff --git a/src/Domain/Form/Form.php b/src/Domain/Form/Form.php new file mode 100644 index 0000000..a7347f2 --- /dev/null +++ b/src/Domain/Form/Form.php @@ -0,0 +1,47 @@ + $fields + * @param array $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 + */ + public function summary(): array + { + return ['provider' => $this->provider, 'id' => $this->id, 'title' => $this->title]; + } + + /** + * @return array + */ + 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], + ]; + } +} diff --git a/src/Domain/Form/FormField.php b/src/Domain/Form/FormField.php new file mode 100644 index 0000000..007cfc4 --- /dev/null +++ b/src/Domain/Form/FormField.php @@ -0,0 +1,37 @@ + $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 + */ + public function toArray(): array + { + return [ + 'name' => $this->name, + 'type' => $this->type, + 'required' => $this->required, + 'multiple' => $this->multiple, + 'options' => $this->options, + ]; + } +} diff --git a/src/Domain/Form/FormProvider.php b/src/Domain/Form/FormProvider.php new file mode 100644 index 0000000..641ee64 --- /dev/null +++ b/src/Domain/Form/FormProvider.php @@ -0,0 +1,21 @@ + + */ + public function forms(): array; + + public function find(string $id): ?Form; +} diff --git a/src/Infrastructure/Config/Settings.php b/src/Infrastructure/Config/Settings.php index 453a81a..69310c9 100644 --- a/src/Infrastructure/Config/Settings.php +++ b/src/Infrastructure/Config/Settings.php @@ -69,6 +69,7 @@ private function __construct( public bool $seo, public ?GraphQlPolicy $graphql, public bool $search, + public bool $forms, ) {} /** @@ -136,6 +137,7 @@ public static function fromArray(array $config, string $backendUrl): self seo: $front instanceof Origin && self::bool(is_array($config['seo'] ?? null) ? $config['seo'] : [], 'enabled', true), graphql: self::graphql($config['graphql'] ?? null), search: $front instanceof Origin && self::bool(is_array($config['search'] ?? null) ? $config['search'] : [], 'enabled', true), + forms: self::bool(is_array($config['forms'] ?? null) ? $config['forms'] : [], 'enabled', true), ); } diff --git a/src/Infrastructure/Form/ContactForm7Provider.php b/src/Infrastructure/Form/ContactForm7Provider.php new file mode 100644 index 0000000..e547c4d --- /dev/null +++ b/src/Infrastructure/Form/ContactForm7Provider.php @@ -0,0 +1,99 @@ + -1]) as $form) { + $forms[] = $this->describe($form); + } + + return $forms; + } + + public function find(string $id): ?Form + { + $form = ctype_digit($id) ? \WPCF7_ContactForm::get_instance((int) $id) : null; + + return $form instanceof \WPCF7_ContactForm ? $this->describe($form) : null; + } + + private function describe(\WPCF7_ContactForm $form): Form + { + $fields = []; + + foreach ($form->scan_form_tags() as $tag) { + $base = (string) $tag->basetype; + + if ($tag->name === '' || in_array($base, self::SKIPPED, true) || ! in_array($base, self::TYPES, true)) { + continue; + } + + $multiple = $base === 'checkbox' ? ! $tag->has_option('exclusive') : ($base === 'select' && $tag->has_option('multiple')); + $fields[] = new FormField($tag->name, $base, $tag->is_required(), $multiple, self::options($base, $tag)); + } + + $id = (string) $form->id(); + + return new Form( + $this->name(), + $id, + (string) $form->title(), + $fields, + rest_url(sprintf('contact-form-7/v1/contact-forms/%s/feedback', $id)), + 'multipart/form-data', + ['_wpcf7' => $id, '_wpcf7_locale' => (string) $form->locale(), '_wpcf7_unit_tag' => sprintf('wpcf7-f%s-o1', $id)], + ); + } + + /** + * @return list + */ + private static function options(string $base, \WPCF7_FormTag $tag): array + { + if (! in_array($base, ['select', 'checkbox', 'radio'], true)) { + return []; + } + + $options = []; + + foreach (array_values((array) $tag->values) as $index => $value) { + $label = (array) $tag->labels; + $options[] = ['value' => (string) $value, 'label' => (string) ($label[$index] ?? $value)]; + } + + return $options; + } +} diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index ed4948a..8be9212 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -17,6 +17,7 @@ use Pollora\Headless\Domain\Media\MediaUrls; use Pollora\Headless\Infrastructure\Config\Settings; use Pollora\Headless\Infrastructure\Config\SettingsLoader; +use Pollora\Headless\Infrastructure\Form\ContactForm7Provider; use Pollora\Headless\Infrastructure\Language\LanguagesFactory; use Pollora\Headless\Infrastructure\Language\NoLanguages; use Pollora\Headless\Infrastructure\Redirect\OldSlugRedirects; @@ -133,6 +134,10 @@ public static function modules(Settings $settings, ?Languages $languages = null) $modules[] = new SearchRoutes($searchUrls, $languages, $settings->perPageMax ?? 50); } + if ($settings->forms) { + $modules[] = new FormRoutes(ContactForm7Provider::isAvailable() ? [new ContactForm7Provider] : []); + } + if ($settings->blocks) { $modules[] = new BlocksField; } diff --git a/src/Infrastructure/WordPress/FormRoutes.php b/src/Infrastructure/WordPress/FormRoutes.php new file mode 100644 index 0000000..b37cb44 --- /dev/null +++ b/src/Infrastructure/WordPress/FormRoutes.php @@ -0,0 +1,86 @@ + [...$providers, new MyProvider])`. + */ +final readonly class FormRoutes implements Module +{ + /** + * @param list $providers + */ + public function __construct(private array $providers) {} + + public function register(HookRegistrar $hooks): void + { + $hooks->addAction('rest_api_init', [$this, 'routes']); + } + + public function routes(): void + { + register_rest_route(ManifestRoutes::NAMESPACE, '/forms', [ + 'methods' => 'GET', + 'callback' => [$this, 'index'], + // Public on purpose: a form is what a visitor sees on the page + 'permission_callback' => '__return_true', + ]); + + register_rest_route(ManifestRoutes::NAMESPACE, '/forms/(?P[a-z0-9_-]+)/(?P[A-Za-z0-9_-]+)', [ + 'methods' => 'GET', + 'callback' => [$this, 'show'], + 'permission_callback' => '__return_true', + ]); + } + + public function index(): \WP_REST_Response + { + $forms = []; + + foreach ($this->providers() as $provider) { + foreach ($provider->forms() as $form) { + $forms[] = $form->summary(); + } + } + + return rest_ensure_response(['forms' => $forms]); + } + + /** + * @param \WP_REST_Request> $request + */ + public function show(\WP_REST_Request $request): \WP_REST_Response|\WP_Error + { + foreach ($this->providers() as $provider) { + if ($provider->name() !== $request->get_param('provider')) { + continue; + } + + $form = $provider->find((string) $request->get_param('id')); + + if ($form instanceof Form) { + return rest_ensure_response($form->toArray()); + } + } + + return new \WP_Error('headless_form_not_found', 'This form does not exist.', ['status' => 404]); + } + + /** + * @return list + */ + private function providers(): array + { + $providers = apply_filters('headless/forms/providers', $this->providers); + + return array_values(array_filter(is_array($providers) ? $providers : [], static fn (mixed $provider): bool => $provider instanceof FormProvider)); + } +} diff --git a/tests/Integration/FormsTest.php b/tests/Integration/FormsTest.php new file mode 100644 index 0000000..b8687cc --- /dev/null +++ b/tests/Integration/FormsTest.php @@ -0,0 +1,98 @@ +register(new WordPressHooks); + + $GLOBALS['wp_rest_server'] = null; + rest_get_server(); +} + +function makeContactForm(): int +{ + $form = WPCF7_ContactForm::get_template(['title' => 'Contact us']); + $form->set_properties(['form' => <<<'FORM' + [text* your-name] + [email* your-email] + [tel your-phone] + [select topic "Sales" "Support"] + [checkbox colours use_label_element "Red" "Blue"] + [radio plan "Free" "Paid"] + [acceptance consent] + [file attachment] + [textarea message] + [submit "Send"] + FORM]); + + return $form->save(); +} + +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('runs against a real Contact Form 7', function (): void { + expect(ContactForm7Provider::isAvailable())->toBeTrue(); +}); + +it('lists the forms of the site', function (): void { + formsServer(); + $id = makeContactForm(); + + $data = rest_do_request(new WP_REST_Request('GET', '/headless/v1/forms'))->get_data(); + wp_delete_post($id, true); + + expect($data['forms'])->toContain(['provider' => 'cf7', 'id' => (string) $id, 'title' => 'Contact us']); +}); + +it('describes the fields of a form and where to send them', function (): void { + formsServer(); + $id = makeContactForm(); + + $response = rest_do_request(new WP_REST_Request('GET', "/headless/v1/forms/cf7/$id")); + $data = $response->get_data(); + wp_delete_post($id, true); + $fields = array_column($data['fields'], null, 'name'); + + expect($response->get_status())->toBe(200) + ->and(array_keys($fields))->toBe(['your-name', 'your-email', 'your-phone', 'topic', 'colours', 'plan', 'consent', 'attachment', 'message']) + ->and($fields['your-name'])->toMatchArray(['type' => 'text', 'required' => true]) + ->and($fields['your-email'])->toMatchArray(['type' => 'email', 'required' => true]) + ->and($fields['your-phone'])->toMatchArray(['type' => 'tel', 'required' => false]) + ->and($fields['topic']['options'])->toBe([['value' => 'Sales', 'label' => 'Sales'], ['value' => 'Support', 'label' => 'Support']]) + ->and($fields['colours'])->toMatchArray(['type' => 'checkbox', 'multiple' => true]) + ->and($fields['plan'])->toMatchArray(['type' => 'radio', 'multiple' => false]) + ->and($fields['consent']['type'])->toBe('acceptance') + ->and($fields['attachment']['type'])->toBe('file') + ->and($data['submit']['method'])->toBe('POST') + ->and($data['submit']['content_type'])->toBe('multipart/form-data') + ->and($data['submit']['url'])->toContain("contact-form-7/v1/contact-forms/$id/feedback") + ->and($data['submit']['extra']->_wpcf7_unit_tag)->toBe("wpcf7-f$id-o1"); +}); + +it('answers 404 for a form that does not exist', function (): void { + formsServer(); + + expect(rest_do_request(new WP_REST_Request('GET', '/headless/v1/forms/cf7/999999'))->get_status())->toBe(404) + ->and(rest_do_request(new WP_REST_Request('GET', '/headless/v1/forms/cf7/abc'))->get_status())->toBe(404) + ->and(rest_do_request(new WP_REST_Request('GET', '/headless/v1/forms/other/1'))->get_status())->toBe(404); +}); diff --git a/tests/Unit/FormTest.php b/tests/Unit/FormTest.php new file mode 100644 index 0000000..1e09ca8 --- /dev/null +++ b/tests/Unit/FormTest.php @@ -0,0 +1,113 @@ +alias(static function (array $data): WP_REST_Response { + $response = Mockery::mock('WP_REST_Response'); + $response->shouldReceive('get_data')->andReturn($data); + + return $response; + }); +} + +function sampleForm(): Form +{ + return new Form( + 'cf7', + '12', + 'Contact', + [new FormField('your-email', 'email', true), new FormField('topics', 'checkbox', false, true, [['value' => 'a', 'label' => 'A']])], + 'https://cms.example.com/wp-json/contact-form-7/v1/contact-forms/12/feedback', + 'multipart/form-data', + ['_wpcf7_unit_tag' => 'wpcf7-f12-o1'], + ); +} + +function sampleProvider(): FormProvider +{ + return new class implements FormProvider + { + public function name(): string + { + return 'cf7'; + } + + public function forms(): array + { + return [sampleForm()]; + } + + public function find(string $id): ?Form + { + return $id === '12' ? sampleForm() : null; + } + }; +} + +it('describes a form and how to send it', function (): void { + $form = sampleForm()->toArray(); + + expect($form['provider'])->toBe('cf7') + ->and($form['id'])->toBe('12') + ->and($form['fields'][0])->toBe(['name' => 'your-email', 'type' => 'email', 'required' => true, 'multiple' => false, 'options' => []]) + ->and($form['fields'][1]['multiple'])->toBeTrue() + ->and($form['submit']['method'])->toBe('POST') + ->and($form['submit']['content_type'])->toBe('multipart/form-data') + ->and((array) $form['submit']['extra'])->toBe(['_wpcf7_unit_tag' => 'wpcf7-f12-o1']) + ->and(sampleForm()->summary())->toBe(['provider' => 'cf7', 'id' => '12', 'title' => 'Contact']); +}); + +it('keeps an empty extra as a JSON object', function (): void { + $form = new Form('x', '1', 't', [], 'https://x.test', 'application/json'); + + expect(json_encode($form->toArray()['submit']))->toContain('"extra":{}'); +}); + +it('registers its two routes on the REST API', function (): void { + Brain\Monkey\Actions\expectAdded('rest_api_init')->once(); + $routes = []; + Functions\when('register_rest_route')->alias(function (string $namespace, string $route) use (&$routes): void { + $routes[] = $namespace.$route; + }); + + $module = new FormRoutes([]); + $module->register(new WordPressHooks); + $module->routes(); + + expect($routes)->toBe(['headless/v1/forms', 'headless/v1/forms/(?P[a-z0-9_-]+)/(?P[A-Za-z0-9_-]+)']); +}); + +it('lists the forms of every provider, and lets a filter add providers', function (): void { + responseDouble(); + Filters\expectApplied('headless/forms/providers')->once()->andReturnUsing(static fn (array $providers): array => [...$providers, 'not a provider']); + + expect((new FormRoutes([sampleProvider()]))->index()->get_data())->toBe(['forms' => [['provider' => 'cf7', 'id' => '12', 'title' => 'Contact']]]); +}); + +it('gives the fields of one form, and a 404 for one that is not there', function (): void { + responseDouble(); + Functions\when('apply_filters')->alias(static fn (string $hook, mixed $value): mixed => $value); + + $module = new FormRoutes([sampleProvider()]); + $request = static function (string $provider, string $id): WP_REST_Request { + $request = Mockery::mock('WP_REST_Request'); + $request->shouldReceive('get_param')->with('provider')->andReturn($provider); + $request->shouldReceive('get_param')->with('id')->andReturn($id); + + return $request; + }; + + expect($module->show($request('cf7', '12'))->get_data()['title'])->toBe('Contact') + ->and($module->show($request('cf7', '99')))->toBeInstanceOf(WP_Error::class) + ->and($module->show($request('other', '12')))->toBeInstanceOf(WP_Error::class); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 3b2f52c..0053caf 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(17); + expect(Bootstrap::modules($settings))->toHaveCount(18); Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->times(8); + Actions\expectAdded('rest_api_init')->times(9); Filters\expectAdded('preview_post_link')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('rest_post_dispatch')->once(); @@ -141,9 +141,9 @@ function gateFor(FrontMode $mode, array &$ended): TemplateRedirectGate it('hooks no gate when the front is left as it is', function (): void { $settings = Settings::fromArray([], 'https://cms.example.com'); - expect(Bootstrap::modules($settings))->toHaveCount(5); + expect(Bootstrap::modules($settings))->toHaveCount(6); - Actions\expectAdded('template_redirect')->never(); + Actions\expectAdded('template_redirect')->once(); Actions\expectAdded('rest_api_init')->never(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('wp_sitemaps_add_provider')->once(); From 3e37d1c8a764851b6687004e9e622dde0a6a3f32 Mon Sep 17 00:00:00 2001 From: Olivier Gorzalka Date: Wed, 25 Nov 2026 09:10:09 +0100 Subject: [PATCH 6/6] docs(0.7): README and changelog; fix module counts, analysers for Contact Form 7 --- CHANGELOG.md | 5 +++ README.md | 41 ++++++++++++++++++++++- composer-dependency-analyser.php | 2 +- phpstan.neon | 2 ++ tests/Unit/Infrastructure/ModulesTest.php | 4 +-- 5 files changed, 50 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c175cd9..fcb2f51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 2dbf91c..09ed990 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 diff --git a/composer-dependency-analyser.php b/composer-dependency-analyser.php index db1d2ce..9942dbf 100644 --- a/composer-dependency-analyser.php +++ b/composer-dependency-analyser.php @@ -16,7 +16,7 @@ return (new Configuration) ->disableReportingUnmatchedIgnores() - ->ignoreUnknownClassesRegex('~^(WP_|Walker_|Requests_|wpdb$)~') + ->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('~.*~') diff --git a/phpstan.neon b/phpstan.neon index 1618d39..2b42fe2 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -18,5 +18,7 @@ parameters: - '#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 diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 0053caf..ddc642f 100644 --- a/tests/Unit/Infrastructure/ModulesTest.php +++ b/tests/Unit/Infrastructure/ModulesTest.php @@ -143,8 +143,8 @@ function gateFor(FrontMode $mode, array &$ended): TemplateRedirectGate expect(Bootstrap::modules($settings))->toHaveCount(6); - Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->never(); + Actions\expectAdded('template_redirect')->never(); + Actions\expectAdded('rest_api_init')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('wp_sitemaps_add_provider')->once(); Actions\expectAdded('init')->once();