<?php

namespace Sibs\Stargate\Utils;

defined('ABSPATH') || exit;

class SibsObjectify
{
    /**
     * Json Mapper.
     *
     * @param mixed $value
     * @param bool  $recursive
     *
     * @return mixed
     */
    public static function json_mapper($value, $recursive = true)
    {
        if (
            !empty($value) && is_string($value)
            && $decoded = json_decode($value, true)
        ) {
            return $decoded;
        }
        if (is_array($value) && $recursive) {
            return array_map('\Sibs\Stargate\Utils\SibsObjectify::json_mapper', $value);
        }

        return $value;
    }

    /**
     * Json Mapper No Recursive.
     *
     * @param mixed $value
     *
     * @return mixed
     */
    public static function json_mapper_norecurse($value)
    {
        return self::json_mapper($value, false);
    }

    /**
     * Json to Array.
     *
     * @param array $array
     * @param bool  $recursive
     *
     * @return array
     */
    public static function json_to_array($array, $recursive = true)
    {
        // if $array is not an array, let's make it array with one value of
        // former $array.
        if (!is_array($array)) {
            $array = [$array];
        }

        return array_map(
            $recursive ? '\Sibs\Stargate\Utils\SibsObjectify::json_mapper'
                : '\Sibs\Stargate\Utils\SibsObjectify::json_mapper_norecurse',
            $array
        );
    }
}
