andreiavrammsd/serializer

This package is abandoned and no longer maintained. No replacement package was suggested.

JSON string to object. Object/array to JSON.

v1.0.0 2019-12-28 12:02 UTC

This package is auto-updated.

Last update: 2024-02-29 03:43:44 UTC


README

build

Very basic serializer/unserializer/toarray. Also transforms data by types and/or callbacks.

Currently handles only JSON.

Install

composer require andreiavrammsd/serializer

Usage

$input = '{...}';
$class = ObjectClass::class;

$serializer = Serializer\SerializerBuilder::instance()->build();
// OR
$serializer = Serializer\Factory::create();

$object = $serializer->unserialize($input, $class);

$serializer->serialize($object);

$serializer->toArray($object);

See examples and tests.

Property annotations (all annotations are optional)

  • Property: name of key in input. If not set, the variable name is used.
  • Type: If set, the value will be transformed as follows
    • int, float, string, bool, array: will cast value to the type.
    • collection: value will be wrapped by a countable iterator with array access.
    • DateTime: creates a DateTime object, formatting the value by formats given as arguments; first valid format is used.
    • Fully qualified class name: the value will be parsed into the given class.
    • Array of class: the value will be parsed into an array with each element parsed into the given class.
    • Collection of class: the value will be parsed into a collection with each element parsed into the given class.
  • Callback: A callable (function or class method) is accepted (with optional parameters). The value will be passed to the callable (with the optional parameters, if set), and the new value will be the result of the callable.

Examples

@Serializer\Property("first_name")

@Serializer\Type("int")
@Serializer\Type("float")
@Serializer\Type("string")
@Serializer\Type("bool")
@Serializer\Type("array")
@Serializer\Type("collection")
@Serializer\Type("DateTime","Y-m-d H:i", "Y-m-d")
@Serializer\Type("Entity\User")
@Serializer\Type("array[Entity\User]")
@Serializer\Type("collection[Entity\User]")

@Serializer\Callback("strtoupper")
@Serializer\Callback("substr", "0", "3")
@Serializer\Callback("[User\NameFormatter, firstName]")
@Serializer\Callback("[User\NameFormatter, lastName]", "1", "3")

@Serializer\IgnoreNull() // Ignores null values when serializing or converting to array.

Object class annotations

  • Collection: a class annotated with Collection and extending the Collection class will be a collection class with its items of the specified class type.

Examples

@Serializer\Collection("Entity\User")

Development

  • Requirements: Docker, Make
  • Build and install dev container:
    • make build PHPVERSION=7.4
    • make install PHPVERSION=7.4
  • Run QA tools: make PHPVERSION=7.4
  • Work inside dev container: make run PHPVERSION=7.4 then make localqa
  • Remove Docker image: make clean PHPVERSION=7.4

Developed with PhpStorm

JetBrains