<?php
namespace fast;
use ArrayAccess;
class Form
{
public function __construct()
{
}
public static function __callStatic($name, $arguments)
{
return call_user_func_array([FormBuilder::instance(), $name], $arguments);
}
}
class FormBuilder
{
protected $csrfToken = array('name' => '__token__');
protected $labels = [];
protected $skipValueTypes = array('file', 'password', 'checkbox', 'radio');
protected $escapeHtml = true;
protected static $instance;
public function __construct()
{
}
public static function instance($options = [])
{
if (is_null(self::$instance)) {
self::$instance = new static($options);
}
return self::$instance;
}
public function setEscapeHtml($escape)
{
$this->escapeHtml = $escape;
}
public function escape($value)
{
if (!$this->escapeHtml) {
return $value;
}
if (is_array($value)) {
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
}
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
}
public function token($name = '__token__', $type = 'md5')
{
if (function_exists('token')) {
return token($name, $type);
}
return '';
}
public function label($name, $value = null, $options = [])
{
$this->labels[] = $name;
$options = $this->attributes($options);
$value = $this->escape($this->formatLabel($name, $value));
return '<label for="' . $name . '"' . $options . '>' . $value . '</label>';
}
protected function formatLabel($name, $value)
{
return $value ?: ucwords(str_replace('_', ' ', $name));
}
public function input($type, $name, $value = null, $options = [])
{
if (!isset($options['name']))
$options['name'] = $name;
$id = $this->getIdAttribute($name, $options);
if (!in_array($type, $this->skipValueTypes)) {
$value = $this->getValueAttribute($name, $value);
$options['class'] = isset($options['class']) ? $options['class'] . ' form-control' : 'form-control';
}
$merge = compact('type', 'value', 'id');
$options = array_merge($options, $merge);
return '<input' . $this->attributes($options) . '>';
}
public function text($name, $value = null, $options = [])
{
return $this->input('text', $name, $value, $options);
}
public function password($name, $options = [])
{
return $this->input('password', $name, '', $options);
}
public function hidden($name, $value = null, $options = [])
{
return $this->input('hidden', $name, $value, $options);
}
public function email($name, $value = null, $options = [])
{
return $this->input('email', $name, $value, $options);
}
public function url($name, $value = null, $options = [])
{
return $this->input('url', $name, $value, $options);
}
public function file($name, $options = [])
{
return $this->input('file', $name, null, $options);
}
public function textarea($name, $value = null, $options = [])
{
if (!isset($options['name']))
$options['name'] = $name;
$options = $this->setTextAreaSize($options);
$options['id'] = $this->getIdAttribute($name, $options);
$value = (string)$this->getValueAttribute($name, $value);
unset($options['size']);
$options['class'] = isset($options['class']) ? $options['class'] . ' form-control' : 'form-control';
$options = $this->attributes($options);
return '<textarea' . $options . '>' . $this->escape($value) . '</textarea>';
}
public function editor($name, $value = null, $options = [])
{
$options['class'] = isset($options['class']) ? $options['class'] . ' editor' : 'editor';
return $this->textarea($name, $value, $options);
}
protected function setTextAreaSize($options)
{
if (isset($options['size'])) {
return $this->setQuickTextAreaSize($options);
}
$cols = array_get($options, 'cols', 50);
$rows = array_get($options, 'rows', 5);
return array_merge($options, compact('cols', 'rows'));
}
protected function setQuickTextAreaSize($options)
{
$segments = explode('x', $options['size']);
return array_merge($options, array('cols' => $segments[0], 'rows' => $segments[1]));
}
public function select($name, $list = [], $selected = null, $options = [])
{
$selected = $this->getValueAttribute($name, $selected);
$options['id'] = $this->getIdAttribute($name, $options);
if (!isset($options['name']))
$options['name'] = $name;
$html = [];
foreach ($list as $value => $display) {
$html[] = $this->getSelectOption($display, $value, $selected);
}
$options['class'] = isset($options['class']) ? $options['class'] . ' form-control' : 'form-control';
$options = $this->attributes($options);
$list = implode('', $html);
return "<select{$options}>{$list}</select>";
}
public function selects($name, $list = [], $selected = null, $options = [])
{
$options[] = 'multiple';
return $this->select($name, $list, $selected, $options);
}
public function selectpicker($name, $list = [], $selected = null, $options = [])
{
$options['class'] = isset($options['class']) ? $options['class'] . ' selectpicker' : 'selectpicker';
return $this->select($name, $list, $selected, $options);
}
public function selectpickers($name, $list = [], $selected = null, $options = [])
{
$options[] = 'multiple';
return $this->selectpicker($name, $list, $selected, $options);
}
public function selectpage($name, $value, $url, $field = null, $primaryKey = null, $options = [])
{
$options = array_merge($options, ['data-source' => $url, 'data-field' => $field ? $field : 'name', 'data-primary-key' => $primaryKey ? $primaryKey : 'id']);
$options['class'] = isset($options['class']) ? $options['class'] . ' selectpage' : 'selectpage';
return $this->text($name, $value, $options);
}
public function selectpages($name, $value, $url, $field = null, $primaryKey = null, $options = [])
{
$options['data-multiple'] = "true";
return $this->selectpage($name, $value, $url, $field, $primaryKey, $options);
}
public function citypicker($name, $value, $options = [])
{
$options['data-toggle'] = 'city-picker';
return "<div class='control-relative'>" . $this->text($name, $value, $options) . "</div>";
}
public function switcher($name, $value, $options = [])
{
$domname = str_replace(['[', ']', '.'], '', $name);
$btn = $this->hidden($name, $value, ['id' => "c-{$domname}"]);
$yes = 1;
$no = 0;
if (isset($options['yes']) && isset($options['no'])) {
$yes = $options['yes'];
$no = $options['no'];
}
$selected = $no == $value ? "fa-flip-horizontal text-gray" : "";
$disabled = (isset($options['disabled']) && $options['disabled']) || in_array('disabled', $options) ? "disabled" : '';
$color = isset($options['color']) ? $options['color'] : 'success';
unset($options['yes'], $options['no'], $options['color'], $options['disabled']);
$attr = $this->attributes($options);
$html = <<<EOD
{$btn}
<a href="javascript:;" data-toggle="switcher" class="btn-switcher {$disabled}" data-input-id="c-{$domname}" data-yes="{$yes}" data-no="{$no}" {$attr}><i class="fa fa-toggle-on text-{$color} {$selected} fa-2x"></i></a>
EOD;
return $html;
}
public function datepicker($name, $value, $options = [])
{
$defaults = [
'data-date-format' => "YYYY-MM-DD",
];
$options = array_merge($defaults, $options);
$value = is_numeric($value) ? date("Y-m-d", $value) : $value;
return $this->datetimepicker($name, $value, $options);
}
public function timepicker($name, $value, $options = [])
{
$defaults = [
'data-date-format' => "HH:mm:ss",
];
$options = array_merge($defaults, $options);
$value = is_numeric($value) ? date("H:i:s", $value) : $value;
return $this->datetimepicker($name, $value, $options);
}
public function datetimepicker($name, $value, $options = [])
{
$defaults = [
'data-date-format' => "YYYY-MM-DD HH:mm:ss",
'data-use-current' => "true",
];
$value = is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
$options = array_merge($defaults, $options);
$options['class'] = isset($options['class']) ? $options['class'] . ' datetimepicker' : 'datetimepicker';
return $this->text($name, $value, $options);
}
public function daterange($name, $value, $options = [])
{
$defaults = [
'data-locale' => [
'format' => 'YYYY-MM-DD'
]
];
$options = array_merge($defaults, $options);
return $this->datetimerange($name, $value, $options);
}
public function timerange($name, $value, $options = [])
{
$defaults = [
'data-locale' => [
'format' => 'HH:mm:ss'
],
'data-ranges' => [],
'data-show-custom-range-label' => "false",
'data-time-picker' => "true",
];
$options = array_merge($defaults, $options);
return $this->datetimerange($name, $value, $options);
}
public function datetimerange($name, $value, $options = [])
{
$defaults = [
'data-locale' => [
'format' => 'YYYY-MM-DD HH:mm:ss'
]
];
$options = array_merge($defaults, $options);
$options['class'] = isset($options['class']) ? $options['class'] . ' datetimerange' : 'datetimerange';
return $this->text($name, $value, $options);
}
public function fieldlist($name, $value, $title = null, $template = null, $options = [])
{
$append = __('Append');
$template = $template ? 'data-template="' . $template . '"' : '';
$attributes = $this->attributes($options);
if (is_null($title)) {
$title = [__('Key'), __('Value')];
}
$ins = implode("\n", array_map(function ($value) {
return "<ins>{$value}</ins>";
}, $title));
$value = is_array($value) ? json_encode($value) : $value;
$html = <<<EOD
<dl class="fieldlist" data-name="{$name}" {$template} {$attributes}>
<dd>
{$ins}
</dd>
<dd><a href="javascript:;" class="btn btn-sm btn-success btn-append"><i class="fa fa-plus"></i> {$append}</a></dd>
<textarea name="{$name}" class="form-control hide" cols="30" rows="5">{$value}</textarea>
</dl>
EOD;
return $html;
}
public function cxselect($url, $names = [], $values = [], $options = [])
{
$classes = [];
$cxselect = [];
$attributes = $this->attributes($options);
foreach ($names as $index => $value) {
$level = $index + 1;
$class = "cxselect-{$level}";
$classes[] = $class;
$selectValue = isset($values[$value]) ? $values[$value] : (isset($values[$index]) ? $values[$index] : '');
$cxselect[] = <<<EOD
<select class="{$class} form-control" name="{$value}" data-value="{$selectValue}" data-url="{$url}?level={$level}&name={$value}" {$attributes}></select>
EOD;
}
$cxselect = implode("\n", $cxselect);
$selects = implode(',', $classes);
$html = <<<EOD
<div class="form-inline" data-toggle="cxselect" data-selects="{$selects}">
{$cxselect}
</div>
EOD;
return $html;
}
public function selectRange($name, $begin, $end, $selected = null, $options = [])
{
$range = array_combine($range = range($begin, $end), $range);
return $this->select($name, $range, $selected, $options);
}
public function selectYear($name, $begin, $end, $selected, $options)
{
return call_user_func_array(array($this, 'selectRange'), func_get_args());
}
public function selectMonth($name, $selected = null, $options = [], $format = '%m')
{
$months = [];
foreach (range(1, 12) as $month) {
$months[$month] = strftime($format, mktime(0, 0, 0, $month, 1));
}
return $this->select($name, $months, $selected, $options);
}
public function getSelectOption($display, $value, $selected)
{
if (is_array($display)) {
return $this->optionGroup($display, $value, $selected);
}
return $this->option($display, $value, $selected);
}
protected function optionGroup($list, $label, $selected)
{
$html = [];
foreach ($list as $value => $display) {
$html[] = $this->option($display, $value, $selected);
}
return '<optgroup label="' . $this->escape($label) . '">' . implode('', $html) . '</optgroup>';
}
protected function option($display, $value, $selected)
{
$selected = $this->getSelectedValue($value, $selected);
$options = array('value' => $this->escape($value), 'selected' => $selected);
return '<option' . $this->attributes($options) . '>' . $this->escape($display) . '</option>';
}
protected function getSelectedValue($value, $selected)
{
if (is_array($selected)) {
return in_array($value, $selected) ? 'selected' : null;
}
return ((string)$value == (string)$selected) ? 'selected' : null;
}
public function checkbox($name, $value = 1, $checked = null, $options = [])
{
if ($checked)
$options['checked'] = 'checked';
return $this->input('checkbox', $name, $value, $options);
}
public function checkboxs($name, $list, $checked, $options = [])
{
$html = [];
$checked = is_null($checked) ? [] : $checked;
$checked = is_array($checked) ? $checked : explode(',', $checked);
foreach ($list as $k => $v) {
$options['id'] = "{$name}-{$k}";
$html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $checked), $options));
}
return '<div class="checkbox">' . implode(' ', $html) . '</div>';
}
public function radio($name, $value = null, $checked = null, $options = [])
{
if (is_null($value))
$value = $name;
if ($checked)
$options['checked'] = 'checked';
return $this->input('radio', $name, $value, $options);
}
public function radios($name, $list, $checked = null, $options = [])
{
$html = [];
$checked = is_null($checked) ? key($list) : $checked;
$checked = is_array($checked) ? $checked : explode(',', $checked);
foreach ($list as $k => $v) {
$options['id'] = "{$name}-{$k}";
$html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::radio($name, $k, in_array($k, $checked), $options));
}
return '<div class="radio">' . implode(' ', $html) . '</div>';
}
public function image($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
{
$default = [
'data-mimetype' => 'image/gif,image/jpeg,image/png,image/jpg,image/bmp'
];
$uploadAttr = is_array($chooseAttr) ? array_merge($default, $uploadAttr) : $uploadAttr;
$chooseAttr = is_array($chooseAttr) ? array_merge($default, $chooseAttr) : $chooseAttr;
return $this->uploader($name, $value, $inputAttr, $uploadAttr, $chooseAttr, $previewAttr);
}
public function images($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
{
$default = [
'data-multiple' => 'true',
'data-mimetype' => 'image/gif,image/jpeg,image/png,image/jpg,image/bmp'
];
$uploadAttr = is_array($chooseAttr) ? array_merge($default, $uploadAttr) : $uploadAttr;
$chooseAttr = is_array($chooseAttr) ? array_merge($default, $chooseAttr) : $chooseAttr;
return $this->uploader($name, $value, $inputAttr, $uploadAttr, $chooseAttr, $previewAttr);
}
public function upload($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
{
return $this->uploader($name, $value, $inputAttr, $uploadAttr, $chooseAttr, $previewAttr);
}
public function uploads($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
{
$default = [
'data-multiple' => 'true',
];
$uploadAttr = is_array($chooseAttr) ? array_merge($default, $uploadAttr) : $uploadAttr;
$chooseAttr = is_array($chooseAttr) ? array_merge($default, $chooseAttr) : $chooseAttr;
return $this->uploader($name, $value, $inputAttr, $uploadAttr, $chooseAttr, $previewAttr);
}
protected function uploader($name = null, $value, $inputAttr = [], $uploadAttr = [], $chooseAttr = [], $previewAttr = [])
{
$domname = str_replace(['[', ']', '.'], '', $name);
$options = [
'id' => "plupload-{$domname}",
'class' => "btn btn-danger plupload",
'data-input-id' => "c-{$domname}",
];
$upload = $uploadAttr === false ? false : true;
$choose = $chooseAttr === false ? false : true;
$preview = $previewAttr === false ? false : true;
if ($preview) {
$options['data-preview-id'] = "p-{$domname}";
}
$uploadBtn = $upload ? $this->button('<i class="fa fa-upload"></i> ' . __('Upload'), array_merge($options, $uploadAttr)) : '';
$options = [
'id' => "fachoose-{$domname}",
'class' => "btn btn-danger fachoose",
'data-input-id' => "c-{$domname}",
];
if ($preview) {
$options['data-preview-id'] = "p-{$domname}";
}
$chooseBtn = $choose ? $this->button('<i class="fa fa-list"></i> ' . __('Choose'), array_merge($options, $chooseAttr)) : '';
$previewAttrHtml = $this->attributes($previewAttr);
$previewArea = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $domname . '" ' . $previewAttrHtml . '></ul>' : '';
$input = $this->text($name, $value, array_merge(['size' => 50, 'id' => "c-{$domname}"], $inputAttr));
$html = <<<EOD
<div class="input-group">
{$input}
<div class="input-group-addon no-border no-padding">
<span>{$uploadBtn}</span>
<span>{$chooseBtn}</span>
</div>
<span class="msg-box n-right" for="c-{$domname}"></span>
</div>
{$previewArea}
EOD;
return $html;
}
public function button($value = null, $options = [])
{
if (!array_key_exists('type', $options)) {
$options['type'] = 'button';
}
return '<button' . $this->attributes($options) . '>' . $value . '</button>';
}
public function getIdAttribute($name, $attributes)
{
if (array_key_exists('id', $attributes)) {
return $attributes['id'];
}
if (in_array($name, $this->labels)) {
return $name;
}
}
public function getValueAttribute($name, $value = null)
{
if (is_null($name))
return $value;
if (!is_null($value))
return $value;
}
public function attributes($attributes)
{
$html = [];
foreach ((array)$attributes as $key => $value) {
$element = $this->attributeElement($key, $value);
if (!is_null($element))
$html[] = $element;
}
return count($html) > 0 ? ' ' . implode(' ', $html) : '';
}
protected function attributeElement($key, $value)
{
if (is_numeric($key))
$key = $value;
if (!is_null($value)) {
if (is_array($value) || stripos($value, '"') !== false) {
$value = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
return $key . "='" . $value . "'";
} else {
return $key . '="' . $value . '"';
}
}
}
}
class Arr
{
public static function accessible($value)
{
return is_array($value) || $value instanceof ArrayAccess;
}
public static function exists($array, $key)
{
if ($array instanceof ArrayAccess) {
return $array->offsetExists($key);
}
return array_key_exists($key, $array);
}
public static function get($array, $key, $default = null)
{
if (!static::accessible($array)) {
return $default;
}
if (is_null($key)) {
return $array;
}
if (static::exists($array, $key)) {
return $array[$key];
}
foreach (explode('.', $key) as $segment) {
if (static::accessible($array) && static::exists($array, $segment)) {
$array = $array[$segment];
} else {
return $default;
}
}
return $array;
}
public static function except($array, $keys)
{
static::forget($array, $keys);
return $array;
}
public static function forget(&$array, $keys)
{
$original = &$array;
$keys = (array)$keys;
if (count($keys) === 0) {
return;
}
foreach ($keys as $key) {
if (static::exists($array, $key)) {
unset($array[$key]);
continue;
}
$parts = explode('.', $key);
$array = &$original;
while (count($parts) > 1) {
$part = array_shift($parts);
if (isset($array[$part]) && is_array($array[$part])) {
$array = &$array[$part];
} else {
continue 2;
}
}
unset($array[array_shift($parts)]);
}
}
}
if (!function_exists('array_get')) {
function array_get($array, $key, $default = null)
{
return Arr::get($array, $key, $default);
}
}
if (!function_exists('e')) {
function e($value)
{
if (is_array($value)) {
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
}
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
}
}
if (!function_exists('array_except')) {
function array_except($array, $keys)
{
return Arr::except($array, $keys);
}
}