americanreading / object-normalizer
Normalize fields on objects
    v1.1.0
    2015-06-05 21:17 UTC
Requires
- php: >=5.3.0
 
Requires (Dev)
- phpunit/phpunit: ~4.6
 
This package is auto-updated.
Last update: 2025-10-19 12:37:46 UTC
README
Features
- Required fields must be present on the output object, or 
normalizethrows an exception. - Optional fields are added to the output object, if present.
 - Default values can be supplied for fields.
 - Aliases allow you to map field names on the input object to field names on the output object.
 - Modifier callables alter the values for fields.
 - Finalizer callable allows an additional modification after the object is normalized
 
Example
<?php
use AmericanReading\ObjectNormalizer\ObjectNormalizer;
// Begin with an array or object that contains fields we don't want and fields
// with the wrong names.
$input = [
    "id" => 12852,
    "show" => "Bob's Burger",
    "character" => "Gene Belcher",
    "favoriteColor" => "blue"
];
// Create a normalizer.
$normalizer = new ObjectNormalizer();
// Provide the names of the fields the final object should contain.
$normalizer->setRequiredFields(["name", "series")
// List other names for a field that may appear on the input object.
$normalizer->setAlias("name", ["character", "person"])
// Normalize using the settings provided above.
$output = $normalizer->normalize($input);
print_r($output);
/*
    stdClass Object
    (
        [name] => Gene Belcher
        [show] => Bob's Burger
    )
*/
Extended Example
<?php
use AmericanReading\ObjectNormalizer\ObjectNormalizer;
$normalizer = new ObjectNormalizer();
$normalizer
    ->setRequiredFields(["name", "show"])
    ->setOptionalFields(["instrument",  "favoriteColor", "favoriteAnimal"])
    ->setAlias("name", "character")
    ->setDefault("favoriteColor", "blue")
    ->setModifier("favoriteColor", function ($value) {
        if ($value == "green") {
            $value = "red";
        }
        return $value;
    })
    ->setFinalizer(function ($obj) {
        // Add an additional field, only for Gene.
        if ($obj->name === "Gene Belcher") {
            $obj->costume = "Beefsquatch";
        }
        return $obj;
    });
$gene = [
    "id" => 12852,
    "show" => "Bob's Burgers",
    "character" => "Gene Belcher",
    "instrument" => "Casio Keyboard"
];
$normalGene = $normalizer->normalize($gene);
print_r($normalGene);
/*
    stdClass Object
    (
        [name] => Gene Belcher
        [show] => Bob's Burgers
        [instrument] => Casio Keyboard
        [favoriteColor] => blue
    )
*/
$tina = [
    "id" => 12853,
    "show" => "Bob's Burgers",
    "character" => "Tina Belcher",
    "favoriteColor" => "green",
    "favoriteAnimal" => "Horse"
];
$normalTina = $normalizer->normalize($tina);
print_r($normalTina);
/*
    stdClass Object
    (
        [name] => Tina Belcher
        [show] => Bob's Burgers
        [favoriteColor] => red
        [favoriteAnimal] => Horse
    )
*/