<?php

namespace Velis\Mvc\Controller\Listeners;

use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use Velis\Mvc\Controller\Exception\FormValidationException;
use Velis\Mvc\Controller\Listeners\Concrete\AbstractListener;
use Velis\Mvc\Validators\FormValidatorFactory;

class ValidateFormParamsListener extends AbstractListener
{
    public function __construct(protected Event $event, protected readonly Dispatcher $dispatcher)
    {
    }

    /**
     * @throws FormValidationException
     */
    public function handle(): void
    {
        $validatorFactory = new FormValidatorFactory(
            $this->dispatcher->getActionName(),
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getModuleName()
        );

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

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