<?php

namespace FiloBlu\Flow\Helper;

use Magento\Framework\App\ObjectManager;
use function serialize;
use function unserialize;
use Magento\Framework\Serialize\SerializerInterface;

/**
 * Class SerializeHelper
 * @package FiloBlu\Flow\Helper
 */
class SerializeHelper
{
    /**
     * @var bool
     */
    private static $_useSerializer = false;

    /**
     * @var null
     */
    private static $_serializer;

    /**
     * @var bool
     */
    private static $_ready = false;

    /**
     * SerializeHelper constructor.
     */
    private function __construct()
    {
    }

    /**
     * @param mixed $data
     * @return string
     */
    public static function serialize($data)
    {
        self::init();

        if (self::$_useSerializer) {
            return self::$_serializer->serialize($data);
        }

        return serialize($data);
    }

    /**
     *
     */
    protected static function init()
    {
        if (self::$_ready === true) {
            return;
        }

        if (interface_exists(SerializerInterface::class)) {
            self::$_useSerializer = true;
            self::$_serializer = ObjectManager::getInstance()->create('Magento\Framework\Serialize\SerializerInterface');
        }

        self::$_ready = true;
    }

    /**
     * @param $string
     * @return mixed
     */
    public static function unserialize($string)
    {
        self::init();

        if (self::$_useSerializer) {
            return self::$_serializer->unserialize($string);
        }

        return unserialize($string);
    }

    /**
     * Private clone method to prevent cloning of the instance of this class.
     *
     * @return void
     */
    final public function __clone()
    {
    }

    /**
     * Private unserialize method to prevent unserializing of the instance of
     * this class.
     *
     * @return void
     */
    final public function __wakeup()
    {
    }
}
