Using Rich Text in the PHP Delivery client library
Sometimes you find yourself in a situation where the editor must have great control over how content is structured. For such cases, the rich text field type is exactly what you need. The previous link will discuss how this field type is handled in the web app, whereas this tutorial will teach how you can use it in your applications with the PHP Delivery client library.
The client library automatically handles rich text field types, using the rich-text.php library. However, it’s very likely that you might want to customize its behavior. You can do this in two ways: through the NodeRenderer and through the NodeParser.
Customizing the rendering
Often you might want to customize the rendering of a certain node type, most commonly those with entries or assets. In order to do so, you need to work with a main renderer, and multiple node renderers. Let’s make an example with the following assumption: we have a content type with ID blogPost, which has a slug and a title (simple strings) and a body (a rich text field). We want to allow the editor to link to other blog posts in the body, and in our templates use the slug property to generate the appropriate link:
For more about extending the renderer, and how to integrate it with Twig or Plates, take a look at the library’s README.
Customizing the parsing
A less common yet still useful use case is to customize the parsing of rich text, that is, the process of converting the raw API response structured as a nested PHP array into a graph of Contentful\RichText\Node\NodeInterface objects. The Delivery client library automatically creates an instance of the Contentful\RichText\NodeParser class, and you can access it using $client->getNodeParser(); the most common use case is to define custom node mappers.
In the example above, all nodes with "nodeType": "text" will be forwarded to the custom node mapper instead of the default one.