<?php
/**
 * Form KernelEvent Listener
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use VisualM\FormBundle\Helper\FormHelper;
use VisualM\FormBundle\Helper\SubmitHandler;

/**
 * Form KernelEvent Listener
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class FormKernelEventListener
{
    /**
     * Form SubmitHandler
     * @var SubmitHandler
     */
    private $submitHandler;

    /**
     * Constructor
     *
     * @param FormHelper $submitHandler Form Helper
     */
    public function __construct(SubmitHandler $submitHandler)
    {
        $this->submitHandler = $submitHandler;
    }

    /**
     * {@inheritdoc}
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        // Only handle master requests
        if (!$event->isMasterRequest()) {
            return;
        }

        // Only handle POST requests
        $request = $event->getRequest();
        if ($request->getMethod() !== 'POST') {
            return;
        }

        // Handle Submit in FormHelper,
        // if response is returned return it
        if (null !== ($response = $this->submitHandler->handleSubmit($request))) {
            $event->setResponse($response);
        }

    }

}