<?php
/**
 * Class FormField
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 2017-03-14
 */
namespace Mtc\Core;

use Twig\Environment;

/**
 * Class FormField
 *
 * Form Field generator function.
 * Allows generating base input fields
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 2017-03-14
 */
class FormField
{
    /**
     * @var string[] currently supported fields and which templates they use
     */
    private static $supported_fields = [
        'text' => 'text',
        'email' => 'text',
        'tel' => 'text',
        'password' => 'text',
        'number' => 'text',
        'textarea' => 'textarea',
        'radio' => 'radio',
        'select' => 'select',
        'checkbox' => 'checkbox',
        'file' => 'text',
    ];

    /**
     * Render a form field based on given $options.
     * This ensures all form fields are inline with general mtc styling.
     * Expected fields in options:
     * - type
     * - value
     * - id
     * - label
     * - errors (array)
     * - class (optional)
     * - field_value (checkbox|radio)
     * - values (select)
     *
     * @param string[] $options list of rendering params
     * @param Environment $twig
     * @return string|void html of input field|nothing if template not supported
     */
    public static function renderField(Array $options, Environment $twig)
    {
        if (empty($options['type'])) {
            return;
        }

        if (!array_key_exists($options['type'], self::$supported_fields)) {
            return;
        }

        $template = self::$supported_fields[$options['type']];
        return $twig->render("includes/input_fields/{$template}.twig", $options);
    }
}
