<?php

/**
 * Copyright (c) 2025 Bruno Meilick
 * All rights reserved.
 *
 * This file is part of Kirby Turbo and is proprietary software.
 * Unauthorized copying, modification, or distribution is prohibited.
 */

namespace Bnomei;

use Kirby\Cache\Value;

class TurboValue extends Value
{
    public function toJson(): string
    {
        if (extension_loaded('msgpack')) {
            return msgpack_pack($this->toArray());
        }

        if (extension_loaded('igbinary')) {
            return igbinary_serialize($this->toArray()) ?: '';
        }

        return parent::toJson(); // TODO: Change the autogenerated stub
    }

    public static function fromJson(string $json): ?static
    {
        if (extension_loaded('msgpack')) {
            $data = msgpack_unpack($json);
            if (is_array($data)) {
                return parent::fromArray($data);
            }
        }

        if (extension_loaded('igbinary')) {
            $data = igbinary_unserialize($json);
            if (is_array($data)) {
                return parent::fromArray($data);
            }
        }

        return parent::fromJson($json);
    }
}
