Install via Composer:
composer require 21torr/simple-normalizer
Register the service provider in config/app.php:
'providers' => [
// ...
SimpleNormalizer\SimpleNormalizerServiceProvider::class,
],
First Use Case: Normalize a complex object to JSON with context:
use SimpleNormalizer\Normalizer;
// Basic usage
$normalizer = app(Normalizer::class);
$json = $normalizer->normalize($object, Normalizer::FORMAT_JSON);
// With new ContextBag helper (1.6.0)
$context = new \SimpleNormalizer\ContextBag();
$context->set('group', 'user');
$json = $normalizer->normalize($object, Normalizer::FORMAT_JSON, $context);
Key starting points:
Normalizer facade for quick accessContextBag class for reusable context management$normalizer->normalize($entity, Normalizer::FORMAT_JSON);
$context = new ContextBag(['group' => 'admin', 'depth' => 5]);
$result = $normalizer->normalize($object, Normalizer::FORMAT_JSON, $context);
$normalizer->addNormalizer(new class implements NormalizerInterface {
public function normalize($object, $format, array $context = []) {
// Custom logic
}
});
SimpleNormalizer with Doctrine metadata caching (now optimized in 1.6.0):$normalizer->normalize($entity, Normalizer::FORMAT_JSON, [
'groups' => ['api'],
'use_metadata' => true
]);
ValidJsonVerifier (optimized in 1.6.0):$verifier = new \SimpleNormalizer\ValidJsonVerifier();
$verifier->verify($json, $expectedSchema);
SimpleNormalizer (reduces overhead for repeated calls).ValidJsonVerifier reuses path stack internally (no more allocation per element).(array) cast instead of get_object_vars() for stdClass detection (faster).Stack Traces: All relevant exceptions now include stack traces:
try {
$normalizer->normalize($object);
} catch (\SimpleNormalizer\NormalizationFailedException $e) {
$e->getTraceAsString(); // Full stack trace
}
Max Depth Guard: Added default max-depth of 128 to prevent DoS via deep nesting. Override via context:
$context->set('max_depth', 256);
ContextBag for shared state).$context['handled'] = [];
use_metadata option (caching helps here).Custom Context: Extend ContextBag for project-specific context handling:
class ProjectContextBag extends ContextBag {
public function setProjectId(int $id) { /* ... */ }
}
Normalizer Decorators: Wrap existing normalizers for pre/post-processing:
$normalizer->addNormalizer(new class implements NormalizerInterface {
public function __construct(private NormalizerInterface $decorated) {}
public function normalize($object, $format, array $context) {
$result = $this->decorated->normalize($object, $format, $context);
return $this->postProcess($result);
}
});
Exception Handling: Catch NormalizationFailedException for granular error handling (now with stack traces).
catch (NormalizationFailedException $e) {
$path = $e->getPath(); // e.g., ['user', 'address', 'city']
$value = $e->getValue();
}
How can I help you explore Laravel packages today?