<?php
/**
 * @author Ulrich Hecht <ulrich.hecht@hecht-software.de>
 * @date 02/10/2017
 */

namespace AppBundle\Twig;


class AppExtension extends \Twig_Extension
{
    protected $environment;
    private $template;

    public function __construct(\Twig_Environment $env)
    {
        $this->environment = $env;
    }

    public function getFilters()
    {
        return [
            'stripslashes' => new \Twig_SimpleFilter('stripslashes', [$this, 'stripslashesFilter'], [
                'is_safe' => ['html']
            ]),
        ];
    }

    public function getFunctions()
    {
        return [
            'form_field' => new \Twig_SimpleFunction('form_field', [$this, 'formField'], [
                'is_safe' => ['html']
            ]),
            'form_field_pho' => new \Twig_SimpleFunction('form_field_pho', [$this, 'formFieldPho'], [
                'is_safe' => ['html']
            ]),
        ];
    }

    public function stripslashesFilter($v)
    {
        return stripslashes($v);
    }

    public function formField($form, $label = null, $opt = null)
    {
        $this->template = $this->environment->loadTemplate( '::default/form/helpers.html.twig' );
        return $this->template->renderBlock('form_field', [
            'form' => $form,
            'label' => $label,
            'opt' => $opt
        ]);
    }

    /**
     * Form field with placeholder only
     *
     * @param $form
     * @param null $label
     * @param null $opt
     *
     * @return mixed
     */
    public function formFieldPho($form, $label = null, $opt = [])
    {
        $this->template = $this->environment->loadTemplate( '::default/form/helpers.html.twig' );

        return $this->template->renderBlock('form_field_pho', [
            'form' => $form,
            'label' => $label,
            'opt' => $opt
        ]);
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'app_extension';
    }
}