util-transformer
Type transformers, normalizers and resolvers.
Installation
Install with Composer;
composer require phrity/util-transformer
All transformers exposes canTransform() and transform() methods.
This allows us to transform data of a certain type to another type. A specific transformer may not be able to transform all types.
$transformer = new BasicTypeConverter();
if ($transformer->canTransform($subject)) {
$transformed = transformer->transform($subject);
}
As option, a transformer can take a target type specifier as second argument.
$transformer = new BasicTypeConverter();
if ($transformer->canTransform($subject, Type::ARRAY)) {
$transformed = transformer->transform($subject, Type::ARRAY);
}
Utility resolvers enable stacking multiple transformers and performing other tasks.
$transformer = new RecursionResolver(
new FirstMatchResolver([
new EnumConverter(),
new ReadableConverter(),
new ThrowableConverter(),
new StringableConverter(),
new BasicTypeConverter(),
])
);
if ($transformer->canTransform($subject, Type::STRING)) {
$transformed = transformer->transform($subject, Type::STRING);
}
Encoders & Decoders
- Flatten Decoder - Expands array with flattened keys to nested array
- Json Decoder - Decodes JSON string
Type converters
- Basic Type - Support transforming all PHP types to all other types
- DateTime - Transform DateTime classes to string
- Enum - Transform Enums to string
- Json Serializable - Transform JSON serializable objects
- Readable - Transform booleans and null to readable strings
- Reversed Readable - Transform some strings to boolean and null
- Stringable - Transform stringable objects to string
- Throwable - Transform throwable to object, array or string
Utility resolvers
- Chained - Collection of transformers that will send output from one into next one
- First Match - Collection of transformers that will use first compatible transformer for transformation
- Recursion - Will apply transformer recursively
- String - Fold anything to a string
Wrappers
- Symfony Normalizer - Wrap class implementing Symfony
NormalizerInterface
| Version | PHP | |
|---|---|---|
1.3 |
^8.1 |
Transformer: DateTime, Resolver: Chained, String |
1.2 |
^8.1 |
Additional transformers |
1.1 |
^8.1 |
Additional transformers |
1.0 |
^8.1 |
Initial version |
Requirements
PHP
^8.1Documentation
Overview TypesCodecs
FlattenDecoderJsonDecoderConverters
BasicTypeDateTimeEnumJsonSerializableReadableReversedReadableStringableThrowableResolvers
ChainedFirstMatchRecursionStringWrappers
SymfonyNormalizer