Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,212 of 9,212 pages
About the help in other languages
All help pages

Maintainer guide

What this is. A map of the kernel code behind the headless features, and step-by-step instructions for the changes maintainers make most: a field, a datatype mapping, a mutation, an event kind, a schema extension; the…

Download as PDF

Address: https://doc.exponential.earth/learninminutes/exphelp/viewer/headless/maintainer-guide.md

On this page

Maintainer guide

What this is. A map of the kernel code behind the headless features, and step-by-step instructions for the changes maintainers make most: a field, a datatype mapping, a mutation, an event kind, a schema extension; the tests that cover them; and the release checklist.

When to use it. Before you change anything under kernel/classes/graphql/, the API keys, the CORS layer or the event journal, or write an extension that adds to the schema.

Quick example: a schema extension that adds the root query ping (put it in an extension, list it in SchemaExtensionList[]).

<?php
use GraphQL\Type\Definition\Type;

class myGraphQLPingExtension implements expGraphQLSchemaExtension
{
    public function isAvailable() { return true; }
    public function name() { return 'myping/1'; }                 // part of the schema hash
    public function datatypes() { return array(); }
    public function fieldMapping( array $attribute, expGraphQLTypes $types ) { return null; }
    public function locationFields( expGraphQLTypes $types ) { return array(); }
    public function queryFields( expGraphQLTypes $types )
    {
        return array( 'ping' => array( 'type' => Type::nonNull( Type::string() ), 'description' => 'Answers pong.',
                                       'resolve' => function () { return 'pong'; } ) );
    }
}
# extension/myext/settings/graphql.ini.append.php
[GraphQLSettings]
SchemaExtensionList[]=myGraphQLPingExtension
php bin/php/ezpgenerateautoloads.php -e && php bin/php/ezcache.php --clear-tag=ini --allow-root-user
./console exp:graphql:query '{ ping }'      # {"data":{"ping":"pong"}, ...}

Contents

  1. Where the code lives
  2. Design rules
  3. How a request flows through the classes
  4. Adding a field
  5. Adding a datatype
  6. Adding a mutation
  7. Adding an event kind
  8. Adding a setting
  9. Messages and translations
  10. The tests
  11. Running the gates
  12. The release checklist
  13. Keeping the SDK in step

Where the code lives

PathWhat
kernel/classes/graphql/expgraphql.phpexpGraphQL: settings access (setting(), intSetting(), listSetting()), isEnabled(), loadLibrary(), the library state
expgraphqlserver.phpexpGraphQLServer: request parsing, persisted queries, the response, validation rules, error formatting and codes
expgraphqlcontext.phpexpGraphQLContext: who asks, how signed in, request id, cache tags, batch loaders, audit, writer
expgraphqlschemabuilder.phpexpGraphQLSchemaBuilder: the schema of a siteaccess, its hash, the root Query
expgraphqltypes.phpexpGraphQLTypes: every kernel type (Content, Location, connections, value types), extension hooks
expgraphqlclasscatalogue.phpthe classes and attributes the schema shows (ClassList[], HiddenFieldList[] ...)
expgraphqlnaming.phptype and field names (NamingStyle, reserved names)
expgraphqlfieldmapper.phpdatatype → GraphQL type and resolver
expgraphqlrepository.php, expgraphqlcontent.php, expgraphqllocation.php, expgraphqlconnection.php, expgraphqlsearchconnection.php, expgraphqlbatchloader.phpreading content through the user's policies, pagination, batching
expgraphqlimage.php, expgraphqlrichtext.phpvalue objects of images and rich text
expgraphqlmutations.php, expgraphqlwriter.php, expgraphqlfieldinput.php, expgraphqlupload.php, expgraphqluploadcheck.php, expgraphqldraftcontent.phpmutations, writing, field input, uploads
expgraphqlpreviewtoken.phppreview tokens
expgraphqlpersistedqueries.phpthe store of persisted queries
expgraphqlresponsecache.phpthe response cache, the early answer, ETags, cache-tag headers, credential cache
expgraphqlratelimiter.phprate limits
expgraphqlevents.php, expgraphqleventlistener.php, expgraphqleventkinds.php, expgraphqleventextension.phpthe journal, the listener, package event kinds
expgraphqlwebhooks.php, expgraphqlwebhookqueuehandler.phpwebhooks, the expqueue handler
expgraphqlsubscriptions.phpsubscriptions, SSE
expgraphqlschemaextension.php, expgraphqlschemaextensions.php, expgraphqlmutationextension.phpthe extension interfaces and their loading
extensions/the shipped extensions: tags (expGraphQLTagsExtension), layouts (expGraphQLLayoutsExtension)
rest/expGraphQLRestProvider (routes), expGraphQLRestController, the response classes
expgraphqlmessage.php, expgraphqlerror.phptranslated messages; error codes
expgraphqlsetup.php, expgraphqlstarter.php, expgraphqlbench.phpSetup > GraphQL, starters, benchmarks
kernel/graphql/module.php, kernel/private/classes/views/graphql/the module graphql (playground, session end point)
kernel/private/classes/commands/expgraphql*.php, bin/php/expgraphql*.phpthe console commands
kernel/private/classes/cronjobs/graphqlwebhooks.phpthe cron part
kernel/classes/apikey/expapikey.php, kernel/private/rest/classes/auth/apikey_*.phppersonal API keys
kernel/private/rest/classes/cors.phpexpRestCors
index_rest.phpthe early answer hook at the top
settings/graphql.ini, settings/rest.ini, settings/expqueue.inisettings with their documentation
share/graphql/starters/the starter kits
tests/tests/kernel/classes/graphql/the tests
doc/eng-us/features/6.0/graphql.md, doc/eng-us/headless/the documentation

