<?php


namespace Mainto\RpcServer\RpcServer\Definition\Traits;


use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Mainto\RpcServer\RpcServer\RpcDefinition;
use Mainto\RpcServer\RpcServer\Definition\Property;

trait ValidateGetter {
    private ?array $validationRules = null;

    public function getValidationRules (): array {
        if ($this->validationRules === null) {
            $this->validationRules = [];

            /** @var Property $property */
            foreach ($this->properties as $property) {
                if (RpcDefinition::getInstance()->inStructCache($property->type)) {
                    foreach (RpcDefinition::getInstance()->getStruct($property->type)->getValidationRules() as $name => $validation) {
                        $this->validationRules[$property->name.'.'.$name] = $validation;
                    }
                } else {
                    $this->validationRules[$property->name] = $property->getValidation();
                }
            }
        }

        return $this->validationRules;
    }

    /**
     * @param array $params
     * @throws ValidationException
     */
    public function validate(array $params): void {
        $validator = Validator::make($params, $this->getValidationRules(), [], []);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
    }
}