PHP code example of haskel / map-serializer

1. Go to this page and download the library: Download haskel/map-serializer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

haskel / map-serializer example snippets


/** Define a class that you want to serialize */
class User 
{
    private $id;
    private $name;
    private status = 0;
    private $role;
    private $phone;
    private $mail;
    private group;
    
    public function __construct($id, $name, $role)
    {
        $this->id = $id;
        $this->name = $name;
        $this->role = $role;
    }
    
    /**
     * ... Boring code with getters and setters ...
     */
}

/** Specify the schema */
$schema = [
    'id'     => 'int',
    'name'   => 'string',
    'status' => 'int',
    'role'   => 'string',
];
/** Add this schema definition, uniq schema name and class name to serializer */
$serializer->addSchema(User::class, 'default', $schema);

/** serialize some instance of the class */
$result = $serializer->serialize(new User('Alice', 'user'));

use Haskel\MapSerializer\Serializer;

$serializer = new Serializer();

$schemas = [
    'default' => [
        'id'     => 'int',
        'name'   => 'string',
        'status' => 'int',
        'role'   => 'string',
    ],
    'short' => [
        'id'   => 'int',
        'name' => 'string',
    ]
];
foreach ($orderSchemas as $schemaName => $schema) {
    $serializer->addSchema(User::class, $schemaName, $schema);
}

$users = [
    new User(1, 'Alice'),
    new User(2, 'Bob'),
];
$result = $serializer->serialize($users, 'short');

use Haskel\MapSerializer\Serializer;

$serializer = new Serializer();

$userSchema = [
    'id'     => 'int',
    'name'   => 'string',
    'group'  => 'short',
];
$groupSchema = [
  'id'   => 'int',
  'name' => 'string',
];
$serializer->addSchema(User::class, 'default', $userSchema);
$serializer->addSchema(Group::class, 'short', $groupSchema);

$group = new Group('sales');
$user = new User('Alice');
$user->addToGroup($group);

$result = $serializer->serialize($user);

interface Formatter
{
    public function format($value, $schemaName);
}

class DatetimeFormatter implements Formatter
{
    public function format($value, $schemaName)
    {
        if (!$value instanceof DateTime) {
            throw new FormatterException(sprintf('wrong value type'));
        }

        switch ($schemaName) {
            case 'default':
            case 'datetime':
            default:
                return $value->format("Y-m-d H:i:s");

            case 'date':
                return $value->format('Y-m-d');

            case 'time':
                return $value->format('H:i:s');
        }
    }
}

use Haskel\MapSerializer\Formatter\DatetimeFormatter;
use Haskel\MapSerializer\Serializer;

$serializer = new Serializer();
$serializer->addFormatter(new DatetimeFormatter());

$datetime = new DateTime('2015-10-21 12:00:00');
$serializer->format($datetime, 'date');

final class AppEntityUserExtractor extends \Haskel\MapSerializer\EntityExtractor\BaseExtractor
{
    /** @var \App\Entity\User */
    protected $entity;

    protected function extract()
    {
        return [
            "id" => $this->entity->getId(),
            "name" => $this->entity->getName(),
        ];
    }
    
    public function exists($fieldName)
    {
        if (count($this->fields) === 0) {
            $this->fields = $this->extract();
        }

        return array_key_exists($fieldName, $this->fields);
    }

    /**
     * @param $fieldName
     *
     * @return mixed
     */
    public function get($fieldName)
    {
        if (count($this->fields) === 0) {
            $this->fields = $this->extract();
        }

        return $this->fields[$fieldName];
    }
}

namespace Haskel\MapSerializer\EntityExtractor;

interface Extractor
{
    public function get($fieldName);
    public function exists($fieldName);
}

class UserExtractor implements Extractor 
{
    public function get($fieldName)
    {
        return 42;
    }
    
    public function exists($fieldName)
    {
        return true;
    }
}

$schema = [
    'id'     => 'int',
    'name'   => 'string',
    'status' => 'int',
    'role'   => 'string',
];
$serializer->addSchema(User::class, 'default', $schema);
$serializer->addExtractor(User::class, 'default', UserExtractor::class);
$result = $serializer->serialize(new User('Alice'));