Extending
Decorators
A decorator changes the types the mapper builds, whatever builder built them. A builder adds a type for a name, a decorator wraps types already built: every enum, every type of some class, every type at all.
A decorator is called once for each built type, before the mapper keeps it. It gets the type, the node it was built from, and returns the type to keep: the same one when it is not interested, or a wrapper. Decorators run in the order of the list, each gets the result of the previous one.
A decorator that trims the strings given to every backed enum:
use TypeLang\Mapper\Context\Context;use TypeLang\Mapper\Mapper;use TypeLang\Mapper\Type\BackedEnumType;use TypeLang\Mapper\Type\Decorator\TypeDecoratorInterface;use TypeLang\Mapper\Type\TypeDecorator;use TypeLang\Mapper\Type\TypeInterface;
// The wrapper: TypeDecorator passes every call to $this->delegatefinal class TrimmingType extends TypeDecorator{ #[\Override] public function isDenormalizable(mixed $value, Context $context): bool { return $this->delegate->isDenormalizable(self::trim($value), $context); }
#[\Override] public function denormalize(mixed $value, Context $context): mixed { return $this->delegate->denormalize(self::trim($value), $context); }
private static function trim(mixed $value): mixed { return \is_string($value) ? \trim($value) : $value; }}
// The decorator: wraps the types of backed enums onlyfinal class TrimEnumsDecorator implements TypeDecoratorInterface{ public function decorate(TypeInterface $type, /* ... */): TypeInterface { if (!$type instanceof BackedEnumType) { return $type; }
return new TrimmingType($type); }}
$mapper = new Mapper(decorators: [new TrimEnumsDecorator()]);enum Status: string{ case Active = 'active'; case Banned = 'banned';}$mapper->denormalize(' active ', Status::class); // Status::Active$mapper->denormalize([' banned'], 'list<Status>'); // [Status::Banned]$mapper->denormalize('gone', Status::class);// throws InvalidValueException:// $: Value must be of type 'active'|'banned', but "gone" givenThe wrapped type is still described by its own form in errors (the values of the enum above), unless an expander supports the wrapper.