Compare commits

..
41 Commits
Author SHA1 Message Date
Adam Engebretson add2c74b14 Merge pull request #135 from dennisoderwald/patch-1 2016-01-15 15:59:03 -06:00
Tom Shafer 10111f558c Merge pull request #136 from LaravelCollective/analysis-8mkeVq
Applied fixes from StyleCI
2015-12-28 20:09:30 -05:00
Tom Shafer b60bb4da7c Applied fixes from StyleCI 2015-12-28 20:09:17 -05:00
Dennis Oderwald e7db3dd11a [5.2] Use toArray() for Model Object Value 2015-12-23 22:28:01 +01:00
Adam Engebretson 5a8f1380a0 Updating composer.json metadata
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-22 23:46:46 -08:00
Adam Engebretson 5b58b7e90b Updating for 5.2
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-22 23:32:30 -08:00
Adam Engebretson 4c9b44a817 Extracting Components to Trait & Adding to Forms
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-02 02:15:22 -06:00
Adam Engebretson 4dca637a23 Merge branch 'master' of github.com:LaravelCollective/html 2015-12-01 04:02:52 -06:00
Adam Engebretson 3e6729614c Fixing Tests
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 03:52:30 -06:00
Adam Engebretson a5ce692fd7 Merge pull request #121 from LaravelCollective/analysis-qyPlGX
Applied fixes from StyleCI
2015-12-01 03:52:06 -06:00
Adam Engebretson 0946c7f0a3 Applied fixes from StyleCI 2015-12-01 04:45:27 -05:00
Adam Engebretson 68f2a68c47 Fixing CS
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 03:44:46 -06:00
Adam Engebretson 5b7668573d Adding FormAccessible Trait
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 03:41:47 -06:00
Adam Engebretson e70854b523 Returning HtmlStrings [html]
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 02:03:53 -06:00
Adam Engebretson 29efd5ae14 Returning HtmlStrings [form]
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 01:58:43 -06:00
Adam Engebretson 24d14f259d Formatting
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 01:46:08 -06:00
Adam Engebretson c772164bff Allowing default component values
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 01:44:34 -06:00
Adam Engebretson c4ae1f54de Tidying
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 00:44:13 -06:00
Adam Engebretson 53b8b23bf9 Protecting a method
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 00:36:40 -06:00
Adam Engebretson d2b7e24d72 Starting Html Components
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 00:35:47 -06:00
Adam Engebretson 46409f294e Incrementing for 5.2
Signed-off-by: Adam Engebretson <adam.engebretson@bridgeconx.com>
2015-12-01 00:35:36 -06:00
Adam Engebretson f8cd022c4f Merge pull request #120 from mul14/add-test-for-input-color-type
Add test for input color type
2015-11-28 02:36:08 -06:00
Mulia Arifandi Nasution bca8b11d67 Fix Style-CI 2015-11-28 15:34:33 +07:00
Mulia Arifandi Nasution db665c9f0f Add test for input color type 2015-11-28 15:32:53 +07:00
Adam Engebretson f62269629b Merge pull request #96 from patrickbrouwers/patch-1
HtmlBuilder shouldn't depend on concrete implementation
2015-11-28 02:27:09 -06:00
Adam Engebretson 2516472b3f Merge pull request #97 from patrickbrouwers/patch-2
Don't depend on concretes in FormBuilder
2015-11-28 02:26:44 -06:00
Adam Engebretson 828da38dcd Merge pull request #100 from jackmcdade/5.1
dl() now supports multiple descriptions per term
2015-11-28 02:26:21 -06:00
Adam Engebretson 292a4787a4 Merge pull request #119 from mul14/add-color-input-type
Add color input type
2015-11-28 02:24:41 -06:00
Mulia Arifandi Nasution b6b3693586 Add color input type 2015-11-28 15:21:36 +07:00
Adam Engebretson 5ad8377968 Merge pull request #108 from martinbean/feature/datetime-inputs
Add datetime input types
2015-11-06 12:14:38 -06:00
Martin Bean cea1f619b3 Add datetime input types 2015-11-06 13:44:42 +00:00
Jack McDade acb21a9364 correct code formatting 2015-10-23 17:47:44 -04:00
Jack McDade b5d6fdedb6 dl() now supports multiple descriptions per term 2015-10-23 17:45:01 -04:00
Patrick Brouwers 9ab4568241 Don't depend on concretes in FormBuilder 2015-10-08 10:08:07 +02:00
Patrick Brouwers 575d891b64 HtmlBuilder shouldn't depend on concrete implementation 2015-10-08 09:56:16 +02:00
Adam Engebretson a4acc4a0ad Merge pull request #85 from wmather/5.1
Replace bindShared with singleton
2015-09-29 20:05:59 -05:00
wmather a28c3dc94c Replace bindShared with singleton 2015-09-11 14:46:31 +01:00
Adam Engebretson bfb0ed2487 Merge pull request #83 from neoxia/5.1-dead-code
Remove dead code in HtmlBuilderTest
2015-09-08 12:03:18 -05:00
alexandre-butynski ef5befed96 Remove dead code in HtmlBuilderTest 2015-09-07 19:18:56 +02:00
Adam Engebretson 36922db2bc Merge pull request #79 from LaravelCollective/analysis-86MO9z
Applied fixes from StyleCI
2015-09-03 12:20:52 -05:00
Adam Engebretson 017d60144f Applied fixes from StyleCI 2015-09-03 13:18:42 -04:00
13 changed files with 868 additions and 333 deletions

No files matched your search

