Handlers
Serializer handlers take over (de)serialization of a value of given type. T3api delivers handlers for things which are common in TYPO3 but which plain JSON serialization can not handle well - files, processed images, links to records and typolinks.
Some handlers are used automatically (based on the class of the value), others are activated by setting the type of a property or virtual property - with annotation from \Source namespace or with type key in YAML metadata.
| Handler | Activated by | Output |
|---|---|---|
File | automatically for classes extending Extbase's File or Folder nested in an entity (on
deserialization also File and its subclasses) | object with url, uid and file data |
Image | @T3api\, type Image<...> | absolute URL of processed image |
Record | @T3api\, type Record | absolute URL of record (e.g. news detail page) |
Typolink | @T3api\, type Typolink | absolute URL built from typolink value |
Rte | @T3api\, type Rte | HTML processed by lib. |
Password | @T3api\, type Password | on deserialization: hashed password; on serialization: null (stored hash with serialize=true) |
Current | @T3api\ | see Current user assignment |
FileReference
Objects of classes extending Extbase's \TYPO3\ or Folder (e.g. \Georg or your own file reference class) nested in an entity are serialized automatically, there is nothing to configure. Objects of classes extending File are serialized like other objects. Example of fal property of news:
"falMedia": [
{
"url": "https://14.t3api.ddev.site/fileadmin/user_upload/test1.jpg",
"uid": 4,
"file": {
"uid": 1,
"name": "test1.jpg",
"mimeType": "image/jpeg",
"size": 42520
}
}
]
url- absolute URL of the original file.uid- uid of the file reference (sys_).file_ reference file- data of the original file (sys_). Containsfile filewhen the token is returned for the file, see File token.Token url- only for videos (e.g. YouTube, Vimeo) - URL which can be used inEmbed <iframe>.
The structure of the output is fixed - other properties of the file reference (title, alternative, link...) are not added to it, even if they are configured in serialization metadata. If you need them in the response, expose them with a virtual property of the parent entity or with a custom handler.
The same handler is used for deserialization, also of properties of type File or a class extending it - see Handling File Upload how to attach files in POST / PATCH payload.
Image
Returns absolute URL of an image processed by TYPO3 (resized / cropped) - so frontend does not need to load original, possibly huge, files. It can be used on a property or a method returning File, uid of sys_, or a list (e.g. Object) of them - then a list of URLs is returned.
Parameters (all optional; values are the same as in f: ViewHelper, so c and m suffixes work):
widthheightmaxWidth maxHeight crop- name of the crop variant (defaultVariant default).
use SourceBroker\T3api\Annotation as T3api;
class News extends \GeorgRinger\News\Domain\Model\News
{
/**
* @T3api\Serializer\VirtualProperty("imageThumbnail")
* @T3api\Serializer\Type\Image(width="380", height="250c")
*/
public function getImageThumbnail(): ?FileReference
{
return $this->getFalMedia()->count() ? $this->getFalMedia()->toArray()[0] : null;
}
}
The same in YAML metadata (parameters are positional: width, height, max, max, crop). This is how image and image are configured in EXT::
SourceBroker\T3apinews\Domain\Model\News:
virtual_properties:
getImageThumbnail:
serialized_name: imageThumbnail
groups: [api_get_collection_t3apinews_news, api_get_item_t3apinews_news]
type: "Image<'380','250c','','',''>"
getImageLarge:
serialized_name: imageLarge
groups: [api_get_collection_t3apinews_news, api_get_item_t3apinews_news]
type: "Image<'1280','768','','',''>"
RecordUri
Returns absolute URL to the record, built with TYPO3 record link handler (t3://). The only parameter is the identifier of the link handler configured in config. TypoScript. The value of the property itself is not used - uid of the serialized entity is taken, so it is usually used on a virtual property.
config.recordLinks.tx_news {
typolink {
parameter = {$plugin.tx_t3apinews.pageUid.newsDetails}
additionalParams.data = field:uid
additionalParams.wrap = &tx_news_pi1[controller]=News&tx_news_pi1[action]=detail&tx_news_pi1[news]=|
}
}
/**
* @T3api\Serializer\VirtualProperty("singleUri")
* @T3api\Serializer\Type\RecordUri("tx_news")
*/
public function getSingleUri(): string
{
return '';
}
SourceBroker\T3apinews\Domain\Model\News:
virtual_properties:
getSingleUri:
serialized_name: singleUri
groups: [api_get_collection_t3apinews_news, api_get_item_t3apinews_news]
type: "RecordUri<'tx_news'>"
If the URL can not be resolved an empty string is returned.
Note
JMS serializer skips virtual properties returning null before the handler is called, so the method used for Record has to return a non-null value (e.g. empty string).
Typolink
Converts value of a typolink field (e.g. t3://, https://, t3://, or legacy 5 _) into an absolute URL. If the value is empty or the link can not be resolved (e.g. target page is hidden or deleted), an empty string is returned.
/**
* @T3api\Serializer\Type\Typolink
*/
protected string $link = '';
GeorgRinger\News\Domain\Model\FileReference:
properties:
link:
type: Typolink
Rte
Processes the value with lib. (as f: does), so t3:// links inside RTE content are converted into real URLs.
/**
* @T3api\Serializer\Type\Rte
*/
protected string $bodytext = '';
PasswordHash
Used in deserialization only - plain password sent in the payload is hashed with default frontend hashing method before it is set on the entity. Useful for registration endpoints.
/**
* @T3api\Serializer\Type\PasswordHash
*/
protected $password = '';
On serialization null is returned, so the stored password hash is not included in API responses. If you need to read the hash (e.g. to migrate users to another system), enable it explicitly with serialize=true:
/**
* @T3api\Serializer\Type\PasswordHash(serialize=true)
*/
protected $password = '';
or in YAML metadata:
Vendor\Extension\Domain\Model\User:
properties:
password:
type: "PasswordHash<'serialize'>"
Warning
With serialize=true make sure the property is added only to groups of operations restricted to trusted users (see Security).
Real examples. Run "ddev restart && ddev ci 14" and try those links below.
- Single news - see
fal(FileReference),Media image/Thumbnail image(Image) andLarge single(RecordUri):Uri
Custom handlers
Custom handler is a class implementing JMS \JMS\. The easiest way is to extend \Source and implement Serialize and/or Deserialize - then only the list of supported types is needed.
<?php
namespace Vendor\Extension\Serializer\Handler;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
use SourceBroker\T3api\Serializer\Handler\AbstractHandler;
use SourceBroker\T3api\Serializer\Handler\SerializeHandlerInterface;
class PriceHandler extends AbstractHandler implements SerializeHandlerInterface
{
public const TYPE = 'Price';
protected static $supportedTypes = [self::TYPE];
public function serialize(
SerializationVisitorInterface $visitor,
$value,
array $type,
SerializationContext $context
): string {
$currency = $type['params'][0] ?? 'EUR';
return number_format((int)$value / 100, 2, '.', '') . ' ' . $currency;
}
}
Register the handler in ext_. Handlers are created with General, so constructor dependency injection works if the class is public in Services..
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['t3api']['serializerHandlers'][]
= \Vendor\Extension\Serializer\Handler\PriceHandler::class;
And use the type in YAML metadata:
Vendor\Extension\Domain\Model\Product:
properties:
priceInCents:
serialized_name: price
type: "Price<'USD'>"
To use the type as annotation, create a class implementing \Source (see \Source as an example) - get returns the type name and get the list of parameters.
Note
Flush system caches after registering a new handler or changing types - serializer metadata is cached.