<?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 RuleChild message in Cucumber's message protocol
 * @see https://github.com/cucumber/messages
 *
 * A child node of a `Rule` node */
final class RuleChild implements JsonSerializable
{
    use JsonEncodingTrait;

    /**
     * Construct the RuleChild with all properties
     *
     */
    public function __construct(
        public readonly ?Background $background = null,
        public readonly ?Scenario $scenario = null,
    ) {
    }

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

        return new self(
            isset($arr['background']) ? Background::fromArray($arr['background']) : null,
            isset($arr['scenario']) ? Scenario::fromArray($arr['scenario']) : null,
        );
    }

    /**
     * @psalm-assert array{background?: array} $arr
     */
    private static function ensureBackground(array $arr): void
    {
        if (array_key_exists('background', $arr) && !is_array($arr['background'])) {
            throw new SchemaViolationException('Property \'background\' was not array');
        }
    }

    /**
     * @psalm-assert array{scenario?: array} $arr
     */
    private static function ensureScenario(array $arr): void
    {
        if (array_key_exists('scenario', $arr) && !is_array($arr['scenario'])) {
            throw new SchemaViolationException('Property \'scenario\' was not array');
        }
    }
}
