<?php

namespace FiloBlu\Esb\Converter;

use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use RuntimeException;

/**
 * Class JsonToDataObject
 * @package FiloBlu\Esb\Converter
 */
class JsonToDataObject
{
    /**
     * @var DataObjectFactory
     */
    private $dataObjectFactory;

    /**
     * JsonToDataObject constructor.
     * @param DataObjectFactory $dataObjectFactory
     */
    public function __construct(DataObjectFactory $dataObjectFactory)
    {
        $this->dataObjectFactory = $dataObjectFactory;
    }

    /**
     * @param string $jsonString
     * @return DataObject
     */
    public function convert(string $jsonString): DataObject
    {
        if ($jsonString === null || empty($jsonString) || ctype_space($jsonString)) {
            $jsonString = '{}';
        }

        $data = json_decode($jsonString, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException(json_last_error_msg(), json_last_error());
        }

        return $this->dataObjectFactory->create(['data' => $data]);
    }
}
