<?php

/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 04/11/19
 * Time: 8.56
 */

namespace FiloBlu\Rma\Helper;

use Exception;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Unserialize\Unserialize;
use Psr\Log\LoggerInterface;

/**
 *
 */
class SerializerHelper
{
    /**
     * @var ObjectManagerInterface
     */
    protected $objectManager;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * SerializerHelper constructor.
     * @param ObjectManagerInterface $objectManager
     * @param LoggerInterface $logger
     */
    public function __construct(ObjectManagerInterface $objectManager, LoggerInterface $logger)
    {
        $this->objectManager = $objectManager;
        $this->logger = $logger;
    }

    /**
     * @param $value
     * @return mixed
     */
    public function unserialize($value)
    {
        try {
            if ($this->isSerialized($value)) {
                $unserializer = $this->objectManager->get(Unserialize::class);
            } else {
                if (class_exists(Json::class) && !empty($value)) {
                    $unserializer = $this->objectManager->get(Json::class);
                } else {
                    return [];
                }
            }

            return $unserializer->unserialize($value);
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
            return [];
        }
    }

    /**
     * @param $value
     * @return bool
     */
    protected function isSerialized($value)
    {
        if(empty($value)){
            return $value;
        }
        return (bool)preg_match('/^((s|i|d|b|a|O|C):|N;)/', $value);
    }
}
