<?php

namespace Sibs2;

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;
        } elseif (is_array($value) && $recursive) {
            return array_map('\\Sibs2\\sibsObjectify::json_mapper', $value);
        } else {
            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 ? '\\Sibs2\\sibsObjectify::json_mapper'
                : '\\Sibs2\\sibsObjectify::json_mapper_norecurse',
            $array
        );
    }
}
