<?php

namespace Simulador\Models;

use JsonMapper;
use JsonMapper_Exception;

class BaseModel
{

    /**
     * @param object $value
     * @return static
     */
    private static function fromJSONObject(object $value)
    {

        $mapper = new JsonMapper();
        $mapper->bStrictNullTypes = false;
        try {
            /** @noinspection PhpIncompatibleReturnTypeInspection */
            return $mapper->map($value, new static());
        } catch (JsonMapper_Exception $e) {
            return new static();
        }
    }

    /**
     * @param array $value
     * @return static[]
     */
    private static function fromJSONArray(array $value): array
    {

        $mapper = new JsonMapper();
        $mapper->bStrictNullTypes = false;
        try {
            return $mapper->mapArray($value, array(), static::class);
        } catch (JsonMapper_Exception $e) {
//            var_dump($e->getMessage());
            return [];
        }
    }

    /**
     * @param $value
     * @return static|static[]
     */
    public static function fromArray($value)
    {
        return static::fromJSON(json_encode($value));
    }

    /**
     * @param string $json
     * @return static|static[]
     */
    public static function fromJSON(string $json)
    {
        return static::fromObject(json_decode($json, false));
    }

    /**
     * @param object|array $object
     * @return static|static[]
     */
    public static function fromObject($object)
    {

        if (is_array($object)) {
            return static::fromJSONArray($object);
        }
        return static::fromJSONObject($object);
    }

}