+12 -4
View File
@@ -1,6 +1,12 @@
{ {
"name": "laravelcollective/html", "name": "laravelcollective/html",
"description": "HTML and Form Builders for the Laravel Framework",
"license": "MIT", "license": "MIT",
"homepage": "http://laravelcollective.com",
"support": {
"issues": "https://github.com/LaravelCollective/html/issues",
"source": "https://github.com/LaravelCollective/html"
},
"authors": [ "authors": [
{ {
"name": "Adam Engebretson", "name": "Adam Engebretson",
@@ -13,12 +19,14 @@
], ],
"require": { "require": {
"php": ">=5.5.9", "php": ">=5.5.9",
"illuminate/http": "5.1.*", "illuminate/http": "5.2.*",
"illuminate/routing": "5.1.*", "illuminate/routing": "5.2.*",
"illuminate/session": "5.1.*", "illuminate/session": "5.2.*",
"illuminate/support": "5.1.*" "illuminate/support": "5.2.*",
"illuminate/view": "5.2.*"
}, },
"require-dev": { "require-dev": {
"illuminate/database": "5.2.*",
"mockery/mockery": "~0.9", "mockery/mockery": "~0.9",
"phpunit/phpunit": "~4.0" "phpunit/phpunit": "~4.0"
}, },
+25
View File
@@ -1,5 +1,9 @@
<?php <?php
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Events\Dispatcher;
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Register The Composer Auto Loader | Register The Composer Auto Loader
@@ -26,3 +30,24 @@ require __DIR__.'/vendor/autoload.php';
*/ */
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
/*
* Prepare the db connection (spoofing that shit)
*/
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
]);
$capsule->setEventDispatcher(new Dispatcher);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema()->dropIfExists('models');
$capsule->schema()->create('models', function (Blueprint $table) {
$table->increments('id');
$table->string('string');
$table->string('email');
$table->timestamps();
});
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace Collective\Html;
use BadMethodCallException;
use Illuminate\Support\HtmlString;
trait Componentable
{
/**
* The registered components.
*
* @var array
*/
protected static $components = [];
/**
* Register a custom component.
*
* @param $name
* @param $view
* @param array $signature
*
* @return void
*/
public static function component($name, $view, array $signature)
{
static::$components[$name] = compact('view', 'signature');
}
/**
* Check if a component is registered.
*
* @param $name
*
* @return bool
*/
public static function hasComponent($name)
{
return isset(static::$components[$name]);
}
/**
* Render a custom component.
*
* @param $name
* @param array $arguments
*
* @return \Illuminate\Contracts\View\View
*/
protected function renderComponent($name, array $arguments)
{
$component = static::$components[$name];
$data = $this->getComponentData($component['signature'], $arguments);
return new HtmlString(
$this->view->make($component['view'], $data)->render()
);
}
/**
* Prepare the component data, while respecting provided defaults.
*
* @param array $signature
* @param array $arguments
*
* @return array
*/
protected function getComponentData(array $signature, array $arguments)
{
$data = [];
$i = 0;
foreach ($signature as $variable => $default) {
// If the "variable" value is actually a numeric key, we can assume that
// no default had been specified for the component argument and we'll
// just use null instead, so that we can treat them all the same.
if (is_numeric($variable)) {
$variable = $default;
$default = null;
}
$data[$variable] = array_get($arguments, $i) ?: $default;
$i++;
}
return $data;
}
/**
* Dynamically handle calls to the class.
*
* @param string $method
* @param array $parameters
*
* @return \Illuminate\Contracts\View\View|mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
if (static::hasComponent($method)) {
return $this->renderComponent($method, $parameters);
}
throw new BadMethodCallException("Method {$method} does not exist.");
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace Collective\Html\Eloquent;
use ReflectionClass;
use ReflectionMethod;
use Illuminate\Support\Str;
trait FormAccessible
{
/**
* A cached ReflectionClass instance for $this
*
* @var ReflectionClass
*/
protected $reflection;
/**
* @param string $key
*
* @return mixed
*/
public function getFormValue($key)
{
$value = $this->getAttributeFromArray($key);
// If the attribute is listed as a date, we will convert it to a DateTime
// instance on retrieval, which makes it quite convenient to work with
// date fields without having to create a mutator for each property.
if (in_array($key, $this->getDates())) {
if (! is_null($value)) {
$value = $this->asDateTime($value);
}
}
// If the attribute has a get mutator, we will call that then return what
// it returns as the value, which is useful for transforming values on
// retrieval from the model to a form that is more useful for usage.
if ($this->hasFormMutator($key)) {
return $this->mutateFormAttribute($key, $value);
}
return $value;
}
/**
* @param $key
*
* @return bool
*/
protected function hasFormMutator($key)
{
$methods = $this->getReflection()->getMethods(ReflectionMethod::IS_PUBLIC);
$mutator = collect($methods)
->first(function ($index, ReflectionMethod $method) use ($key) {
return $method->getName() == 'form' . Str::studly($key) . 'Attribute';
});
return (bool) $mutator;
}
/**
* @param $key
* @param $value
*
* @return mixed
*/
private function mutateFormAttribute($key, $value)
{
return $this->{'form' . Str::studly($key) . 'Attribute'}($value);
}
/**
* Get a ReflectionClass Instance
* @return ReflectionClass
*/
protected function getReflection()
{
if (! $this->reflection) {
$this->reflection = new ReflectionClass($this);
}
return $this->reflection;
}
}
+226 -126
View File
@@ -1,14 +1,24 @@
<?php namespace Collective\Html; <?php
namespace Collective\Html;
use DateTime; use DateTime;
use Illuminate\Routing\UrlGenerator; use BadMethodCallException;
use Illuminate\Session\Store as Session;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\HtmlString;
use Illuminate\Contracts\View\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Session\SessionInterface;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Routing\UrlGenerator;
class FormBuilder { class FormBuilder
{
use Macroable; use Macroable, Componentable {
Macroable::__call as macroCall;
Componentable::__call as componentCall;
}
/** /**
* The HTML builder instance. * The HTML builder instance.
@@ -20,10 +30,17 @@ class FormBuilder {
/** /**
* The URL generator instance. * The URL generator instance.
* *
* @var \Illuminate\Routing\UrlGenerator $url * @var \Illuminate\Contracts\Routing\UrlGenerator
*/ */
protected $url; protected $url;
/**
* The View factory instance.
*
* @var \Illuminate\Contracts\View\Factory
*/
protected $view;
/** /**
* The CSRF token used by the form builder. * The CSRF token used by the form builder.
* *
@@ -34,7 +51,7 @@ class FormBuilder {
/** /**
* The session store implementation. * The session store implementation.
* *
* @var \Illuminate\Session\Store * @var \Illuminate\Session\SessionInterface
*/ */
protected $session; protected $session;
@@ -76,16 +93,16 @@ class FormBuilder {
/** /**
* Create a new form builder instance. * Create a new form builder instance.
* *
* @param \Illuminate\Routing\UrlGenerator $url
* @param \Collective\Html\HtmlBuilder $html * @param \Collective\Html\HtmlBuilder $html
* @param \Illuminate\Contracts\Routing\UrlGenerator $url
* @param \Illuminate\Contracts\View\Factory $view
* @param string $csrfToken * @param string $csrfToken
*
* @return void
*/ */
public function __construct(HtmlBuilder $html, UrlGenerator $url, $csrfToken) public function __construct(HtmlBuilder $html, UrlGenerator $url, Factory $view, $csrfToken)
{ {
$this->url = $url; $this->url = $url;
$this->html = $html; $this->html = $html;
$this->view = $view;
$this->csrfToken = $csrfToken; $this->csrfToken = $csrfToken;
} }
@@ -94,7 +111,7 @@ class FormBuilder {
* *
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function open(array $options = []) public function open(array $options = [])
{ {
@@ -114,8 +131,7 @@ class FormBuilder {
// different method than it actually is, for convenience from the forms. // different method than it actually is, for convenience from the forms.
$append = $this->getAppendage($method); $append = $this->getAppendage($method);
if(isset($options['files']) && $options['files']) if (isset($options['files']) && $options['files']) {
{
$options['enctype'] = 'multipart/form-data'; $options['enctype'] = 'multipart/form-data';
} }
@@ -133,7 +149,7 @@ class FormBuilder {
// extra value for the hidden _method field if it's needed for the form. // extra value for the hidden _method field if it's needed for the form.
$attributes = $this->html->attributes($attributes); $attributes = $this->html->attributes($attributes);
return '<form' . $attributes . '>' . $append; return $this->toHtmlString('<form' . $attributes . '>' . $append);
} }
/** /**
@@ -142,7 +158,7 @@ class FormBuilder {
* @param mixed $model * @param mixed $model
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function model($model, array $options = []) public function model($model, array $options = [])
{ {
@@ -174,7 +190,7 @@ class FormBuilder {
$this->model = null; $this->model = null;
return '</form>'; return $this->toHtmlString('</form>');
} }
/** /**
@@ -196,7 +212,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function label($name, $value = null, $options = []) public function label($name, $value = null, $options = [])
{ {
@@ -206,7 +222,7 @@ class FormBuilder {
$value = e($this->formatLabel($name, $value)); $value = e($this->formatLabel($name, $value));
return '<label for="' . $name . '"' . $options . '>' . $value . '</label>'; return $this->toHtmlString('<label for="' . $name . '"' . $options . '>' . $value . '</label>');
} }
/** /**
@@ -230,19 +246,20 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function input($type, $name, $value = null, $options = []) public function input($type, $name, $value = null, $options = [])
{ {
if( ! isset($options['name'])) $options['name'] = $name; if (! isset($options['name'])) {
$options['name'] = $name;
}
// We will get the appropriate value for the given field. We will look for the // We will get the appropriate value for the given field. We will look for the
// value in the session for the value in the old input data then we'll look // value in the session for the value in the old input data then we'll look
// in the model instance if one is set. Otherwise we will just use empty. // in the model instance if one is set. Otherwise we will just use empty.
$id = $this->getIdAttribute($name, $options); $id = $this->getIdAttribute($name, $options);
if( ! in_array($type, $this->skipValueTypes)) if (! in_array($type, $this->skipValueTypes)) {
{
$value = $this->getValueAttribute($name, $value); $value = $this->getValueAttribute($name, $value);
} }
@@ -253,7 +270,7 @@ class FormBuilder {
$options = array_merge($options, $merge); $options = array_merge($options, $merge);
return '<input' . $this->html->attributes($options) . '>'; return $this->toHtmlString('<input' . $this->html->attributes($options) . '>');
} }
/** /**
@@ -263,7 +280,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function text($name, $value = null, $options = []) public function text($name, $value = null, $options = [])
{ {
@@ -276,7 +293,7 @@ class FormBuilder {
* @param string $name * @param string $name
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function password($name, $options = []) public function password($name, $options = [])
{ {
@@ -290,7 +307,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function hidden($name, $value = null, $options = []) public function hidden($name, $value = null, $options = [])
{ {
@@ -304,7 +321,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function email($name, $value = null, $options = []) public function email($name, $value = null, $options = [])
{ {
@@ -318,7 +335,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function tel($name, $value = null, $options = []) public function tel($name, $value = null, $options = [])
{ {
@@ -332,7 +349,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function number($name, $value = null, $options = []) public function number($name, $value = null, $options = [])
{ {
@@ -346,18 +363,53 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function date($name, $value = null, $options = []) public function date($name, $value = null, $options = [])
{ {
if($value instanceof DateTime) if ($value instanceof DateTime) {
{
$value = $value->format('Y-m-d'); $value = $value->format('Y-m-d');
} }
return $this->input('date', $name, $value, $options); return $this->input('date', $name, $value, $options);
} }
/**
* Create a datetime input field.
*
* @param string $name
* @param string $value
* @param array $options
*
* @return \Illuminate\Support\HtmlString
*/
public function datetime($name, $value = null, $options = [])
{
if ($value instanceof DateTime) {
$value = $value->format(DateTime::RFC3339);
}
return $this->input('datetime', $name, $value, $options);
}
/**
* Create a datetime-local input field.
*
* @param string $name
* @param string $value
* @param array $options
*
* @return \Illuminate\Support\HtmlString
*/
public function datetimeLocal($name, $value = null, $options = [])
{
if ($value instanceof DateTime) {
$value = $value->format('Y-m-d\TH:i');
}
return $this->input('datetime-local', $name, $value, $options);
}
/** /**
* Create a time input field. * Create a time input field.
* *
@@ -365,7 +417,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function time($name, $value = null, $options = []) public function time($name, $value = null, $options = [])
{ {
@@ -379,7 +431,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function url($name, $value = null, $options = []) public function url($name, $value = null, $options = [])
{ {
@@ -392,7 +444,7 @@ class FormBuilder {
* @param string $name * @param string $name
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function file($name, $options = []) public function file($name, $options = [])
{ {
@@ -406,11 +458,13 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function textarea($name, $value = null, $options = []) public function textarea($name, $value = null, $options = [])
{ {
if( ! isset($options['name'])) $options['name'] = $name; if (! isset($options['name'])) {
$options['name'] = $name;
}
// Next we will look for the rows and cols attributes, as each of these are put // Next we will look for the rows and cols attributes, as each of these are put
// on the textarea element definition. If they are not present, we will just // on the textarea element definition. If they are not present, we will just
@@ -428,7 +482,7 @@ class FormBuilder {
// the element. Then we'll create the final textarea elements HTML for us. // the element. Then we'll create the final textarea elements HTML for us.
$options = $this->html->attributes($options); $options = $this->html->attributes($options);
return '<textarea' . $options . '>' . e($value) . '</textarea>'; return $this->toHtmlString('<textarea' . $options . '>' . e($value) . '</textarea>');
} }
/** /**
@@ -440,8 +494,7 @@ class FormBuilder {
*/ */
protected function setTextAreaSize($options) protected function setTextAreaSize($options)
{ {
if(isset($options['size'])) if (isset($options['size'])) {
{
return $this->setQuickTextAreaSize($options); return $this->setQuickTextAreaSize($options);
} }
@@ -477,7 +530,7 @@ class FormBuilder {
* @param string $selected * @param string $selected
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function select($name, $list = [], $selected = null, $options = []) public function select($name, $list = [], $selected = null, $options = [])
{ {
@@ -488,21 +541,21 @@ class FormBuilder {
$options['id'] = $this->getIdAttribute($name, $options); $options['id'] = $this->getIdAttribute($name, $options);
if( ! isset($options['name'])) $options['name'] = $name; if (! isset($options['name'])) {
$options['name'] = $name;
}
// We will simply loop through the options and build an HTML value for each of // We will simply loop through the options and build an HTML value for each of
// them until we have an array of HTML declarations. Then we will join them // them until we have an array of HTML declarations. Then we will join them
// all together into one single HTML element that can be put on the form. // all together into one single HTML element that can be put on the form.
$html = []; $html = [];
if(isset($options['placeholder'])) if (isset($options['placeholder'])) {
{
$html[] = $this->placeholderOption($options['placeholder'], $selected); $html[] = $this->placeholderOption($options['placeholder'], $selected);
unset($options['placeholder']); unset($options['placeholder']);
} }
foreach($list as $value => $display) foreach ($list as $value => $display) {
{
$html[] = $this->getSelectOption($display, $value, $selected); $html[] = $this->getSelectOption($display, $value, $selected);
} }
@@ -513,7 +566,7 @@ class FormBuilder {
$list = implode('', $html); $list = implode('', $html);
return "<select{$options}>{$list}</select>"; return $this->toHtmlString("<select{$options}>{$list}</select>");
} }
/** /**
@@ -525,7 +578,7 @@ class FormBuilder {
* @param string $selected * @param string $selected
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function selectRange($name, $begin, $end, $selected = null, $options = []) public function selectRange($name, $begin, $end, $selected = null, $options = [])
{ {
@@ -543,7 +596,7 @@ class FormBuilder {
* @param string $selected * @param string $selected
* @param array $options * @param array $options
* *
* @return string * @return mixed
*/ */
public function selectYear() public function selectYear()
{ {
@@ -558,14 +611,13 @@ class FormBuilder {
* @param array $options * @param array $options
* @param string $format * @param string $format
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function selectMonth($name, $selected = null, $options = [], $format = '%B') public function selectMonth($name, $selected = null, $options = [], $format = '%B')
{ {
$months = []; $months = [];
foreach(range(1, 12) as $month) foreach (range(1, 12) as $month) {
{
$months[$month] = strftime($format, mktime(0, 0, 0, $month, 1)); $months[$month] = strftime($format, mktime(0, 0, 0, $month, 1));
} }
@@ -579,12 +631,11 @@ class FormBuilder {
* @param string $value * @param string $value
* @param string $selected * @param string $selected
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function getSelectOption($display, $value, $selected) public function getSelectOption($display, $value, $selected)
{ {
if(is_array($display)) if (is_array($display)) {
{
return $this->optionGroup($display, $value, $selected); return $this->optionGroup($display, $value, $selected);
} }
@@ -598,18 +649,17 @@ class FormBuilder {
* @param string $label * @param string $label
* @param string $selected * @param string $selected
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
protected function optionGroup($list, $label, $selected) protected function optionGroup($list, $label, $selected)
{ {
$html = []; $html = [];
foreach($list as $value => $display) foreach ($list as $value => $display) {
{
$html[] = $this->option($display, $value, $selected); $html[] = $this->option($display, $value, $selected);
} }
return '<optgroup label="' . e($label) . '">' . implode('', $html) . '</optgroup>'; return $this->toHtmlString('<optgroup label="' . e($label) . '">' . implode('', $html) . '</optgroup>');
} }
/** /**
@@ -619,7 +669,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param string $selected * @param string $selected
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
protected function option($display, $value, $selected) protected function option($display, $value, $selected)
{ {
@@ -627,7 +677,7 @@ class FormBuilder {
$options = ['value' => $value, 'selected' => $selected]; $options = ['value' => $value, 'selected' => $selected];
return '<option' . $this->html->attributes($options) . '>' . e($display) . '</option>'; return $this->toHtmlString('<option' . $this->html->attributes($options) . '>' . e($display) . '</option>');
} }
/** /**
@@ -636,7 +686,7 @@ class FormBuilder {
* @param $display * @param $display
* @param $selected * @param $selected
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
protected function placeholderOption($display, $selected) protected function placeholderOption($display, $selected)
{ {
@@ -645,7 +695,7 @@ class FormBuilder {
$options = compact('selected'); $options = compact('selected');
$options['value'] = ''; $options['value'] = '';
return '<option' . $this->html->attributes($options) . '>' . e($display) . '</option>'; return $this->toHtmlString('<option' . $this->html->attributes($options) . '>' . e($display) . '</option>');
} }
/** /**
@@ -654,12 +704,11 @@ class FormBuilder {
* @param string $value * @param string $value
* @param string $selected * @param string $selected
* *
* @return string|null * @return null|string
*/ */
protected function getSelectedValue($value, $selected) protected function getSelectedValue($value, $selected)
{ {
if(is_array($selected)) if (is_array($selected)) {
{
return in_array($value, $selected) ? 'selected' : null; return in_array($value, $selected) ? 'selected' : null;
} }
@@ -674,7 +723,7 @@ class FormBuilder {
* @param bool $checked * @param bool $checked
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function checkbox($name, $value = 1, $checked = null, $options = []) public function checkbox($name, $value = 1, $checked = null, $options = [])
{ {
@@ -689,11 +738,13 @@ class FormBuilder {
* @param bool $checked * @param bool $checked
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function radio($name, $value = null, $checked = null, $options = []) public function radio($name, $value = null, $checked = null, $options = [])
{ {
if(is_null($value)) $value = $name; if (is_null($value)) {
$value = $name;
}
return $this->checkable('radio', $name, $value, $checked, $options); return $this->checkable('radio', $name, $value, $checked, $options);
} }
@@ -707,13 +758,15 @@ class FormBuilder {
* @param bool $checked * @param bool $checked
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
protected function checkable($type, $name, $value, $checked, $options) protected function checkable($type, $name, $value, $checked, $options)
{ {
$checked = $this->getCheckedState($type, $name, $value, $checked); $checked = $this->getCheckedState($type, $name, $value, $checked);
if($checked) $options['checked'] = 'checked'; if ($checked) {
$options['checked'] = 'checked';
}
return $this->input($type, $name, $value, $options); return $this->input($type, $name, $value, $options);
} }
@@ -730,8 +783,7 @@ class FormBuilder {
*/ */
protected function getCheckedState($type, $name, $value, $checked) protected function getCheckedState($type, $name, $value, $checked)
{ {
switch($type) switch ($type) {
{
case 'checkbox': case 'checkbox':
return $this->getCheckboxCheckedState($name, $value, $checked); return $this->getCheckboxCheckedState($name, $value, $checked);
@@ -754,22 +806,21 @@ class FormBuilder {
*/ */
protected function getCheckboxCheckedState($name, $value, $checked) protected function getCheckboxCheckedState($name, $value, $checked)
{ {
if(isset($this->session) && ! $this->oldInputIsEmpty() && is_null($this->old($name))) return false; if (isset($this->session) && ! $this->oldInputIsEmpty() && is_null($this->old($name))) {
return false;
}
if($this->missingOldAndModel($name)) return $checked; if ($this->missingOldAndModel($name)) {
return $checked;
}
$posted = $this->getValueAttribute($name, $checked); $posted = $this->getValueAttribute($name, $checked);
if (is_array($posted)) if (is_array($posted)) {
{
return in_array($value, $posted); return in_array($value, $posted);
} } elseif ($posted instanceof Collection) {
else if ($posted instanceof Collection)
{
return $posted->contains('id', $value); return $posted->contains('id', $value);
} } else {
else
{
return (bool) $posted; return (bool) $posted;
} }
} }
@@ -785,7 +836,9 @@ class FormBuilder {
*/ */
protected function getRadioCheckedState($name, $value, $checked) protected function getRadioCheckedState($name, $value, $checked)
{ {
if($this->missingOldAndModel($name)) return $checked; if ($this->missingOldAndModel($name)) {
return $checked;
}
return $this->getValueAttribute($name) == $value; return $this->getValueAttribute($name) == $value;
} }
@@ -808,7 +861,7 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $attributes * @param array $attributes
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function reset($value, $attributes = []) public function reset($value, $attributes = [])
{ {
@@ -822,7 +875,7 @@ class FormBuilder {
* @param string $name * @param string $name
* @param array $attributes * @param array $attributes
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function image($url, $name = null, $attributes = []) public function image($url, $name = null, $attributes = [])
{ {
@@ -831,13 +884,27 @@ class FormBuilder {
return $this->input('image', $name, null, $attributes); return $this->input('image', $name, null, $attributes);
} }
/**
* Create a color input field.
*
* @param string $name
* @param string $value
* @param array $options
*
* @return \Illuminate\Support\HtmlString
*/
public function color($name, $value = null, $options = [])
{
return $this->input('color', $name, $value, $options);
}
/** /**
* Create a submit button element. * Create a submit button element.
* *
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function submit($value = null, $options = []) public function submit($value = null, $options = [])
{ {
@@ -850,16 +917,15 @@ class FormBuilder {
* @param string $value * @param string $value
* @param array $options * @param array $options
* *
* @return string * @return \Illuminate\Support\HtmlString
*/ */
public function button($value = null, $options = []) public function button($value = null, $options = [])
{ {
if( ! array_key_exists('type', $options)) if (! array_key_exists('type', $options)) {
{
$options['type'] = 'button'; $options['type'] = 'button';
} }
return '<button' . $this->html->attributes($options) . '>' . $value . '</button>'; return $this->toHtmlString('<button' . $this->html->attributes($options) . '>' . $value . '</button>');
} }
/** /**
@@ -888,21 +954,18 @@ class FormBuilder {
// We will also check for a "route" or "action" parameter on the array so that // We will also check for a "route" or "action" parameter on the array so that
// developers can easily specify a route or controller action when creating // developers can easily specify a route or controller action when creating
// a form providing a convenient interface for creating the form actions. // a form providing a convenient interface for creating the form actions.
if(isset($options['url'])) if (isset($options['url'])) {
{
return $this->getUrlAction($options['url']); return $this->getUrlAction($options['url']);
} }
if(isset($options['route'])) if (isset($options['route'])) {
{
return $this->getRouteAction($options['route']); return $this->getRouteAction($options['route']);
} }
// If an action is available, we are attempting to open a form to a controller // If an action is available, we are attempting to open a form to a controller
// action route. So, we will use the URL generator to get the path to these // action route. So, we will use the URL generator to get the path to these
// actions and return them from the method. Otherwise, we'll use current. // actions and return them from the method. Otherwise, we'll use current.
elseif(isset($options['action'])) elseif (isset($options['action'])) {
{
return $this->getControllerAction($options['action']); return $this->getControllerAction($options['action']);
} }
@@ -918,8 +981,7 @@ class FormBuilder {
*/ */
protected function getUrlAction($options) protected function getUrlAction($options)
{ {
if(is_array($options)) if (is_array($options)) {
{
return $this->url->to($options[0], array_slice($options, 1)); return $this->url->to($options[0], array_slice($options, 1));
} }
@@ -935,8 +997,7 @@ class FormBuilder {
*/ */
protected function getRouteAction($options) protected function getRouteAction($options)
{ {
if(is_array($options)) if (is_array($options)) {
{
return $this->url->route($options[0], array_slice($options, 1)); return $this->url->route($options[0], array_slice($options, 1));
} }
@@ -952,8 +1013,7 @@ class FormBuilder {
*/ */
protected function getControllerAction($options) protected function getControllerAction($options)
{ {
if(is_array($options)) if (is_array($options)) {
{
return $this->url->action($options[0], array_slice($options, 1)); return $this->url->action($options[0], array_slice($options, 1));
} }
@@ -974,16 +1034,14 @@ class FormBuilder {
// If the HTTP method is in this list of spoofed methods, we will attach the // If the HTTP method is in this list of spoofed methods, we will attach the
// method spoofer hidden input to the form. This allows us to use regular // method spoofer hidden input to the form. This allows us to use regular
// form to initiate PUT and DELETE requests in addition to the typical. // form to initiate PUT and DELETE requests in addition to the typical.
if(in_array($method, $this->spoofedMethods)) if (in_array($method, $this->spoofedMethods)) {
{
$appendage .= $this->hidden('_method', $method); $appendage .= $this->hidden('_method', $method);
} }
// If the method is something other than GET we will go ahead and attach the // If the method is something other than GET we will go ahead and attach the
// CSRF token to the form, as this can't hurt and is convenient to simply // CSRF token to the form, as this can't hurt and is convenient to simply
// always have available on every form the developers creates for them. // always have available on every form the developers creates for them.
if($method != 'GET') if ($method != 'GET') {
{
$appendage .= $this->token(); $appendage .= $this->token();
} }
@@ -1000,13 +1058,11 @@ class FormBuilder {
*/ */
public function getIdAttribute($name, $attributes) public function getIdAttribute($name, $attributes)
{ {
if(array_key_exists('id', $attributes)) if (array_key_exists('id', $attributes)) {
{
return $attributes['id']; return $attributes['id'];
} }
if(in_array($name, $this->labels)) if (in_array($name, $this->labels)) {
{
return $name; return $name;
} }
} }
@@ -1021,17 +1077,19 @@ class FormBuilder {
*/ */
public function getValueAttribute($name, $value = null) public function getValueAttribute($name, $value = null)
{ {
if(is_null($name)) return $value; if (is_null($name)) {
return $value;
}
if( ! is_null($this->old($name))) if (! is_null($this->old($name))) {
{
return $this->old($name); return $this->old($name);
} }
if( ! is_null($value)) return $value; if (! is_null($value)) {
return $value;
}
if(isset($this->model)) if (isset($this->model)) {
{
return $this->getModelValueAttribute($name); return $this->getModelValueAttribute($name);
} }
} }
@@ -1045,7 +1103,11 @@ class FormBuilder {
*/ */
protected function getModelValueAttribute($name) protected function getModelValueAttribute($name)
{ {
return data_get($this->model, $this->transformKey($name)); if (method_exists($this->model, 'getFormValue')) {
return $this->model->getFormValue($name);
}
return data_get($this->model->toArray(), $this->transformKey($name));
} }
/** /**
@@ -1057,8 +1119,7 @@ class FormBuilder {
*/ */
public function old($name) public function old($name)
{ {
if(isset($this->session)) if (isset($this->session)) {
{
return $this->session->getOldInput($this->transformKey($name)); return $this->session->getOldInput($this->transformKey($name));
} }
} }
@@ -1078,17 +1139,29 @@ class FormBuilder {
* *
* @param string $key * @param string $key
* *
* @return string * @return mixed
*/ */
protected function transformKey($key) protected function transformKey($key)
{ {
return str_replace(['.', '[]', '[', ']'], ['_', '', '.', ''], $key); return str_replace(['.', '[]', '[', ']'], ['_', '', '.', ''], $key);
} }
/**
* Transform the string to an Html serializable object
*
* @param $html
*
* @return \Illuminate\Support\HtmlString
*/
protected function toHtmlString($html)
{
return new HtmlString($html);
}
/** /**
* Get the session store implementation. * Get the session store implementation.
* *
* @return \Illuminate\Session\Store $session * @return \Illuminate\Session\SessionInterface $session
*/ */
public function getSessionStore() public function getSessionStore()
{ {
@@ -1098,14 +1171,41 @@ class FormBuilder {
/** /**
* Set the session store implementation. * Set the session store implementation.
* *
* @param \Illuminate\Session\Store $session * @param \Illuminate\Session\SessionInterface $session
* *
* @return $this * @return $this
*/ */
public function setSessionStore(Session $session) public function setSessionStore(SessionInterface $session)
{ {
$this->session = $session; $this->session = $session;
return $this; return $this;
} }
/**
* Dynamically handle calls to the class.
*
* @param string $method
* @param array $parameters
*
* @return \Illuminate\Contracts\View\View|mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
try {
return $this->componentCall($method, $parameters);
} catch (BadMethodCallException $e) {
//
}
try {
return $this->macroCall($method, $parameters);
} catch (BadMethodCallException $e) {
//
}
throw new BadMethodCallException("Method {$method} does not exist.");
}
} }
+9 -4
View File
@@ -1,17 +1,22 @@
<?php namespace Collective\Html; <?php
namespace Collective\Html;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
/** /**
* @see \Collective\Html\FormBuilder * @see \Collective\Html\FormBuilder
*/ */
class FormFacade extends Facade { class FormFacade extends Facade
{
/** /**
* Get the registered name of the component. * Get the registered name of the component.
* *
* @return string * @return string
*/ */
protected static function getFacadeAccessor() { return 'form'; } protected static function getFacadeAccessor()
{
return 'form';
}
} }
+169 -80
View File
@@ -1,34 +1,52 @@
<?php namespace Collective\Html; <?php
use Illuminate\Routing\UrlGenerator; namespace Collective\Html;
use BadMethodCallException;
use Illuminate\Support\HtmlString;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Traits\Macroable; use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Routing\UrlGenerator;
class HtmlBuilder { class HtmlBuilder
{
use Macroable; use Macroable, Componentable {
Macroable::__call as macroCall;
Componentable::__call as componentCall;
}
/** /**
* The URL generator instance. * The URL generator instance.
* *
* @var \Illuminate\Routing\UrlGenerator * @var \Illuminate\Contracts\Routing\UrlGenerator
*/ */
protected $url; protected $url;
/**
* The View Factory instance.
*
* @var \Illuminate\Contracts\View\Factory
*/
protected $view;
/** /**
* Create a new HTML builder instance. * Create a new HTML builder instance.
* *
* @param \Illuminate\Routing\UrlGenerator $url * @param \Illuminate\Contracts\Routing\UrlGenerator $url
* @return void * @param \Illuminate\Contracts\View\Factory $view
*/ */
public function __construct(UrlGenerator $url = null) public function __construct(UrlGenerator $url = null, Factory $view)
{ {
$this->url = $url; $this->url = $url;
$this->view = $view;
} }
/** /**
* Convert an HTML string to entities. * Convert an HTML string to entities.
* *
* @param string $value * @param string $value
*
* @return string * @return string
*/ */
public function entities($value) public function entities($value)
@@ -40,6 +58,7 @@ class HtmlBuilder {
* Convert entities to HTML characters. * Convert entities to HTML characters.
* *
* @param string $value * @param string $value
*
* @return string * @return string
*/ */
public function decode($value) public function decode($value)
@@ -53,13 +72,14 @@ class HtmlBuilder {
* @param string $url * @param string $url
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function script($url, $attributes = array(), $secure = null) public function script($url, $attributes = [], $secure = null)
{ {
$attributes['src'] = $this->url->asset($url, $secure); $attributes['src'] = $this->url->asset($url, $secure);
return '<script'.$this->attributes($attributes).'></script>'.PHP_EOL; return $this->toHtmlString('<script' . $this->attributes($attributes) . '></script>' . PHP_EOL);
} }
/** /**
@@ -68,17 +88,18 @@ class HtmlBuilder {
* @param string $url * @param string $url
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function style($url, $attributes = array(), $secure = null) public function style($url, $attributes = [], $secure = null)
{ {
$defaults = array('media' => 'all', 'type' => 'text/css', 'rel' => 'stylesheet'); $defaults = ['media' => 'all', 'type' => 'text/css', 'rel' => 'stylesheet'];
$attributes = $attributes + $defaults; $attributes = $attributes + $defaults;
$attributes['href'] = $this->url->asset($url, $secure); $attributes['href'] = $this->url->asset($url, $secure);
return '<link'.$this->attributes($attributes).'>'.PHP_EOL; return $this->toHtmlString('<link' . $this->attributes($attributes) . '>' . PHP_EOL);
} }
/** /**
@@ -88,13 +109,15 @@ class HtmlBuilder {
* @param string $alt * @param string $alt
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function image($url, $alt = null, $attributes = array(), $secure = null) public function image($url, $alt = null, $attributes = [], $secure = null)
{ {
$attributes['alt'] = $alt; $attributes['alt'] = $alt;
return '<img src="'.$this->url->asset($url, $secure).'"'.$this->attributes($attributes).'>'; return $this->toHtmlString('<img src="' . $this->url->asset($url,
$secure) . '"' . $this->attributes($attributes) . '>');
} }
/** /**
@@ -103,17 +126,18 @@ class HtmlBuilder {
* @param string $url * @param string $url
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function favicon($url, $attributes = array(), $secure = null) public function favicon($url, $attributes = [], $secure = null)
{ {
$defaults = array('rel' => 'shortcut icon', 'type' => 'image/x-icon'); $defaults = ['rel' => 'shortcut icon', 'type' => 'image/x-icon'];
$attributes = $attributes + $defaults; $attributes = $attributes + $defaults;
$attributes['href'] = $this->url->asset($url, $secure); $attributes['href'] = $this->url->asset($url, $secure);
return '<link'.$this->attributes($attributes).'>'.PHP_EOL; return $this->toHtmlString('<link' . $this->attributes($attributes) . '>' . PHP_EOL);
} }
/** /**
@@ -123,15 +147,18 @@ class HtmlBuilder {
* @param string $title * @param string $title
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function link($url, $title = null, $attributes = array(), $secure = null) public function link($url, $title = null, $attributes = [], $secure = null)
{ {
$url = $this->url->to($url, array(), $secure); $url = $this->url->to($url, [], $secure);
if (is_null($title) || $title === false) $title = $url; if (is_null($title) || $title === false) {
$title = $url;
}
return '<a href="'.$url.'"'.$this->attributes($attributes).'>'.$this->entities($title).'</a>'; return $this->toHtmlString('<a href="' . $url . '"' . $this->attributes($attributes) . '>' . $this->entities($title) . '</a>');
} }
/** /**
@@ -140,9 +167,10 @@ class HtmlBuilder {
* @param string $url * @param string $url
* @param string $title * @param string $title
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function secureLink($url, $title = null, $attributes = array()) public function secureLink($url, $title = null, $attributes = [])
{ {
return $this->link($url, $title, $attributes, true); return $this->link($url, $title, $attributes, true);
} }
@@ -154,9 +182,10 @@ class HtmlBuilder {
* @param string $title * @param string $title
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function linkAsset($url, $title = null, $attributes = array(), $secure = null) public function linkAsset($url, $title = null, $attributes = [], $secure = null)
{ {
$url = $this->url->asset($url, $secure); $url = $this->url->asset($url, $secure);
@@ -169,9 +198,10 @@ class HtmlBuilder {
* @param string $url * @param string $url
* @param string $title * @param string $title
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function linkSecureAsset($url, $title = null, $attributes = array()) public function linkSecureAsset($url, $title = null, $attributes = [])
{ {
return $this->linkAsset($url, $title, $attributes, true); return $this->linkAsset($url, $title, $attributes, true);
} }
@@ -183,9 +213,10 @@ class HtmlBuilder {
* @param string $title * @param string $title
* @param array $parameters * @param array $parameters
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function linkRoute($name, $title = null, $parameters = array(), $attributes = array()) public function linkRoute($name, $title = null, $parameters = [], $attributes = [])
{ {
return $this->link($this->url->route($name, $parameters), $title, $attributes); return $this->link($this->url->route($name, $parameters), $title, $attributes);
} }
@@ -197,9 +228,10 @@ class HtmlBuilder {
* @param string $title * @param string $title
* @param array $parameters * @param array $parameters
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function linkAction($action, $title = null, $parameters = array(), $attributes = array()) public function linkAction($action, $title = null, $parameters = [], $attributes = [])
{ {
return $this->link($this->url->action($action, $parameters), $title, $attributes); return $this->link($this->url->action($action, $parameters), $title, $attributes);
} }
@@ -210,9 +242,10 @@ class HtmlBuilder {
* @param string $email * @param string $email
* @param string $title * @param string $title
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function mailto($email, $title = null, $attributes = array()) public function mailto($email, $title = null, $attributes = [])
{ {
$email = $this->email($email); $email = $this->email($email);
@@ -220,13 +253,14 @@ class HtmlBuilder {
$email = $this->obfuscate('mailto:') . $email; $email = $this->obfuscate('mailto:') . $email;
return '<a href="'.$email.'"'.$this->attributes($attributes).'>'.$this->entities($title).'</a>'; return $this->toHtmlString('<a href="' . $email . '"' . $this->attributes($attributes) . '>' . $this->entities($title) . '</a>');
} }
/** /**
* Obfuscate an e-mail address to prevent spam-bots from sniffing it. * Obfuscate an e-mail address to prevent spam-bots from sniffing it.
* *
* @param string $email * @param string $email
*
* @return string * @return string
*/ */
public function email($email) public function email($email)
@@ -239,9 +273,10 @@ class HtmlBuilder {
* *
* @param array $list * @param array $list
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString|string
*/ */
public function ol($list, $attributes = array()) public function ol($list, $attributes = [])
{ {
return $this->listing('ol', $list, $attributes); return $this->listing('ol', $list, $attributes);
} }
@@ -251,9 +286,10 @@ class HtmlBuilder {
* *
* @param array $list * @param array $list
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString|string
*/ */
public function ul($list, $attributes = array()) public function ul($list, $attributes = [])
{ {
return $this->listing('ul', $list, $attributes); return $this->listing('ul', $list, $attributes);
} }
@@ -263,7 +299,8 @@ class HtmlBuilder {
* *
* @param array $list * @param array $list
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function dl(array $list, array $attributes = []) public function dl(array $list, array $attributes = [])
{ {
@@ -271,14 +308,19 @@ class HtmlBuilder {
$html = "<dl{$attributes}>"; $html = "<dl{$attributes}>";
foreach ($list as $key => $value) foreach ($list as $key => $value) {
{ $value = (array) $value;
$html .= "<dt>$key</dt><dd>$value</dd>";
$html .= "<dt>$key</dt>";
foreach ($value as $v_key => $v_value) {
$html .= "<dd>$v_value</dd>";
}
} }
$html .= '</dl>'; $html .= '</dl>';
return $html; return $this->toHtmlString($html);
} }
/** /**
@@ -287,25 +329,27 @@ class HtmlBuilder {
* @param string $type * @param string $type
* @param array $list * @param array $list
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString|string
*/ */
protected function listing($type, $list, $attributes = array()) protected function listing($type, $list, $attributes = [])
{ {
$html = ''; $html = '';
if (count($list) == 0) return $html; if (count($list) == 0) {
return $html;
}
// Essentially we will just spin through the list and build the list of the HTML // Essentially we will just spin through the list and build the list of the HTML
// elements from the array. We will also handled nested lists in case that is // elements from the array. We will also handled nested lists in case that is
// present in the array. Then we will build out the final listing elements. // present in the array. Then we will build out the final listing elements.
foreach ($list as $key => $value) foreach ($list as $key => $value) {
{
$html .= $this->listingElement($key, $type, $value); $html .= $this->listingElement($key, $type, $value);
} }
$attributes = $this->attributes($attributes); $attributes = $this->attributes($attributes);
return "<{$type}{$attributes}>{$html}</{$type}>"; return $this->toHtmlString("<{$type}{$attributes}>{$html}</{$type}>");
} }
/** /**
@@ -314,16 +358,14 @@ class HtmlBuilder {
* @param mixed $key * @param mixed $key
* @param string $type * @param string $type
* @param mixed $value * @param mixed $value
*
* @return string * @return string
*/ */
protected function listingElement($key, $type, $value) protected function listingElement($key, $type, $value)
{ {
if (is_array($value)) if (is_array($value)) {
{
return $this->nestedListing($key, $type, $value); return $this->nestedListing($key, $type, $value);
} } else {
else
{
return '<li>' . e($value) . '</li>'; return '<li>' . e($value) . '</li>';
} }
} }
@@ -334,16 +376,14 @@ class HtmlBuilder {
* @param mixed $key * @param mixed $key
* @param string $type * @param string $type
* @param mixed $value * @param mixed $value
*
* @return string * @return string
*/ */
protected function nestedListing($key, $type, $value) protected function nestedListing($key, $type, $value)
{ {
if (is_int($key)) if (is_int($key)) {
{
return $this->listing($type, $value); return $this->listing($type, $value);
} } else {
else
{
return '<li>' . $key . $this->listing($type, $value) . '</li>'; return '<li>' . $key . $this->listing($type, $value) . '</li>';
} }
} }
@@ -352,17 +392,19 @@ class HtmlBuilder {
* Build an HTML attribute string from an array. * Build an HTML attribute string from an array.
* *
* @param array $attributes * @param array $attributes
*
* @return string * @return string
*/ */
public function attributes($attributes) public function attributes($attributes)
{ {
$html = array(); $html = [];
foreach ((array) $attributes as $key => $value) foreach ((array) $attributes as $key => $value) {
{
$element = $this->attributeElement($key, $value); $element = $this->attributeElement($key, $value);
if ( ! is_null($element)) $html[] = $element; if (! is_null($element)) {
$html[] = $element;
}
} }
return count($html) > 0 ? ' ' . implode(' ', $html) : ''; return count($html) > 0 ? ' ' . implode(' ', $html) : '';
@@ -373,6 +415,7 @@ class HtmlBuilder {
* *
* @param string $key * @param string $key
* @param string $value * @param string $value
*
* @return string * @return string
*/ */
protected function attributeElement($key, $value) protected function attributeElement($key, $value)
@@ -380,35 +423,42 @@ class HtmlBuilder {
// For numeric keys we will assume that the key and the value are the same // For numeric keys we will assume that the key and the value are the same
// as this will convert HTML attributes such as "required" to a correct // as this will convert HTML attributes such as "required" to a correct
// form like required="required" instead of using incorrect numerics. // form like required="required" instead of using incorrect numerics.
if (is_numeric($key)) $key = $value; if (is_numeric($key)) {
$key = $value;
}
if ( ! is_null($value)) return $key.'="'.e($value).'"'; if (! is_null($value)) {
return $key . '="' . e($value) . '"';
}
} }
/** /**
* Obfuscate a string to prevent spam-bots from sniffing it. * Obfuscate a string to prevent spam-bots from sniffing it.
* *
* @param string $value * @param string $value
*
* @return string * @return string
*/ */
public function obfuscate($value) public function obfuscate($value)
{ {
$safe = ''; $safe = '';
foreach (str_split($value) as $letter) foreach (str_split($value) as $letter) {
{ if (ord($letter) > 128) {
if (ord($letter) > 128) return $letter; return $letter;
}
// To properly obfuscate the value, we will randomly convert each letter to // To properly obfuscate the value, we will randomly convert each letter to
// its entity or hexadecimal representation, keeping a bot from sniffing // its entity or hexadecimal representation, keeping a bot from sniffing
// the randomly obfuscated letters out of the string on the responses. // the randomly obfuscated letters out of the string on the responses.
switch (rand(1, 3)) switch (rand(1, 3)) {
{
case 1: case 1:
$safe .= '&#'.ord($letter).';'; break; $safe .= '&#' . ord($letter) . ';';
break;
case 2: case 2:
$safe .= '&#x'.dechex(ord($letter)).';'; break; $safe .= '&#x' . dechex(ord($letter)) . ';';
break;
case 3: case 3:
$safe .= $letter; $safe .= $letter;
@@ -424,7 +474,8 @@ class HtmlBuilder {
* @param string $name * @param string $name
* @param string $content * @param string $content
* @param array $attributes * @param array $attributes
* @return string *
* @return \Illuminate\Support\HtmlString
*/ */
public function meta($name, $content, array $attributes = []) public function meta($name, $content, array $attributes = [])
{ {
@@ -432,7 +483,45 @@ class HtmlBuilder {
$attributes = array_merge($defaults, $attributes); $attributes = array_merge($defaults, $attributes);
return '<meta'.$this->attributes($attributes).'>'.PHP_EOL; return $this->toHtmlString('<meta' . $this->attributes($attributes) . '>' . PHP_EOL);
} }
/**
* Transform the string to an Html serializable object
*
* @param $html
*
* @return \Illuminate\Support\HtmlString
*/
protected function toHtmlString($html)
{
return new HtmlString($html);
}
/**
* Dynamically handle calls to the class.
*
* @param string $method
* @param array $parameters
*
* @return \Illuminate\Contracts\View\View|mixed
*
* @throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
try {
return $this->componentCall($method, $parameters);
} catch (BadMethodCallException $e) {
//
}
try {
return $this->macroCall($method, $parameters);
} catch (BadMethodCallException $e) {
//
}
throw new BadMethodCallException("Method {$method} does not exist.");
}
} }
+9 -4
View File
@@ -1,17 +1,22 @@
<?php namespace Collective\Html; <?php
namespace Collective\Html;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
/** /**
* @see \Collective\Html\HtmlBuilder * @see \Collective\Html\HtmlBuilder
*/ */
class HtmlFacade extends Facade { class HtmlFacade extends Facade
{
/** /**
* Get the registered name of the component. * Get the registered name of the component.
* *
* @return string * @return string
*/ */
protected static function getFacadeAccessor() { return 'html'; } protected static function getFacadeAccessor()
{
return 'html';
}
} }
+10 -10
View File
@@ -1,8 +1,11 @@
<?php namespace Collective\Html; <?php
namespace Collective\Html;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class HtmlServiceProvider extends ServiceProvider { class HtmlServiceProvider extends ServiceProvider
{
/** /**
* Indicates if loading of the provider is deferred. * Indicates if loading of the provider is deferred.
@@ -33,9 +36,8 @@ class HtmlServiceProvider extends ServiceProvider {
*/ */
protected function registerHtmlBuilder() protected function registerHtmlBuilder()
{ {
$this->app->bindShared('html', function($app) $this->app->singleton('html', function ($app) {
{ return new HtmlBuilder($app['url'], $app['view']);
return new HtmlBuilder($app['url']);
}); });
} }
@@ -46,9 +48,8 @@ class HtmlServiceProvider extends ServiceProvider {
*/ */
protected function registerFormBuilder() protected function registerFormBuilder()
{ {
$this->app->bindShared('form', function($app) $this->app->singleton('form', function ($app) {
{ $form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->getToken());
$form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken());
return $form->setSessionStore($app['session.store']); return $form->setSessionStore($app['session.store']);
}); });
@@ -61,7 +62,6 @@ class HtmlServiceProvider extends ServiceProvider {
*/ */
public function provides() public function provides()
{ {
return array('html', 'form', 'Collective\Html\HtmlBuilder', 'Collective\Html\FormBuilder'); return ['html', 'form', 'Collective\Html\HtmlBuilder', 'Collective\Html\FormBuilder'];
} }
} }
+12 -12
View File
@@ -1,7 +1,6 @@
<?php <?php
if ( ! function_exists('link_to')) if (! function_exists('link_to')) {
{
/** /**
* Generate a HTML link. * Generate a HTML link.
* *
@@ -9,16 +8,16 @@ if ( ! function_exists('link_to'))
* @param string $title * @param string $title
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
*
* @return string * @return string
*/ */
function link_to($url, $title = null, $attributes = array(), $secure = null) function link_to($url, $title = null, $attributes = [], $secure = null)
{ {
return app('html')->link($url, $title, $attributes, $secure); return app('html')->link($url, $title, $attributes, $secure);
} }
} }
if ( ! function_exists('link_to_asset')) if (! function_exists('link_to_asset')) {
{
/** /**
* Generate a HTML link to an asset. * Generate a HTML link to an asset.
* *
@@ -26,16 +25,16 @@ if ( ! function_exists('link_to_asset'))
* @param string $title * @param string $title
* @param array $attributes * @param array $attributes
* @param bool $secure * @param bool $secure
*
* @return string * @return string
*/ */
function link_to_asset($url, $title = null, $attributes = array(), $secure = null) function link_to_asset($url, $title = null, $attributes = [], $secure = null)
{ {
return app('html')->linkAsset($url, $title, $attributes, $secure); return app('html')->linkAsset($url, $title, $attributes, $secure);
} }
} }
if ( ! function_exists('link_to_route')) if (! function_exists('link_to_route')) {
{
/** /**
* Generate a HTML link to a named route. * Generate a HTML link to a named route.
* *
@@ -43,16 +42,16 @@ if ( ! function_exists('link_to_route'))
* @param string $title * @param string $title
* @param array $parameters * @param array $parameters
* @param array $attributes * @param array $attributes
*
* @return string * @return string
*/ */
function link_to_route($name, $title = null, $parameters = array(), $attributes = array()) function link_to_route($name, $title = null, $parameters = [], $attributes = [])
{ {
return app('html')->linkRoute($name, $title, $parameters, $attributes); return app('html')->linkRoute($name, $title, $parameters, $attributes);
} }
} }
if ( ! function_exists('link_to_action')) if (! function_exists('link_to_action')) {
{
/** /**
* Generate a HTML link to a controller action. * Generate a HTML link to a controller action.
* *
@@ -60,9 +59,10 @@ if ( ! function_exists('link_to_action'))
* @param string $title * @param string $title
* @param array $parameters * @param array $parameters
* @param array $attributes * @param array $attributes
*
* @return string * @return string
*/ */
function link_to_action($action, $title = null, $parameters = array(), $attributes = array()) function link_to_action($action, $title = null, $parameters = [], $attributes = [])
{ {
return app('html')->linkAction($action, $title, $parameters, $attributes); return app('html')->linkAction($action, $title, $parameters, $attributes);
} }
+108
View File
@@ -0,0 +1,108 @@
<?php
use Carbon\Carbon;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Database\Eloquent\Model;
use Collective\Html\FormBuilder;
use Collective\Html\HtmlBuilder;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Database\Capsule\Manager as Capsule;
use Mockery as m;
class FormAccessibleTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
Capsule::table('models')->truncate();
Model::unguard();
$this->now = Carbon::now();
$this->modelData = [
'string' => 'abcdefghijklmnop',
'email' => 'tj@tjshafer.com',
'created_at' => $this->now,
'updated_at' => $this->now,
];
$this->urlGenerator = new UrlGenerator(new RouteCollection(), Request::create('/foo', 'GET'));
$this->viewFactory = m::mock(Factory::class);
$this->htmlBuilder = new HtmlBuilder($this->urlGenerator, $this->viewFactory);
$this->formBuilder = new FormBuilder($this->htmlBuilder, $this->urlGenerator, $this->viewFactory, 'abc');
}
public function testItCanMutateValuesForForms()
{
$model = new ModelThatUsesForms($this->modelData);
$this->formBuilder->setModel($model);
$this->assertEquals($model->getFormValue('string'), 'ponmlkjihgfedcba');
$this->assertEquals($model->getFormValue('created_at'), $this->now->timestamp);
}
public function testItCanStillMutateValuesForViews()
{
$model = new ModelThatUsesForms($this->modelData);
$this->formBuilder->setModel($model);
$this->assertEquals($model->string, 'ABCDEFGHIJKLMNOP');
$this->assertEquals($model->created_at, '1 second ago');
}
public function testItDoesntRequireTheUseOfThisFeature()
{
$model = new ModelThatDoesntUseForms($this->modelData);
$this->formBuilder->setModel($model);
$this->assertEquals($model->string, 'ABCDEFGHIJKLMNOP');
$this->assertEquals($model->created_at, '1 second ago');
}
}
class ModelThatUsesForms extends Model
{
use FormAccessible;
protected $table = 'models';
public function formStringAttribute($value)
{
return strrev($value);
}
public function getStringAttribute($value)
{
return strtoupper($value);
}
public function formCreatedAtAttribute(Carbon $value)
{
return $value->timestamp;
}
public function getCreatedAtAttribute($value)
{
return '1 second ago';
}
}
class ModelThatDoesntUseForms extends Model
{
protected $table = 'models';
public function getStringAttribute($value)
{
return strtoupper($value);
}
public function getCreatedAtAttribute($value)
{
return '1 second ago';
}
}
+75 -81
View File
@@ -1,27 +1,28 @@
<?php <?php
use Illuminate\Session\Store;
use Mockery as m;
use Illuminate\Http\Request;
use Collective\Html\FormBuilder; use Collective\Html\FormBuilder;
use Collective\Html\HtmlBuilder; use Collective\Html\HtmlBuilder;
use Illuminate\Routing\UrlGenerator; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection; use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Mockery as m;
class FormBuilderTest extends PHPUnit_Framework_TestCase { class FormBuilderTest extends PHPUnit_Framework_TestCase
{
/** /**
* Setup the test environment. * Setup the test environment.
*/ */
public function setUp() public function setUp()
{ {
$this->urlGenerator = new UrlGenerator(new RouteCollection, Request::create('/foo', 'GET')); $this->urlGenerator = new UrlGenerator(new RouteCollection(), Request::create('/foo', 'GET'));
$this->htmlBuilder = new HtmlBuilder($this->urlGenerator); $this->viewFactory = m::mock(Factory::class);
$this->formBuilder = new FormBuilder($this->htmlBuilder, $this->urlGenerator, 'abc'); $this->htmlBuilder = new HtmlBuilder($this->urlGenerator, $this->viewFactory);
$this->formBuilder = new FormBuilder($this->htmlBuilder, $this->urlGenerator, $this->viewFactory, 'abc');
} }
/** /**
* Destroy the test environment. * Destroy the test environment.
*/ */
@@ -30,7 +31,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
m::close(); m::close();
} }
public function testOpeningForm() public function testOpeningForm()
{ {
$form1 = $this->formBuilder->open(['method' => 'GET']); $form1 = $this->formBuilder->open(['method' => 'GET']);
@@ -39,21 +39,21 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$form4 = $this->formBuilder->open(['method' => 'GET', 'accept-charset' => 'UTF-16', 'files' => true]); $form4 = $this->formBuilder->open(['method' => 'GET', 'accept-charset' => 'UTF-16', 'files' => true]);
$form5 = $this->formBuilder->open(['method' => 'PUT']); $form5 = $this->formBuilder->open(['method' => 'PUT']);
$this->assertEquals('<form method="GET" action="http://localhost/foo" accept-charset="UTF-8">', $form1); $this->assertEquals('<form method="GET" action="http://localhost/foo" accept-charset="UTF-8">', $form1);
$this->assertEquals('<form method="POST" action="http://localhost/foo" accept-charset="UTF-8" class="form" id="id-form"><input name="_token" type="hidden" value="abc">', $form2); $this->assertEquals('<form method="POST" action="http://localhost/foo" accept-charset="UTF-8" class="form" id="id-form"><input name="_token" type="hidden" value="abc">',
$form2);
$this->assertEquals('<form method="GET" action="http://localhost/foo" accept-charset="UTF-16">', $form3); $this->assertEquals('<form method="GET" action="http://localhost/foo" accept-charset="UTF-16">', $form3);
$this->assertEquals('<form method="GET" action="http://localhost/foo" accept-charset="UTF-16" enctype="multipart/form-data">', $form4); $this->assertEquals('<form method="GET" action="http://localhost/foo" accept-charset="UTF-16" enctype="multipart/form-data">',
$this->assertEquals('<form method="POST" action="http://localhost/foo" accept-charset="UTF-8"><input name="_method" type="hidden" value="PUT"><input name="_token" type="hidden" value="abc">', $form5); $form4);
$this->assertEquals('<form method="POST" action="http://localhost/foo" accept-charset="UTF-8"><input name="_method" type="hidden" value="PUT"><input name="_token" type="hidden" value="abc">',
$form5);
} }
public function testClosingForm() public function testClosingForm()
{ {
$this->assertEquals('</form>', $this->formBuilder->close()); $this->assertEquals('</form>', $this->formBuilder->close());
} }
public function testFormLabel() public function testFormLabel()
{ {
$form1 = $this->formBuilder->label('foo', 'Foobar'); $form1 = $this->formBuilder->label('foo', 'Foobar');
@@ -63,7 +63,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<label for="foo" class="control-label">Foobar</label>', $form2); $this->assertEquals('<label for="foo" class="control-label">Foobar</label>', $form2);
} }
public function testFormInput() public function testFormInput()
{ {
$form1 = $this->formBuilder->input('text', 'foo'); $form1 = $this->formBuilder->input('text', 'foo');
@@ -75,7 +74,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foobar" type="date">', $form3); $this->assertEquals('<input class="span2" name="foobar" type="date">', $form3);
} }
public function testPasswordsNotFilled() public function testPasswordsNotFilled()
{ {
$this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store')); $this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store'));
@@ -87,7 +85,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input name="password" type="password" value="">', $form1); $this->assertEquals('<input name="password" type="password" value="">', $form1);
} }
public function testFilesNotFilled() public function testFilesNotFilled()
{ {
$this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store')); $this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store'));
@@ -99,7 +96,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input name="img" type="file">', $form); $this->assertEquals('<input name="img" type="file">', $form);
} }
public function testFormText() public function testFormText()
{ {
$form1 = $this->formBuilder->input('text', 'foo'); $form1 = $this->formBuilder->input('text', 'foo');
@@ -113,7 +109,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="text">', $form4); $this->assertEquals('<input class="span2" name="foo" type="text">', $form4);
} }
public function testFormTextRepopulation() public function testFormTextRepopulation()
{ {
$this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store')); $this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store'));
@@ -137,7 +132,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals($input1, $input2); $this->assertEquals($input1, $input2);
} }
public function testFormRepopulationWithMixOfArraysAndObjects() public function testFormRepopulationWithMixOfArraysAndObjects()
{ {
$this->formBuilder->model(['user' => (object) ['password' => 'apple']]); $this->formBuilder->model(['user' => (object) ['password' => 'apple']]);
@@ -149,7 +143,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input name="letters[1]" type="text" value="b">', $input); $this->assertEquals('<input name="letters[1]" type="text" value="b">', $input);
} }
public function testFormPassword() public function testFormPassword()
{ {
$form1 = $this->formBuilder->password('foo'); $form1 = $this->formBuilder->password('foo');
@@ -159,7 +152,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="password" value="">', $form2); $this->assertEquals('<input class="span2" name="foo" type="password" value="">', $form2);
} }
public function testFormHidden() public function testFormHidden()
{ {
$form1 = $this->formBuilder->hidden('foo'); $form1 = $this->formBuilder->hidden('foo');
@@ -171,7 +163,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="hidden">', $form3); $this->assertEquals('<input class="span2" name="foo" type="hidden">', $form3);
} }
public function testFormEmail() public function testFormEmail()
{ {
$form1 = $this->formBuilder->email('foo'); $form1 = $this->formBuilder->email('foo');
@@ -183,7 +174,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="email">', $form3); $this->assertEquals('<input class="span2" name="foo" type="email">', $form3);
} }
public function testFormTel() public function testFormTel()
{ {
$form1 = $this->formBuilder->tel('foo'); $form1 = $this->formBuilder->tel('foo');
@@ -195,7 +185,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="tel">', $form3); $this->assertEquals('<input class="span2" name="foo" type="tel">', $form3);
} }
public function testFormNumber() public function testFormNumber()
{ {
$form1 = $this->formBuilder->number('foo'); $form1 = $this->formBuilder->number('foo');
@@ -216,7 +205,8 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input name="foo" type="date">', $form1); $this->assertEquals('<input name="foo" type="date">', $form1);
$this->assertEquals('<input name="foo" type="date" value="2015-02-20">', $form2); $this->assertEquals('<input name="foo" type="date" value="2015-02-20">', $form2);
$this->assertEquals('<input name="foo" type="date" value="' . \Carbon\Carbon::now()->format('Y-m-d') . '">', $form3); $this->assertEquals('<input name="foo" type="date" value="' . \Carbon\Carbon::now()->format('Y-m-d') . '">',
$form3);
$this->assertEquals('<input class="span2" name="foo" type="date">', $form4); $this->assertEquals('<input class="span2" name="foo" type="date">', $form4);
} }
@@ -227,11 +217,11 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$form3 = $this->formBuilder->time('foo', null, ['class' => 'span2']); $form3 = $this->formBuilder->time('foo', null, ['class' => 'span2']);
$this->assertEquals('<input name="foo" type="time">', $form1); $this->assertEquals('<input name="foo" type="time">', $form1);
$this->assertEquals('<input name="foo" type="time" value="' . \Carbon\Carbon::now()->format('H:i') . '">', $form2); $this->assertEquals('<input name="foo" type="time" value="' . \Carbon\Carbon::now()->format('H:i') . '">',
$form2);
$this->assertEquals('<input class="span2" name="foo" type="time">', $form3); $this->assertEquals('<input class="span2" name="foo" type="time">', $form3);
} }
public function testFormFile() public function testFormFile()
{ {
$form1 = $this->formBuilder->file('foo'); $form1 = $this->formBuilder->file('foo');
@@ -241,7 +231,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="file">', $form2); $this->assertEquals('<input class="span2" name="foo" type="file">', $form2);
} }
public function testFormTextarea() public function testFormTextarea()
{ {
$form1 = $this->formBuilder->textarea('foo'); $form1 = $this->formBuilder->textarea('foo');
@@ -255,25 +244,22 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<textarea name="foo" cols="60" rows="15"></textarea>', $form4); $this->assertEquals('<textarea name="foo" cols="60" rows="15"></textarea>', $form4);
} }
public function testSelect() public function testSelect()
{ {
$select = $this->formBuilder->select( $select = $this->formBuilder->select(
'size', 'size',
['L' => 'Large', 'S' => 'Small'] ['L' => 'Large', 'S' => 'Small']
); );
$this->assertEquals($select, '<select name="size"><option value="L">Large</option><option value="S">Small</option></select>'); $this->assertEquals($select,
'<select name="size"><option value="L">Large</option><option value="S">Small</option></select>');
$select = $this->formBuilder->select( $select = $this->formBuilder->select(
'size', 'size',
['L' => 'Large', 'S' => 'Small'], ['L' => 'Large', 'S' => 'Small'],
'L' 'L'
); );
$this->assertEquals($select, '<select name="size"><option value="L" selected="selected">Large</option><option value="S">Small</option></select>'); $this->assertEquals($select,
'<select name="size"><option value="L" selected="selected">Large</option><option value="S">Small</option></select>');
$select = $this->formBuilder->select( $select = $this->formBuilder->select(
'size', 'size',
@@ -281,9 +267,8 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
null, null,
['class' => 'class-name', 'id' => 'select-id'] ['class' => 'class-name', 'id' => 'select-id']
); );
$this->assertEquals($select, '<select class="class-name" id="select-id" name="size"><option value="L">Large</option><option value="S">Small</option></select>'); $this->assertEquals($select,
'<select class="class-name" id="select-id" name="size"><option value="L">Large</option><option value="S">Small</option></select>');
$this->formBuilder->label('select-name-id'); $this->formBuilder->label('select-name-id');
$select = $this->formBuilder->select( $select = $this->formBuilder->select(
@@ -295,7 +280,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals($select, '<select name="select-name" id="select-name-id"></select>'); $this->assertEquals($select, '<select name="select-name" id="select-name-id"></select>');
} }
public function testFormSelectRepopulation() public function testFormSelectRepopulation()
{ {
$list = ['L' => 'Large', 'M' => 'Medium', 'S' => 'Small']; $list = ['L' => 'Large', 'M' => 'Medium', 'S' => 'Small'];
@@ -304,15 +288,18 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$session->shouldReceive('getOldInput')->twice()->with('size')->andReturn('M'); $session->shouldReceive('getOldInput')->twice()->with('size')->andReturn('M');
$select = $this->formBuilder->select('size', $list, 'S'); $select = $this->formBuilder->select('size', $list, 'S');
$this->assertEquals($select, '<select name="size"><option value="L">Large</option><option value="M" selected="selected">Medium</option><option value="S">Small</option></select>'); $this->assertEquals($select,
'<select name="size"><option value="L">Large</option><option value="M" selected="selected">Medium</option><option value="S">Small</option></select>');
$session->shouldReceive('getOldInput')->twice()->with('size.multi')->andReturn(['L', 'S']); $session->shouldReceive('getOldInput')->twice()->with('size.multi')->andReturn(['L', 'S']);
$select = $this->formBuilder->select('size[multi][]', $list, 'M', ['multiple' => 'multiple']); $select = $this->formBuilder->select('size[multi][]', $list, 'M', ['multiple' => 'multiple']);
$this->assertEquals($select, '<select multiple="multiple" name="size[multi][]"><option value="L" selected="selected">Large</option><option value="M">Medium</option><option value="S" selected="selected">Small</option></select>'); $this->assertEquals($select,
'<select multiple="multiple" name="size[multi][]"><option value="L" selected="selected">Large</option><option value="M">Medium</option><option value="S" selected="selected">Small</option></select>');
$session->shouldReceive('getOldInput')->once()->with('size.key')->andReturn(null); $session->shouldReceive('getOldInput')->once()->with('size.key')->andReturn(null);
$select = $this->formBuilder->select('size[key]', $list); $select = $this->formBuilder->select('size[key]', $list);
$this->assertEquals($select, '<select name="size[key]"><option value="L">Large</option><option value="M">Medium</option><option value="S" selected="selected">Small</option></select>'); $this->assertEquals($select,
'<select name="size[key]"><option value="L">Large</option><option value="M">Medium</option><option value="S" selected="selected">Small</option></select>');
} }
public function testFormWithOptionalPlaceholder() public function testFormWithOptionalPlaceholder()
@@ -323,7 +310,8 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
null, null,
['placeholder' => 'Select One...'] ['placeholder' => 'Select One...']
); );
$this->assertEquals($select, '<select name="size"><option selected="selected" value="">Select One...</option><option value="L">Large</option><option value="S">Small</option></select>'); $this->assertEquals($select,
'<select name="size"><option selected="selected" value="">Select One...</option><option value="L">Large</option><option value="S">Small</option></select>');
$select = $this->formBuilder->select( $select = $this->formBuilder->select(
'size', 'size',
@@ -331,42 +319,44 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
'L', 'L',
['placeholder' => 'Select One...'] ['placeholder' => 'Select One...']
); );
$this->assertEquals($select, '<select name="size"><option value="">Select One...</option><option value="L" selected="selected">Large</option><option value="S">Small</option></select>'); $this->assertEquals($select,
'<select name="size"><option value="">Select One...</option><option value="L" selected="selected">Large</option><option value="S">Small</option></select>');
} }
public function testFormSelectYear() public function testFormSelectYear()
{ {
$select1 = $this->formBuilder->selectYear('year', 2000, 2020); $select1 = (string) $this->formBuilder->selectYear('year', 2000, 2020);
$select2 = $this->formBuilder->selectYear('year', 2000, 2020, null, ['id' => 'foo']); $select2 = (string) $this->formBuilder->selectYear('year', 2000, 2020, null, ['id' => 'foo']);
$select3 = $this->formBuilder->selectYear('year', 2000, 2020, '2000'); $select3 = (string) $this->formBuilder->selectYear('year', 2000, 2020, '2000');
$this->assertContains('<select name="year"><option value="2000">2000</option><option value="2001">2001</option>', $select1); $this->assertContains('<select name="year"><option value="2000">2000</option><option value="2001">2001</option>',
$this->assertContains('<select id="foo" name="year"><option value="2000">2000</option><option value="2001">2001</option>', $select2); $select1);
$this->assertContains('<select name="year"><option value="2000" selected="selected">2000</option><option value="2001">2001</option>', $select3); $this->assertContains('<select id="foo" name="year"><option value="2000">2000</option><option value="2001">2001</option>',
$select2);
$this->assertContains('<select name="year"><option value="2000" selected="selected">2000</option><option value="2001">2001</option>',
$select3);
} }
public function testFormSelectRange() public function testFormSelectRange()
{ {
$range = $this->formBuilder->selectRange('dob', 1900, 2013); $range = (string) $this->formBuilder->selectRange('dob', 1900, 2013);
$this->assertContains('<select name="dob"><option value="1900">1900</option>', $range); $this->assertContains('<select name="dob"><option value="1900">1900</option>', $range);
$this->assertContains('<option value="2013">2013</option>', $range); $this->assertContains('<option value="2013">2013</option>', $range);
} }
public function testFormSelectMonth() public function testFormSelectMonth()
{ {
$month1 = $this->formBuilder->selectMonth('month'); $month1 = (string) $this->formBuilder->selectMonth('month');
$month2 = $this->formBuilder->selectMonth('month', '1'); $month2 = (string) $this->formBuilder->selectMonth('month', '1');
$month3 = $this->formBuilder->selectMonth('month', null, ['id' => 'foo']); $month3 = (string) $this->formBuilder->selectMonth('month', null, ['id' => 'foo']);
$this->assertContains('<select name="month"><option value="1">January</option><option value="2">February</option>', $month1); $this->assertContains('<select name="month"><option value="1">January</option><option value="2">February</option>',
$month1);
$this->assertContains('<select name="month"><option value="1" selected="selected">January</option>', $month2); $this->assertContains('<select name="month"><option value="1" selected="selected">January</option>', $month2);
$this->assertContains('<select id="foo" name="month"><option value="1">January</option>', $month3); $this->assertContains('<select id="foo" name="month"><option value="1">January</option>', $month3);
} }
public function testFormCheckbox() public function testFormCheckbox()
{ {
$this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store')); $this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store'));
@@ -385,7 +375,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="checkbox" value="foobar">', $form4); $this->assertEquals('<input class="span2" name="foo" type="checkbox" value="foobar">', $form4);
} }
public function testFormCheckboxRepopulation() public function testFormCheckboxRepopulation()
{ {
$this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store')); $this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store'));
@@ -409,18 +398,17 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input checked="checked" name="multicheck[]" type="checkbox" value="3">', $check3); $this->assertEquals('<input checked="checked" name="multicheck[]" type="checkbox" value="3">', $check3);
} }
public function testFormCheckboxWithModelRelation() public function testFormCheckboxWithModelRelation()
{ {
$this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store')); $this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store'));
$session->shouldReceive('getOldInput')->withNoArgs()->andReturn(array()); $session->shouldReceive('getOldInput')->withNoArgs()->andReturn([]);
$session->shouldReceive('getOldInput')->with('items')->andReturn(null); $session->shouldReceive('getOldInput')->with('items')->andReturn(null);
$mockModel2 = new StdClass; $mockModel2 = new StdClass();
$mockModel2->id = 2; $mockModel2->id = 2;
$mockModel3 = new StdClass; $mockModel3 = new StdClass();
$mockModel3->id = 3; $mockModel3->id = 3;
$this->setModel(array('items' => new Collection(array($mockModel2, $mockModel3)))); $this->setModel(['items' => new Collection([$mockModel2, $mockModel3])]);
$check1 = $this->formBuilder->checkbox('items[]', 1); $check1 = $this->formBuilder->checkbox('items[]', 1);
$check2 = $this->formBuilder->checkbox('items[]', 2); $check2 = $this->formBuilder->checkbox('items[]', 2);
@@ -433,7 +421,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input checked="checked" name="items[]" type="checkbox" value="4">', $check4); $this->assertEquals('<input checked="checked" name="items[]" type="checkbox" value="4">', $check4);
} }
public function testFormCheckboxWithoutSession() public function testFormCheckboxWithoutSession()
{ {
$form1 = $this->formBuilder->checkbox('foo'); $form1 = $this->formBuilder->checkbox('foo');
@@ -443,7 +430,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input checked="checked" name="foo" type="checkbox" value="foobar">', $form2); $this->assertEquals('<input checked="checked" name="foo" type="checkbox" value="foobar">', $form2);
} }
public function testFormRadio() public function testFormRadio()
{ {
$form1 = $this->formBuilder->input('radio', 'foo'); $form1 = $this->formBuilder->input('radio', 'foo');
@@ -457,7 +443,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" name="foo" type="radio" value="foobar">', $form4); $this->assertEquals('<input class="span2" name="foo" type="radio" value="foobar">', $form4);
} }
public function testFormRadioRepopulation() public function testFormRadioRepopulation()
{ {
$this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store')); $this->formBuilder->setSessionStore($session = m::mock('Illuminate\Session\Store'));
@@ -471,7 +456,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input name="radio" type="radio" value="2">', $radio2); $this->assertEquals('<input name="radio" type="radio" value="2">', $radio2);
} }
public function testFormSubmit() public function testFormSubmit()
{ {
$form1 = $this->formBuilder->submit('foo'); $form1 = $this->formBuilder->submit('foo');
@@ -481,7 +465,6 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input class="span2" type="submit" value="foo">', $form2); $this->assertEquals('<input class="span2" type="submit" value="foo">', $form2);
} }
public function testFormButton() public function testFormButton()
{ {
$form1 = $this->formBuilder->button('foo'); $form1 = $this->formBuilder->button('foo');
@@ -491,14 +474,12 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<button class="span2" type="button">foo</button>', $form2); $this->assertEquals('<button class="span2" type="button">foo</button>', $form2);
} }
public function testResetInput() public function testResetInput()
{ {
$resetInput = $this->formBuilder->reset('foo'); $resetInput = $this->formBuilder->reset('foo');
$this->assertEquals('<input type="reset" value="foo">', $resetInput); $this->assertEquals('<input type="reset" value="foo">', $resetInput);
} }
public function testImageInput() public function testImageInput()
{ {
$url = 'http://laravel.com/'; $url = 'http://laravel.com/';
@@ -507,35 +488,48 @@ class FormBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<input src="' . $url . '" type="image">', $image); $this->assertEquals('<input src="' . $url . '" type="image">', $image);
} }
public function testFormColor()
{
$form1 = $this->formBuilder->color('foo');
$form2 = $this->formBuilder->color('foo', '#ff0000');
$form3 = $this->formBuilder->color('foo', null, ['class' => 'span2']);
$this->assertEquals('<input name="foo" type="color">', $form1);
$this->assertEquals('<input name="foo" type="color" value="#ff0000">', $form2);
$this->assertEquals('<input class="span2" name="foo" type="color">', $form3);
}
protected function setModel(array $data, $object = true) protected function setModel(array $data, $object = true)
{ {
if ($object) $data = new FormBuilderModelStub($data); if ($object) {
$data = new FormBuilderModelStub($data);
}
$this->formBuilder->model($data, ['method' => 'GET']); $this->formBuilder->model($data, ['method' => 'GET']);
} }
} }
class FormBuilderModelStub { class FormBuilderModelStub
{
protected $data; protected $data;
public function __construct(array $data = []) public function __construct(array $data = [])
{ {
foreach ($data as $key => $val) foreach ($data as $key => $val) {
{ if (is_array($val)) {
if (is_array($val)) $val = new self($val); $val = new self($val);
}
$this->data[$key] = $val; $this->data[$key] = $val;
} }
} }
public function __get($key) public function __get($key)
{ {
return $this->data[$key]; return $this->data[$key];
} }
public function __isset($key) public function __isset($key)
{ {
return isset($this->data[$key]); return isset($this->data[$key]);
+16 -12
View File
@@ -1,27 +1,25 @@
<?php <?php
use Illuminate\Session\Store; use Illuminate\Contracts\View\Factory;
use Mockery as m;
use Illuminate\Http\Request;
use Collective\Html\FormBuilder;
use Collective\Html\HtmlBuilder; use Collective\Html\HtmlBuilder;
use Illuminate\Routing\UrlGenerator; use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection; use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;
use Mockery as m;
class HtmlBuilderTest extends PHPUnit_Framework_TestCase { class HtmlBuilderTest extends PHPUnit_Framework_TestCase
{
/** /**
* Setup the test environment. * Setup the test environment.
*/ */
public function setUp() public function setUp()
{ {
$this->urlGenerator = new UrlGenerator(new RouteCollection, Request::create('/foo', 'GET')); $this->urlGenerator = new UrlGenerator(new RouteCollection(), Request::create('/foo', 'GET'));
$this->htmlBuilder = new HtmlBuilder($this->urlGenerator); $this->viewFactory = m::mock(Factory::class);
$this->htmlBuilder = new HtmlBuilder($this->urlGenerator, $this->viewFactory);
} }
/**
* Destroy the test environment.
*/
public function tearDown() public function tearDown()
{ {
m::close(); m::close();
@@ -31,7 +29,7 @@ class HtmlBuilderTest extends PHPUnit_Framework_TestCase {
{ {
$list = [ $list = [
'foo' => 'bar', 'foo' => 'bar',
'bing' => 'baz' 'bing' => 'baz',
]; ];
$attributes = ['class' => 'example']; $attributes = ['class' => 'example'];
@@ -64,4 +62,10 @@ class HtmlBuilderTest extends PHPUnit_Framework_TestCase {
$this->assertEquals('<link rel="shortcut icon" type="image/x-icon" href="' . $target . '">' . PHP_EOL, $result); $this->assertEquals('<link rel="shortcut icon" type="image/x-icon" href="' . $target . '">' . PHP_EOL, $result);
} }
public function testComponentRegistration()
{
$this->htmlBuilder->component('tweet', 'components.tweet', ['handle', 'body', 'date']);
$this->assertTrue($this->htmlBuilder->hasComponent('tweet'));
}
} }