The migrations' schema extension (expMigrationGraphQLExtension) lives with the migration code; expwt and cjw_newsletter bring their own extensions.

Design rules

These hold for every change; reviews check them.

  1. The user's policies decide. Every resolver reads through the kernel's fetch functions with policy checks (canRead(), checkAccess()); never a raw database read that skips them. What the user may not read is null or left out, never an error that confirms it exists.
  2. The kernel's operations write. Mutations go through eZOperationHandler (workflows run) or the same collection functions the administration uses, in a transaction, with audit (expGraphQLMutations::run()), cache expiry and a journal event.
  3. No library, no harm. Classes that the early answer, the journal or the error codes need must not depend on webonyx (expGraphQLError, expGraphQLEvents, expGraphQLRateLimiter, expGraphQLResponseCache). Files that use the library are loaded only after expGraphQL::loadLibrary() succeeded.
  4. Persistent workers. Velocity serves many requests per process: no request state in statics (reset it per request, as expApiKeyRest::reset() and the listener's request id do); a new expGraphQLContext per request.
  5. Stable contract. Error codes, kernel fields, headers, event fields and wire formats only grow (see Compatibility and upgrades).
  6. Batch, do not loop. A field that resolves something per item of a list uses a batch loader ($ctx->loader( kind, language, batch )) and returns a \GraphQL\Deferred.
  7. Cache tags. A resolver that shows content notes its tags ($ctx->noteContent(), noteCacheTags(), expGraphQLTypes::noteListTags()); a new kind of answer without tags makes cached front ends stale.
  8. No personal data in the journal or webhooks beyond what the record already carries; package event fields are reviewed for it.
  9. Every message translatable through expGraphQLMessage::tr().
  10. Every change documented in both languages (doc/eng-us/, doc/ger-de/).

How a request flows through the classes

index_rest.php ── expGraphQLResponseCache::serveEarly()  (HIT → answer, exit)
   └─ ezpKernelRest ─ CORS (expRestCors) ─ auth (expApiKeyRest / OAuth) ─ route (expGraphQLRestProvider)
        └─ expGraphQLRestController::doQuery()
             ├─ expGraphQL::isEnabled(), loadLibrary()
             ├─ expGraphQLServer::parseHttpRequest()
             ├─ expGraphQLRateLimiter::hitRequest()
             ├─ expGraphQLSchemaBuilder::fromSettings()  (catalogue, naming, types, field mapper, extensions)
             ├─ new expGraphQLContext( user, authMode, repository, baseUrl )
             └─ expGraphQLServer::respond()
                  ├─ resolvePersisted() (store, APQ, PersistedQueriesOnly)
                  ├─ response cache lookup / write, credential cache
                  └─ execute(): parse, mutation refusal, validation rules, GraphQL::executeQuery(), formatError()

Mutations: expGraphQLMutations::fields() → resolver → run() (audit begin, expGraphQLWriter::<op>(), audit end, expireCache(), expGraphQLEventListener::mutation()). Events: kernel hooks → expGraphQLEventListener::note() → end of request → expGraphQLEvents::append(); read by expGraphQLWebhooks::dispatch()/deliver() and expGraphQLSubscriptions::stream().

Adding a field

A field every content has (Content): add it to expGraphQLTypes::contentFields(), which is shared by the interface and every class type. Before you do: a field name that a class attribute could have collides (the attribute is renamed to <name>_field, which changes those classes' schema): prefer names unlikely as attribute identifiers, and list the reserved names in expGraphQLNaming.

'mainNodeDepth' => array( 'type' => Type::int(), 'description' => 'The depth of the main location.',
    'resolve' => function ( expGraphQLContent $c ) {
        $main = $c->mainLocation();
        return $main instanceof expGraphQLLocation ? $main->depth() : null;
    } ),

A field of Location from an extension: locationFields() of a schema extension. A root query from an extension: queryFields(). In the kernel: expGraphQLSchemaBuilder (the root Query).

Checklist for a new field:

  1. Read through the policies; null when not readable.
  2. Note cache tags for what it shows.
  3. Batch when it is per item of a list.
  4. Description in the schema (one sentence; clients see it in their tools).
  5. Tests: expGraphQLSchemaTest (the field is there, its type), a behavior test (what it answers, for a user who may and one who may not read).
  6. Documentation: GraphQL API reference (EN and DE), the feature page.
  7. The schema hash changes: mention it in the changelog ("regenerate your types").

Adding a datatype

A datatype without a mapping is a String with its toString(). To give it a type:

In an extension (preferred for an extension's datatype): implement datatypes() and fieldMapping() of a schema extension:

public function datatypes() { return array( 'myrating' ); }

public function fieldMapping( array $attribute, expGraphQLTypes $types )
{
    if ( $attribute['datatype'] !== 'myrating' )
        return null;
    $type = $types->register( 'MyRating', function () {
        return new \GraphQL\Type\Definition\ObjectType( array( 'name' => 'MyRating', 'fields' => array(
            'stars' => array( 'type' => \GraphQL\Type\Definition\Type::int() ),
            'votes' => array( 'type' => \GraphQL\Type\Definition\Type::nonNull( \GraphQL\Type\Definition\Type::int() ) ),
        ) ) );
    } );
    return array( $type, function ( eZContentObjectAttribute $field, expGraphQLContext $ctx, array $args ) {
        $content = $field->content();
        return array( 'stars' => $field->hasContent() ? (int)$content['stars'] : null, 'votes' => (int)$content['votes'] );
    } );
}
  • $types->register( name, factory ) makes a type once per schema; the name must not be one a content class could take, nor a kernel name (expGraphQLNaming::RESERVED_TYPES).
  • The resolver gets the attribute of the translation read; return null for an empty field, [] for an empty list.
  • A relation-like value uses a batch loader.

In the kernel (for a kernel datatype): add it to expGraphQLFieldMapper::MAPPED and a case in mapping(), a value type in expGraphQLTypes (and its name in RESERVED_TYPES), and expGraphQLDatatypesTest. When its value is a file, add it to expGraphQLFieldInput::FILE_DATATYPES so it is written by upload only.

Writing. FieldInput.value goes through the datatype's fromString(); make sure it reads what toString() writes. Document the format in Datatypes in GraphQL and in exponentialcms-datatypes.

Adding a mutation

In the kernel: add a field to expGraphQLMutations::fields(), a method to expGraphQLWriter, and run it through expGraphQLMutations::run():

'renameContent' => array(
    'type' => $payload,
    'description' => 'Sets the name field of content (content/edit).',
    'args' => array( 'id' => array( 'type' => Type::nonNull( Type::int() ) ), 'name' => array( 'type' => Type::nonNull( Type::string() ) ) ),
    'resolve' => function ( $root, $args, expGraphQLContext $ctx ) {
        return expGraphQLMutations::run( 'renameContent', $ctx, $args, array( 'type' => 'object', 'id' => (int)$args['id'] ),
            function ( expGraphQLWriter $writer ) use ( $args ) {
                return $writer->update( array( 'id' => $args['id'], 'fields' => array( array( 'identifier' => 'name', 'value' => $args['name'] ) ) ) );
            } );
    },
),

run() records the audit (content.graphql.mutation, or .failed with the reason), expires the response cache unless the status is CANCELLED, and writes the mutation event. The writer method checks the policies (throw expGraphQLWriter::forbidden() / notFound()), uses the kernel's operation (eZOperationHandler::execute( 'content', '<op>', ..., null, true )) where one exists so workflows run, maps workflow results with workflowStatus(), and returns status, contentId, nodeId, version, content.

In an extension: implement expGraphQLMutationExtension::mutationFields(); the resolver must call expGraphQLMutations::refusal( $ctx ) first and throw what it answers. A mutation open to anonymous callers (a newsletter sign-up) also declares anonymousMutationFields() and guards itself (its own policy check and rate limit), since refusal() would refuse the anonymous user.

Checklist: policies; the operation and its workflows; idempotency notes (can a retry duplicate?); audit; cache; event; ContentPayload status; expGraphQLMutationsTest (allowed, refused per rule, the audit lines, the event); documentation (reference EN/DE, the SDK package exponentialcms-write).

Adding an event kind

For a package: implement expGraphQLEventExtension::eventKinds() on the extension's schema extension and call expGraphQLEventListener::packageEvent( $kind, $fields, $objectId, $nodeIds ) where it happens. The kernel validates the declaration (segments, length, object/policy, at most 20 typed fields), keeps only declared fields, and lists the kind in exp:graphql:status. Receivers get it only when they name it. Keep personal data out of the fields.

For the kernel: a new core kind is a contract change. Add the constant to expGraphQLEvents, put it in EXPLICIT (sent only when named, so existing receivers are not surprised), call the listener from the kernel where it happens (always through note(), written at the end of the request), add it to ContentEventKind, the SDK's JournalEventKind and tagsForEvent(), and document it in Events, webhooks and subscriptions. Tests: expGraphQLRealTimeTest, expGraphQLEventKindsTest.

Adding a setting

  1. Add it to settings/graphql.ini (or rest.ini) with a comment that says what it does, its values and its default (the comment is the first documentation).
  2. Read it through expGraphQL::setting( 'Name', <default> ) / intSetting() / listSetting(), with the same default in code, so an installation with an old settings file behaves.
  3. If the early answer needs it, remember it with the cache entry (the early answer reads no settings).
  4. Show it in exp:graphql:status and Setup > GraphQL when operators need it.
  5. Document it: the example pages (doc/eng-us/examples/ini-settings/graphql/), the feature page, the settings tables of these pages; DE too.
  6. If it changes the schema, include it in the schema hash.

Messages and translations

Every text a client or an operator sees goes through expGraphQLMessage::tr( 'English text with %placeholders.', array( '%placeholder' => $value ) ). The context is kernel/graphql; translations live in share/translations/<language>/translation.ts of every administration catalogue. The language follows Accept-Language (expGraphQLMessage::useLanguage(), set per request), else the siteaccess's locale. Do not translate specification messages of the library or PersistedQueryNotFound/PersistedQueryNotSupported (Apollo reads them). Add new texts to the catalogues (the translation tests list missing ones).

The tests

tests/tests/kernel/classes/graphql/:

TestCovers
expGraphQLSchemaTestthe schema, naming, hidden classes and fields, the hash
expGraphQLDatatypesTestevery datatype mapping
expGraphQLRestTestthe HTTP end point: parsing, statuses, headers
expGraphQLQueryBudgetTestdepth, complexity, list limits
expGraphQLSearchTestsearch
expGraphQLMutationsTest, expGraphQLWriterSectionsStatesSqliteTest, expGraphQLMutationExtensionTestmutations, sections and states (SQLite), extension mutations
expGraphQLPersistedQueriesTest, expGraphQLResponseCacheTestpersisted queries, the cache, early answers
expGraphQLRateLimiterTestrate limits
expGraphQLRealTimeTest, expGraphQLEventKindsTest, expGraphQLWebhookQueueLiveTestthe journal, webhooks, subscriptions, package kinds, queue delivery
expGraphQLTagsExtensionTest, expGraphQLLayoutsExtensionTest, expMigrationGraphQLExtensionTestthe shipped extensions
expGraphQLMessageTesttranslated messages
expGraphQLSetupTest, expGraphQLStarterTest, expGraphQLBenchTestadministration, starters, bench
expGraphQLLibraryMissingTestthe API without the library

The API keys and CORS have their own tests under tests/tests/kernel/private/restapi/ (expRestCorsTest, key tests). tests/test-map.json maps source files to the tests the fast gate runs for them.

Run one test file (never a whole directory by path):

php vendor/bin/phpunit --no-coverage tests/tests/kernel/classes/graphql/expGraphQLMutationsTest.php

Contract tests of the SDK run against a test installation: EXPONENTIAL_CONTRACT_URL=https://test.example.com npm run test:contract in exponentialcms-client. Never point them at production.

Running the gates

Before a push to the kernel's main, the same checks the continuous integration runs: PHP lint (8.3 and 8.0), the manifest (share/filelist.md5 lines of every changed file), phpcs on the diff, PHPStan, and the PHPUnit tests mapped to the changed files. The fast mode runs them for the changed files only. The full suites run in CI and before a release. The manifest line of a changed file is its md5 as committed; a documentation page is in the manifest too.

The release checklist

For a release that changes the headless features:

  1. Contract. No error code, kernel field, header, event field or wire format renamed, removed or changed in meaning (Compatibility and upgrades). New kernel event kinds are explicit.
  2. Schema. exp:graphql:schema before and after on a reference installation; every difference intended and in the changelog.
  3. Settings. New settings documented in the INI file, the example pages and these pages; defaults safe.
  4. Security. Policies on every new resolver; nothing readable that was not; mutations audited; no personal data in events; CSRF for sessions; keys only from the header.
  5. Persistent workers. No request state in statics; tested under Velocity.
  6. Tests. The mapped tests and the full suites pass; new behavior has tests (allowed and refused).
  7. Performance. exp:graphql:bench on a reference installation: cached rows within 33 ms.
  8. Documentation. These pages and the feature page updated in English and German, the changelog (doc/changelogs/6.0/<version>.md) lists every change with Added:/Updated:/Removed:/Renamed:, the history table extended.
  9. Manifest. share/filelist.md5 current for every changed file.
  10. SDK. The client's contract tests pass against the release candidate; SDK packages that need the new feature state the kernel version.
  11. Version numbers. Chosen from the tags that exist (git tag -l 'v*' --sort=version:refname, gh release list), never from memory; a published tag is never moved: a mistake is fixed by the next version.

Keeping the SDK in step

Kernel changeSDK package to update
new error codeexponentialcms-client (errors.ts, the code list)
new field or typeexponentialcms-codegen (if it needs special handling), exponentialcms-query
new datatype mapping or string formatexponentialcms-datatypes
rich text changesexponentialcms-richtext
new mutationexponentialcms-write
new event kind or fieldexponentialcms-client (events.ts, cache-tags.ts)
new headerexponentialcms-client (ClientResult), the CORS guidance (ExposedHeaders[])
new tag kindexponentialcms-client (tagsForEvent()), the framework packages

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x