Skip to content

Instantly share code, notes, and snippets.

@phcostabh
Created August 16, 2013 15:03
Show Gist options
  • Save phcostabh/6250689 to your computer and use it in GitHub Desktop.
Save phcostabh/6250689 to your computer and use it in GitHub Desktop.
<?php
/**
*
*/
class FormHelper
{
/**
* Controla os indices de metadados
* @var int
*/
private static $index = 0;
/**
* Cria inputs do formulário
*
* @param mixed $type
* @param mixed $name
* @param bool $value
* @param bool $attributes
* @return string
*/
public static function input($type, $name, $value = null, $attributes = array())
{
$html = static::hiddenMeta($name);
$name = 'extras['.static::$index.'][dado]';
$attributes = array_merge(compact('type', 'name', 'value'), $attributes);
$html .= '<input '.static::attributify($attributes).'/>' . PHP_EOL;
static::$index++;
return $html;
}
/**
* Inprime o input hidden com o nome do meta.
*
* @param string $name
* @return string
*/
public static function hiddenMeta($name)
{
return '<input type="hidden" name="extras['.static::$index.'][meta]" value="'.static::escape($name).'"/>'.PHP_EOL;
}
/**
* Cria o text input
*
* @param mixed $name
* @param mixed $value
* @param array $attributes
* @return string
*/
public static function text($name, $value = null, $attributes = array())
{
return static::input('text', $name, $value, $attributes);
}
/**
* Cria checkbox input
*
* @param mixed $name
* @param mixed $value
* @param array $attributes
* @return string
*/
public static function checkbox($name, $value = null, $attributes = array())
{
return static::input('checkbox', $name, $value, $attributes);
}
/**
* Transforma o array de attributes em uma string
*
* @param array $attributes
* @return string
*/
public static function attributify($attributes = array())
{
$html = '';
foreach ($attributes as $key => $value) {
if (is_numeric($key)) {
$key = $value;
}
if (!is_null($value)) {
$html .= $key.'="'.static::escape($value).'" ';
}
}
return $html;
}
/**
* Escapa HTML entities na string.
*
* @param mixed $value
* @return string
*/
public static function escape($value)
{
return htmlentities($value, ENT_QUOTES, 'UTF-8', false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment