<?php

namespace Velis\Mvc\Controller\RestRequestHandler;

use Phalcon\Http\RequestInterface;
use Phalcon\Mvc\Dispatcher;
use Velis\Filter;
use Velis\Mvc\Controller\Exception\FormValidationException;
use Velis\Mvc\Validators\FormValidatorFactory;

class ValidateFormParams extends AbstractRestRequestHandler
{
    private Filter $params;
    private Dispatcher $dispatcher;

    public function __construct(Filter $params, Dispatcher $dispatcher = null)
    {
        $this->params = $params;
        $this->dispatcher = $dispatcher;
    }

    public function handle(RequestInterface $request): void
    {
        $validatorFactory = new FormValidatorFactory(
            $this->dispatcher->getActionName(),
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getModuleName()
        );

        $validator = $validatorFactory->getValidator();
        $validator->validate($this->params->getArrayCopy());

        if ($validator->hasErrors()) {
            throw new FormValidationException($validator->getErrors());
        }

        $this->handleNext($request);
    }
}
