Simple Normalizer
The Simple Normalizer is a fast and simple normalizer, optimized for high performance.
Installation
Install the library using composer:
composer require 21torr/simple-normalizer
When using Symfony Flex there is nothing else to do, otherwise you need to manually load the bundle.
Usage
The bundle provides a SimpleNormalizer service, that you can use to normalize your data:
$normalizer->normalize($value, $context);
// or to make sure that you get an array back
$normalizer->normalizeArray($value, $context);
// or when requiring a map (see below)
$normalizer->normalizeMap($value, $context);
The normalizer will automatically keep all scalar values and traverse all arrays. For every object it encounters, it will use a custom normalizer to normalize the content.
Only a few objects are supported out of the box:
- backed enums are normalized to their value,
- empty
stdClassobjects are kept as-is (see Map Handling), ValueWithContextis normalized to its wrapped value.
For every other object in the data tree, you need to register a custom object normalizer.
List Handling
When normalizing list-arrays (numerical arrays without gaps), the normalizer will automatically filter out values that are normalized to null.
$normalizer->normalize(["a", null, "b"]);
// will normalize to
["a", "b"]
Map Handling
The normalizer is intended to prepare data for serialization. So it is supposed to be used with any data, and the result can then be transformed to JSON using json_serialize().
When normalizing key-value-maps however, there is an issue with empty arrays:
[
"test" => "abc"
]
will be normalized + serialized to
{"test": "abc"}
However an empty map will be normalized to an array:
[]
That is due to the fact, that json_encode() can't know whether you want an object or an array here. For PHP that doesn't matter: both will decode to the same data structure. However, in JavaScript they will decode to either [] or {}, which are not compatible.
So for this case, you can use ->normalizeMap(), which will return stdClass for the case of an empty array, as this will be JSON encoded to {}.
You can also return an empty new \stdClass() from your own normalizers: empty stdClass objects are passed through unchanged. Non-empty stdClass objects are not supported.
Backed Enums
21torr/simple-normalizer v1.7.0Backed enums are normalized to their value, so you don't need a custom normalizer for them:
enum Status : string
{
case Draft = "draft";
case Published = "published";
}
$normalizer->normalize([
"status" => Status::Published,
]);
// will normalize to
["status" => "published"]
If you need a different output for a specific enum, register a custom object normalizer for it. A registered normalizer always takes precedence over the default enum handling.
Pure enums (without a backing type) are not supported automatically, as they have no value. You need to register a custom normalizer for them.
Object Normalizers
For every object you want to normalize, you need to register a custom normalizer.
use Torr\SimpleNormalizer\Normalizer\SimpleObjectNormalizerInterface;
class MyObjectNormalizer implements SimpleObjectNormalizerInterface
{
/**
* @inheritDoc
*/
public function normalize (object $value, array $context, SimpleNormalizer $normalizer) : mixed
{
assert($value instanceof MyObject);
// implement your normalization here
return [
"title" => $value->getTitle(),
// ...
];
}
/**
* @inheritDoc
*/
public static function getNormalizedType () : string
{
return MyObject::class;
}
}
The class is automatically configured when using Symfonys autoconfiguration.
Your normalize() method gets passed the normalizer, so you can recursively normalize content:
public function normalize (object $value, array $context, SimpleNormalizer $normalizer) : mixed
{
assert($value instanceof MyObject);
// implement your normalization here
return [
"image" => $normalizer->normalize($value->getImage(), $context),
// ...
];
}
If Doctrine ORM is installed, the normalizer resolves the class names of Doctrine proxies to the real entity class. So a normalizer registered for your entity class is also used for lazy-loaded proxies of that entity.
Failing Normalization
If your normalizer can't normalize a value, throw a NormalizationFailedException:
use Torr\SimpleNormalizer\Exception\NormalizationFailedException;
public function normalize (object $value, array $context, SimpleNormalizer $normalizer) : mixed
{
assert($value instanceof MyObject);
if (null === $value->getTitle())
{
throw new NormalizationFailedException("Can't normalize object without title.");
}
// ...
}
The normalizer adds the normalization stack to the exception, so you can see where in the data tree the error happened.
Context
The recursive normalization process uses an additional $context array, that you can use to modify the normalization behavior or add global context for normalization (like a locale that the data is normalized for).
$normalizer->normalize($value, [
"locale" => "de",
]);
And then use it in your normalizers:
public function normalize (object $value, array $context, SimpleNormalizer $normalizer) : mixed
{
assert($value instanceof MyObject);
$locale = $context["locale"] ?? "en";
// ...
}
Context Bag
21torr/simple-normalizer v1.6.0To read context values in a type-safe way, you can wrap the context in a ContextBag:
use Torr\SimpleNormalizer\Context\ContextBag;
public function normalize (object $value, array $context, SimpleNormalizer $normalizer) : mixed
{
assert($value instanceof MyObject);
$bag = new ContextBag($context);
// required values: throw if the key is missing or has the wrong type
$locale = $bag->getString("locale");
$site = $bag->getObject("site", Site::class);
// optional values: return `null` if the key is missing
$preview = $bag->getOptionalBool("preview") ?? false;
// ...
}
There are getters for all supported types, each with a required and an optional variant:
| Type | Required | Optional |
|---|---|---|
| any | get() | getOptional() |
| string | getString() | getOptionalString() |
| int | getInt() | getOptionalInt() |
| float | getFloat() | getOptionalFloat() |
| bool | getBool() | getOptionalBool() |
| array | getArray() | getOptionalArray() |
| object | getObject() | getOptionalObject() |
The bag also provides has(), keys() and all(), and you can iterate and count it.
The required getters throw a MissingContextException if the key is missing. All typed getters throw an InvalidContextTypeException if the value has the wrong type. If you don't catch them in your normalizer, the normalizer wraps them in a NormalizationFailedException with the normalization stack.
Passing Context to Nested Values
To change the context only for a part of the data tree, wrap the value in a ValueWithContext:
use Torr\SimpleNormalizer\Data\ValueWithContext;
return [
"title" => $value->getTitle(),
"author" => new ValueWithContext($value->getAuthor(), [
"include_email" => false,
]),
];
The wrapped value is normalized with the current context, merged with the given context. Keys in the given context replace existing keys.
Returning Invalid Values
All values in the generated JSON must be of valid JSON types, that includes: scalars, arrays and empty objects.
Empty objects are allowed, as JSON encoding an empty array1 will always encode to [], but json_encode(new stdClass()) === "{}".
The normalizer doesn't normalize the values your normalizers return again. So if a normalizer returns an invalid value, it ends up in the result (and in the end is passed to json_encode()):
class MyNormalizer implements SimpleObjectNormalizerInterface
{
public function normalize (object $value, array $context, SimpleNormalizer $normalizer) : mixed
{
assert($value instanceof MyObject);
// this object is not normalized and ends up in the result
return new SomeObject();
}
}
In debug mode, the normalizer verifies the complete result and throws an IncompleteNormalizationException with the path to the first invalid value:
Found a JSON-incompatible value when normalizing. Found 'SomeObject' at path '$.teaser.image', but expected only scalars, arrays and empty objects.
The check is disabled in production, so there is no performance overhead.
Error Handling
All exceptions of the normalizer implement NormalizerExceptionInterface.
If the normalizer encounters a value it can't normalize, it throws an exception that contains the normalization stack: the types from the failing value up to the root value.
$normalizer->normalize([
"teaser" => [
"images" => [new Image()],
],
]);
This throws an ObjectTypeNotSupportedException (as there is no normalizer for Image) with the message:
Can't normalize type 'Image' in stack Image > array > array > array
You can also read the stack with getNormalizationStack():
| Exception | Thrown when |
|---|---|
ObjectTypeNotSupportedException | no normalizer is registered for an object |
UnsupportedTypeException | the value has an unsupported type (like resources) |
MaxDepthExceededException | the value is nested too deeply |
NormalizationFailedException | a normalizer failed or a context value is missing or invalid |
Each call of $normalizer->normalize() tracks its own stack. So when you call the normalizer from inside your object normalizer, the stack only contains the part of the tree below that call.
Maximum Depth
21torr/simple-normalizer v1.6.0To protect against excessively deep or recursive data, the normalizer stops at a nesting depth of 128 and throws a MaxDepthExceededException. The same limit applies to the verification in debug mode.
Before v1.7.1, the normalizer threw an UnsupportedTypeException when the max depth was exceeded. Since v1.7.1 it throws a MaxDepthExceededException. If you catch the exception explicitly, update your code or catch NormalizerExceptionInterface instead.
Testing
To test your normalizers, use the SimpleNormalizerTestTrait. It creates a SimpleNormalizer with only the normalizers you pass:
use PHPUnit\Framework\TestCase;
use Torr\SimpleNormalizer\Test\SimpleNormalizerTestTrait;
final class MyObjectNormalizerTest extends TestCase
{
use SimpleNormalizerTestTrait;
public function testNormalize () : void
{
$normalizer = $this->createNormalizer(
new MyObjectNormalizer(),
new ImageNormalizer(),
);
self::assertSame(
["title" => "Example"],
$normalizer->normalize(new MyObject("Example")),
);
}
}