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

namespace FiloBlu\Esb\Helper;

use Magento\Framework\ObjectManagerInterface;
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)
    {
        //error_log(__METHOD__);
        try {
            if ($this->isSerialized($value)) {
                $unserializer = $this->objectManager->get(\Magento\Framework\Unserialize\Unserialize::class);
            } else {
                if (class_exists(\Magento\Framework\Serialize\Serializer\Json::class)) {
                    $unserializer = $this->objectManager->get(\Magento\Framework\Serialize\Serializer\Json::class);
                } else {
                    return [];
                }
            }

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

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