<?php

declare(strict_types=1);

/**
 * This code was auto-generated by {this script}[https://github.com/cucumber/messages/blob/main/jsonschema/scripts/codegen.rb]
 */

namespace Cucumber\Messages;

use JsonSerializable;
use Cucumber\Messages\DecodingException\SchemaViolationException;

/**
 * Represents the Comment message in Cucumber's message protocol
 * @see https://github.com/cucumber/messages
 *
 * A comment in a Gherkin document */
final class Comment implements JsonSerializable
{
    use JsonEncodingTrait;

    /**
     * Construct the Comment with all properties
     *
     */
    public function __construct(

        /**
         * The location of the comment
         */
        public readonly Location $location = new Location(),

        /**
         * The text of the comment
         */
        public readonly string $text = '',
    ) {
    }

    /**
     * @throws SchemaViolationException
     *
     * @internal
     */
    public static function fromArray(array $arr): self
    {
        self::ensureLocation($arr);
        self::ensureText($arr);

        return new self(
            Location::fromArray($arr['location']),
            (string) $arr['text'],
        );
    }

    /**
     * @psalm-assert array{location: array} $arr
     */
    private static function ensureLocation(array $arr): void
    {
        if (!array_key_exists('location', $arr)) {
            throw new SchemaViolationException('Property \'location\' is required but was not found');
        }
        if (array_key_exists('location', $arr) && !is_array($arr['location'])) {
            throw new SchemaViolationException('Property \'location\' was not array');
        }
    }

    /**
     * @psalm-assert array{text: string|int|bool} $arr
     */
    private static function ensureText(array $arr): void
    {
        if (!array_key_exists('text', $arr)) {
            throw new SchemaViolationException('Property \'text\' is required but was not found');
        }
        if (array_key_exists('text', $arr) && is_array($arr['text'])) {
            throw new SchemaViolationException('Property \'text\' was array');
        }
    }
}
