<?php
/**
 * Scan for references to Forms
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\ContentScan;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use VisualM\CmsBundle\ContentScan\ContentHandlerInterface;

/**
 * Scan for references to Forms
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class Form extends ContainerAware implements ContentHandlerInterface, ContainerAwareInterface
{

    /**
     * {@inheritDoc}
     */
    public function getPriority()
    {
        return ContentHandlerInterface::PRIORITY_LOW;
    }

    /**
     * {@inheritDoc}
     */
    public function handle($content)
    {
        $ignore = [];
        $container = $this->container;

        $content = preg_replace_callback('/\[form\|([a-z_\-0-9]+)\]/', function($matches) use (&$ignore, $container) {

            if (in_array($matches[1], $ignore)) {
                return $matches[0];
            }

            $form_manager = $container->get('visualm.form.manager.form');
            $form_helper = $container->get('visualm.form.helper.form');

            if (null === ($form = $form_manager->getFirst([ 'referentie' => $matches[1] ]))) {
                $ignore[] = $matches[1];
                return $matches[0];
            }

            $form_helper = $container->get('visualm.form.helper.form');
            return $form_helper->renderForm($form);

        }, $content);


        return $content;
    }

}
