<?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;

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

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

    /**
     * {@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->formHelper->handleSubmit())) {
            $event->setResponse($response);
        }

    }

}