<?php

declare(strict_types=1);

namespace App\Modules\Shared\Domain\ValueObject;

use InvalidArgumentException;

abstract class JsonValueObject
{

    protected $value;
    protected string $stringValue;

    public function __construct(string $value)
    {
        $this->value = $this->ensureIsValidJson($value);
        $this->stringValue = $value;
    }

    public function value(): string
    {
        return $this->stringValue;
    }

    private function ensureIsValidJson(string $value)
    {
        $json = json_decode($value);
        if (json_last_error() != JSON_ERROR_NONE) {
            throw new InvalidArgumentException(sprintf('<%s> does not allow the value <%s>.', static::class, $value));
        }
        return $json;
    }
}
