1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 
<?php

namespace SAREhub\Commons\Misc;

/**
 * Class for operate on custom configurations
 */
class Parameters implements \JsonSerializable
{

    /**
     * @var array
     */
    private $parameters;

    public function __construct(array $parameters)
    {
        $this->parameters = $parameters;
    }

    public static function createFlatten($parameters)
    {
        return new Parameters(ArrayHelper::flatten($parameters));
    }

    /**
     * @param string $json
     * @return self
     */
    public static function createFromJson($json)
    {
        return new self(json_decode($json, true));
    }

    /**
     * @param string $name
     * @param mixed $default
     * @return mixed
     */
    public function get($name, $default = null)
    {
        return ($this->has($name)) ? $this->parameters[$name] : $default;
    }

    public function getRequired($name)
    {
        if ($this->has($name)) {
            return $this->parameters[$name];
        }

        throw new NotFoundParameterException("Required parameter doesn't exists: $name");
    }

    /**
     * @param string $name
     * @param array $default
     * @return self
     * @throws \Exception
     */
    public function getAsMap($name, array $default = [])
    {
        $parameters = $this->get($name, $default);
        if (is_array($parameters)) {
            return new self($parameters);
        }

        throw new ParameterException("Parameter isn't array: $name");
    }

    /**
     * @param $name
     * @return self
     * @throws \Exception
     */
    public function getRequiredAsMap($name)
    {
        $parameters = $this->getRequired($name);
        if (is_array($parameters)) {
            return new self($parameters);
        }

        throw new ParameterException("Parameter isn't array: $name");
    }

    /**
     * @param $name
     * @return bool
     */
    public function has($name)
    {
        return isset($this->parameters[$name]);
    }

    /**
     * @return array
     */
    public function getAll()
    {
        return $this->parameters;
    }

    /**
     * @return array
     */
    function jsonSerialize()
    {
        return $this->getAll();
    }
}