Completed
Pull Request — master (#591)
by Alex
07:12 queued 05:46
created
src/Former/Form/Fields/Choice.php 3 patches
Doc Comments   +4 added lines, -7 removed lines patch added patch discarded remove patch
@@ -188,6 +188,9 @@  discard block
 block discarded – undo
188 188
 		return $element;
189 189
 	}
190 190
 
191
+	/**
192
+	 * @param string $choiceType
193
+	 */
191 194
 	public function getCheckables($choiceType)
192 195
 	{
193 196
 		if (!(is_array($this->value) || $this->value instanceof \ArrayAccess)) {
@@ -292,7 +295,7 @@  discard block
 block discarded – undo
292 295
 	/**
293 296
 	 * Sets the element's type based on options
294 297
 	 *
295
-	 * @return this
298
+	 * @return Choice
296 299
 	 */
297 300
 	protected function setChoiceType()
298 301
 	{
@@ -309,7 +312,6 @@  discard block
 block discarded – undo
309 312
 	/**
310 313
 	 * Select a value in the field's children
311 314
 	 *
312
-	 * @param mixed   $value
313 315
 	 *
314 316
 	 * @return bool
315 317
 	 */
@@ -333,10 +335,6 @@  discard block
 block discarded – undo
333 335
 	/**
334 336
 	 * Set the choices
335 337
 	 *
336
-	 * @param  array   $_choices     The choices as an array
337
-	 * @param  mixed   $selected     Facultative selected entry
338
-	 * @param  boolean $valuesAsKeys Whether the array's values should be used as
339
-	 *                               the option's values instead of the array's keys
340 338
 	 */
341 339
 	public function addChoice($value, $key = null)
342 340
 	{
@@ -349,7 +347,6 @@  discard block
 block discarded – undo
349 347
 	 * Set the choices
350 348
 	 *
351 349
 	 * @param  array   $_choices     The choices as an array
352
-	 * @param  mixed   $selected     Facultative selected entry
353 350
 	 * @param  boolean $valuesAsKeys Whether the array's values should be used as
354 351
 	 *                               the option's values instead of the array's keys
355 352
 	 */
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 				$attributes['disabled'] = true;
218 218
 			}
219 219
 
220
-			if(isset($attributes['name'])) {
220
+			if (isset($attributes['name'])) {
221 221
 				$name = $attributes['name'];
222 222
 				unset($attributes['name']);
223 223
 			} else {
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 				$name .= '[]';
228 228
 			}
229 229
 		
230
-			if(!isset($attributes['id'])) {
230
+			if (!isset($attributes['id'])) {
231 231
 				$attributes['id'] = $this->id.'_'.count($children);
232 232
 			}
233 233
 
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
 		}
283 283
 
284 284
 		$attributes = array('value' => '', 'disabled' => 'disabled');
285
-		if (!(array)$this->value) {
285
+		if (!(array) $this->value) {
286 286
 			$attributes['selected'] = 'selected';
287 287
 		}
288 288
 
@@ -315,11 +315,11 @@  discard block
 block discarded – undo
315 315
 	 */
316 316
 	protected function hasValue($choiceValue)
317 317
 	{
318
-		foreach ((array)$this->value as $key => $value) {
318
+		foreach ((array) $this->value as $key => $value) {
319 319
 			if (is_object($value) && method_exists($value, 'getKey')) {
320 320
 				$value = $value->getKey();
321 321
 			}
322
-			if ($choiceValue === $value || is_numeric($value) && $choiceValue === (int)$value) {
322
+			if ($choiceValue === $value || is_numeric($value) && $choiceValue === (int) $value) {
323 323
 				return true;
324 324
 			}
325 325
 		}
Please login to merge, or discard this patch.
Indentation   +468 added lines, -468 removed lines patch added patch discarded remove patch
@@ -13,477 +13,477 @@
 block discarded – undo
13 13
  */
14 14
 class Choice extends Field
15 15
 {
16
-	/**
17
-	 * Renders the checkables as inline
18
-	 *
19
-	 * @var boolean
20
-	 */
21
-	protected $inline = false;
22
-
23
-	/**
24
-	 * The choice's placeholder
25
-	 *
26
-	 * @var string
27
-	 */
28
-	private $placeholder = null;
29
-
30
-	/**
31
-	 * The choice's options
32
-	 *
33
-	 * @var array
34
-	 */
35
-	protected $options = [
16
+    /**
17
+     * Renders the checkables as inline
18
+     *
19
+     * @var boolean
20
+     */
21
+    protected $inline = false;
22
+
23
+    /**
24
+     * The choice's placeholder
25
+     *
26
+     * @var string
27
+     */
28
+    private $placeholder = null;
29
+
30
+    /**
31
+     * The choice's options
32
+     *
33
+     * @var array
34
+     */
35
+    protected $options = [
36 36
         'isMultiple' => false,
37 37
         'isExpanded' => false,
38 38
     ];
39 39
 
40
-	/**
41
-	 * The choice's choices
42
-	 *
43
-	 * @var array
44
-	 */
45
-	protected $choices = [];
46
-
47
-	/**
48
-	 * The choice's element
49
-	 *
50
-	 * @var string
51
-	 */
52
-	protected $element = 'choice';
53
-
54
-	/**
55
-	 * The choice's self-closing state
56
-	 *
57
-	 * @var boolean
58
-	 */
59
-	protected $isSelfClosing = false;
60
-
61
-	////////////////////////////////////////////////////////////////////
62
-	/////////////////////////// CORE METHODS ///////////////////////////
63
-	////////////////////////////////////////////////////////////////////
64
-
65
-	/**
66
-	 * Easier arguments order for selects
67
-	 *
68
-	 * @param Container $app        The Container instance
69
-	 * @param string    $type       select
70
-	 * @param string    $name       Field name
71
-	 * @param string    $label      Its label
72
-	 * @param array     $choices    The choice's choices
73
-	 * @param string    $selected   The selected choice(s)
74
-	 * @param array     $attributes Attributes
75
-	 */
76
-	public function __construct(Container $app, $type, $name, $label, $choices, $selected, $attributes)
77
-	{
78
-		if ($selected) {
79
-			$this->value = $selected;
80
-		}
81
-		if ($choices) {
82
-			$this->choices($choices);
83
-		}
84
-
85
-		parent::__construct($app, $type, $name, $label, $selected, $attributes);
86
-
87
-		$this->setChoiceType();
88
-
89
-		// Nested models population
90
-		if (Str::contains($this->name, '.') and is_array($this->value) and !empty($this->value) and is_string($this->value[key($this->value)])) {
91
-			$this->fromQuery($this->value);
92
-			$this->value = $selected ?: null;
93
-		}
94
-	}
95
-
96
-	/**
97
-	 * Renders the choice
98
-	 *
99
-	 * @return string A <select> tag
100
-	 */
101
-	public function render()
102
-	{
103
-		$choiceType = $this->getType();
104
-		$this->setFieldClasses();
105
-
106
-		if (!isset($this->attributes['id'])) {
107
-			$this->setAttribute('id', $this->name);
108
-		}
109
-
110
-		switch ($choiceType) {
111
-			case 'select':
112
-				$field = $this->getSelect();
113
-				break;
114
-			case 'checkbox':
115
-			case 'radio':
116
-				$field = $this->getCheckables($choiceType);
117
-				break;
118
-		}
119
-		$this->value = null;
120
-		$content = $field->render();
121
-		return $content;
122
-	}
123
-
124
-	public function getSelect()
125
-	{
126
-		$field = Element::create('select', null, $this->attributes);
127
-
128
-		$name = $this->name;
129
-		if ($this->options['isMultiple']) {
130
-			$field->multiple();
131
-			$name .= '[]';
132
-		}
133
-
134
-		$field->setAttribute('name', $name);
135
-
136
-		$field->nest($this->getOptions());
137
-
138
-		return $field;
139
-	}
140
-
141
-	public function getOptions()
142
-	{
143
-		$children = [];
144
-
145
-		// Add placeholder text if any
146
-		if ($placeholder = $this->getPlaceholder()) {
147
-			$children[] = $placeholder;
148
-		}
149
-
150
-		foreach ($this->choices as $key => $value) {
151
-			if (is_array($value) and !isset($value['value'])) {
152
-				$children[] = $this->getOptGroup($key, $value);
153
-			} else {
154
-				$children[] = $this->getOption($key, $value);
155
-			}
156
-		}
157
-		return $children;
158
-	}
159
-
160
-	public function getOptGroup($label, $options)
161
-	{
162
-		$element = Element::create('optgroup')->label($label);
163
-		$children = [];
164
-		foreach ($options as $key => $value) {
165
-			$option = $this->getOption($key, $value);
166
-			$children[] = $option;
167
-		}
168
-		$element->nest($children);
169
-
170
-		return $element;
171
-	}
172
-
173
-	public function getOption($key, $value)
174
-	{
175
-		if (is_array($value) and isset($value['value'])) {
176
-			$attributes = $value;
177
-			$text = $key;
178
-			$key = null;
179
-		} else {
180
-			$attributes = array('value' => $key);
181
-			$text = $value;
182
-		}
183
-
184
-		$element = Element::create('option', $text, $attributes);
185
-		if ($this->hasValue($attributes['value'])) {
186
-			$element->selected('selected');
187
-		}
188
-
189
-		return $element;
190
-	}
191
-
192
-	public function getCheckables($choiceType)
193
-	{
194
-		if (!(is_array($this->value) || $this->value instanceof \ArrayAccess)) {
195
-			$this->value = explode(',', $this->value);
196
-		}
197
-
198
-		$disabled = isset($this->attributes['disabled']);
199
-		unset($this->attributes['disabled']);
200
-
201
-		$field = Element::create('div', null, $this->attributes);
202
-
203
-		$children = [];
204
-		foreach ($this->choices as $key => $value) {
205
-			$attributes = [];
206
-
207
-			if (is_array($value) and isset($value['value'])) {
208
-				$attributes = $value;
209
-				$label = $key;
210
-				$inputValue = $value['value'];
211
-			} else {
212
-				$attributes = [];
213
-				$label = $value;
214
-				$inputValue = $key;
215
-			}
216
-
217
-			if ($disabled) {
218
-				$attributes['disabled'] = true;
219
-			}
220
-
221
-			if(isset($attributes['name'])) {
222
-				$name = $attributes['name'];
223
-				unset($attributes['name']);
224
-			} else {
225
-				$name = $this->name;
226
-			}
227
-			if ($this->options['isMultiple']) {
228
-				$name .= '[]';
229
-			}
230
-
231
-			if(!isset($attributes['id'])) {
232
-				$attributes['id'] = $this->id.'_'.count($children);
233
-			}
234
-
235
-			// If inline items, add class
236
-			$isInline = $this->inline ? ' '.$this->app['former.framework']->getInlineLabelClass($this) : null;
237
-
238
-			// In Bootsrap 3, don't append the the checkable type (radio/checkbox) as a class if
239
-			// rendering inline.
240
-			$class = $this->app['former']->framework() == 'TwitterBootstrap3' ? trim($isInline) : $choiceType.$isInline;
241
-
242
-			$element = Input::create($choiceType, $name, $inputValue, $attributes);
243
-
244
-			// $element->setAttribute('name', $name);
245
-
246
-			if ($this->hasValue($inputValue)) {
247
-				$element->checked('checked');
248
-			}
249
-			// $attributes['value'] = $key;
250
-			if (!$label) {
251
-				$element = (is_object($field)) ? $field->render() : $field;
252
-			} else {
253
-				$rendered = $element->render();
254
-				$labelElement = Element::create('label', $rendered.$label);
255
-				$element = $labelElement->for($attributes['id'])->class($class);
256
-			}
257
-
258
-			// If BS3, if checkables are stacked, wrap them in a div with the checkable type
259
-			if (!$isInline && $this->app['former']->framework() == 'TwitterBootstrap3') {
260
-				$wrapper = Element::create('div', $element->render())->class($choiceType);
261
-				if ($disabled) {
262
-					$wrapper->addClass('disabled');
263
-				}
264
-				$element = $wrapper;
265
-			}
266
-
267
-			$children[] = $element;
268
-		}
269
-		$field->nest($children);
270
-
271
-		return $field;
272
-	}
273
-
274
-	/**
275
-	 * Get the choice's placeholder
276
-	 *
277
-	 * @return Element
278
-	 */
279
-	protected function getPlaceholder()
280
-	{
281
-		if (!$this->placeholder) {
282
-			return false;
283
-		}
284
-
285
-		$attributes = array('value' => '', 'disabled' => 'disabled');
286
-		if (!(array)$this->value) {
287
-			$attributes['selected'] = 'selected';
288
-		}
289
-
290
-		return Element::create('option', $this->placeholder, $attributes);
291
-	}
292
-
293
-	/**
294
-	 * Sets the element's type based on options
295
-	 *
296
-	 * @return this
297
-	 */
298
-	protected function setChoiceType()
299
-	{
300
-		if ($this->options['isExpanded'] && !$this->options['isMultiple']) {
301
-			$this->setType('radio');
302
-		} elseif ($this->options['isExpanded'] && $this->options['isMultiple']) {
303
-			$this->setType('checkbox');
304
-		} else {
305
-			$this->setType('select');
306
-		}
307
-		return $this;
308
-	}
309
-
310
-	/**
311
-	 * Select a value in the field's children
312
-	 *
313
-	 * @param mixed   $value
314
-	 *
315
-	 * @return bool
316
-	 */
317
-	protected function hasValue($choiceValue)
318
-	{
319
-		foreach ((array)$this->value as $key => $value) {
320
-			if (is_object($value) && method_exists($value, 'getKey')) {
321
-				$value = $value->getKey();
322
-			}
323
-			if ($choiceValue === $value || is_numeric($value) && $choiceValue === (int)$value) {
324
-				return true;
325
-			}
326
-		}
327
-		return false;
328
-	}
329
-
330
-	////////////////////////////////////////////////////////////////////
331
-	////////////////////////// FIELD METHODS ///////////////////////////
332
-	////////////////////////////////////////////////////////////////////
333
-
334
-	/**
335
-	 * Set the choices
336
-	 *
337
-	 * @param  array   $_choices     The choices as an array
338
-	 * @param  mixed   $selected     Facultative selected entry
339
-	 * @param  boolean $valuesAsKeys Whether the array's values should be used as
340
-	 *                               the option's values instead of the array's keys
341
-	 */
342
-	public function addChoice($value, $key = null)
343
-	{
344
-		$this->choices[$key ?? $value] = $value;
345
-
346
-		return $this;
347
-	}
348
-
349
-	/**
350
-	 * Set the choices
351
-	 *
352
-	 * @param  array   $_choices     The choices as an array
353
-	 * @param  mixed   $selected     Facultative selected entry
354
-	 * @param  boolean $valuesAsKeys Whether the array's values should be used as
355
-	 *                               the option's values instead of the array's keys
356
-	 */
357
-	public function choices($_choices, $valuesAsKeys = false)
358
-	{
359
-		$choices = (array) $_choices;
360
-
361
-		// If valuesAsKeys is true, use the values as keys
362
-		if ($valuesAsKeys) {
363
-			foreach ($choices as $value) {
364
-				$this->addChoice($value, $value);
365
-			}
366
-		} else {
367
-			foreach ($choices as $key => $value) {
368
-				$this->addChoice($value, $key);
369
-			}
370
-		}
371
-
372
-		return $this;
373
-	}
374
-
375
-	/**
376
-	 * Creates a list of choices from a range
377
-	 *
378
-	 * @param  integer $from
379
-	 * @param  integer $to
380
-	 * @param  integer $step
381
-	 */
382
-	public function range($from, $to, $step = 1)
383
-	{
384
-		$range = range($from, $to, $step);
385
-		$this->choices($range, true);
386
-
387
-		return $this;
388
-	}
389
-
390
-	/**
391
-	 * Use the results from a Fluent/Eloquent query as choices
392
-	 *
393
-	 * @param  array           $results    An array of Eloquent models
394
-	 * @param  string|function $text       The value to use as text
395
-	 * @param  string|array    $attributes The data to use as attributes
396
-	 * @param  string	       $selected   The default selected item
397
-	 */
398
-	public function fromQuery($results, $text = null, $attributes = null, $selected = null)
399
-	{
400
-		$this->choices(Helpers::queryToArray($results, $text, $attributes))->value($selected);
401
-
402
-		return $this;
403
-	}
404
-
405
-	/**
406
-	 * Add a placeholder to the current select
407
-	 *
408
-	 * @param  string $placeholder The placeholder text
409
-	 */
410
-	public function placeholder($placeholder)
411
-	{
412
-		$this->placeholder = Helpers::translate($placeholder);
413
-
414
-		return $this;
415
-	}
416
-
417
-	/**
418
-	 * Set isMultiple
419
-	 *
420
-	 * @param boolean $isMultiple
421
-	 * @return $this
422
-	 */
423
-	public function multiple($isMultiple = true)
424
-	{
425
-		$this->options['isMultiple'] = $isMultiple;
426
-		$this->setChoiceType();
427
-
428
-		return $this;
429
-	}
430
-
431
-	/**
432
-	 * Set isExpanded
433
-	 *
434
-	 * @param boolean $isExpanded
435
-	 * @return $this
436
-	 */
437
-	public function expanded($isExpanded = true)
438
-	{
439
-		$this->options['isExpanded'] = $isExpanded;
440
-		$this->setChoiceType();
441
-
442
-		return $this;
443
-	}
444
-
445
-	/**
446
-	 * Set the choices as inline (for expanded items)
447
-	 */
448
-	public function inline($isInline = true)
449
-	{
450
-		$this->inline = $isInline;
451
-
452
-		return $this;
453
-	}
454
-
455
-	/**
456
-	 * Set the choices as stacked (for expanded items)
457
-	 */
458
-	public function stacked($isStacked = true)
459
-	{
460
-		$this->inline = !$isStacked;
461
-
462
-		return $this;
463
-	}
464
-
465
-	/**
466
-	 * Check if field is a checkbox or a radio
467
-	 *
468
-	 * @return boolean
469
-	 */
470
-	public function isCheckable()
471
-	{
472
-		return $this->options['isExpanded'];
473
-	}
474
-
475
-	////////////////////////////////////////////////////////////////////
476
-	////////////////////////////// HELPERS /////////////////////////////
477
-	////////////////////////////////////////////////////////////////////
478
-
479
-	/**
480
-	 * Returns the current choices in memory for manipulations
481
-	 *
482
-	 * @return array The current choices array
483
-	 */
484
-	public function getChoices()
485
-	{
486
-		return $this->choices;
487
-	}
40
+    /**
41
+     * The choice's choices
42
+     *
43
+     * @var array
44
+     */
45
+    protected $choices = [];
46
+
47
+    /**
48
+     * The choice's element
49
+     *
50
+     * @var string
51
+     */
52
+    protected $element = 'choice';
53
+
54
+    /**
55
+     * The choice's self-closing state
56
+     *
57
+     * @var boolean
58
+     */
59
+    protected $isSelfClosing = false;
60
+
61
+    ////////////////////////////////////////////////////////////////////
62
+    /////////////////////////// CORE METHODS ///////////////////////////
63
+    ////////////////////////////////////////////////////////////////////
64
+
65
+    /**
66
+     * Easier arguments order for selects
67
+     *
68
+     * @param Container $app        The Container instance
69
+     * @param string    $type       select
70
+     * @param string    $name       Field name
71
+     * @param string    $label      Its label
72
+     * @param array     $choices    The choice's choices
73
+     * @param string    $selected   The selected choice(s)
74
+     * @param array     $attributes Attributes
75
+     */
76
+    public function __construct(Container $app, $type, $name, $label, $choices, $selected, $attributes)
77
+    {
78
+        if ($selected) {
79
+            $this->value = $selected;
80
+        }
81
+        if ($choices) {
82
+            $this->choices($choices);
83
+        }
84
+
85
+        parent::__construct($app, $type, $name, $label, $selected, $attributes);
86
+
87
+        $this->setChoiceType();
88
+
89
+        // Nested models population
90
+        if (Str::contains($this->name, '.') and is_array($this->value) and !empty($this->value) and is_string($this->value[key($this->value)])) {
91
+            $this->fromQuery($this->value);
92
+            $this->value = $selected ?: null;
93
+        }
94
+    }
95
+
96
+    /**
97
+     * Renders the choice
98
+     *
99
+     * @return string A <select> tag
100
+     */
101
+    public function render()
102
+    {
103
+        $choiceType = $this->getType();
104
+        $this->setFieldClasses();
105
+
106
+        if (!isset($this->attributes['id'])) {
107
+            $this->setAttribute('id', $this->name);
108
+        }
109
+
110
+        switch ($choiceType) {
111
+            case 'select':
112
+                $field = $this->getSelect();
113
+                break;
114
+            case 'checkbox':
115
+            case 'radio':
116
+                $field = $this->getCheckables($choiceType);
117
+                break;
118
+        }
119
+        $this->value = null;
120
+        $content = $field->render();
121
+        return $content;
122
+    }
123
+
124
+    public function getSelect()
125
+    {
126
+        $field = Element::create('select', null, $this->attributes);
127
+
128
+        $name = $this->name;
129
+        if ($this->options['isMultiple']) {
130
+            $field->multiple();
131
+            $name .= '[]';
132
+        }
133
+
134
+        $field->setAttribute('name', $name);
135
+
136
+        $field->nest($this->getOptions());
137
+
138
+        return $field;
139
+    }
140
+
141
+    public function getOptions()
142
+    {
143
+        $children = [];
144
+
145
+        // Add placeholder text if any
146
+        if ($placeholder = $this->getPlaceholder()) {
147
+            $children[] = $placeholder;
148
+        }
149
+
150
+        foreach ($this->choices as $key => $value) {
151
+            if (is_array($value) and !isset($value['value'])) {
152
+                $children[] = $this->getOptGroup($key, $value);
153
+            } else {
154
+                $children[] = $this->getOption($key, $value);
155
+            }
156
+        }
157
+        return $children;
158
+    }
159
+
160
+    public function getOptGroup($label, $options)
161
+    {
162
+        $element = Element::create('optgroup')->label($label);
163
+        $children = [];
164
+        foreach ($options as $key => $value) {
165
+            $option = $this->getOption($key, $value);
166
+            $children[] = $option;
167
+        }
168
+        $element->nest($children);
169
+
170
+        return $element;
171
+    }
172
+
173
+    public function getOption($key, $value)
174
+    {
175
+        if (is_array($value) and isset($value['value'])) {
176
+            $attributes = $value;
177
+            $text = $key;
178
+            $key = null;
179
+        } else {
180
+            $attributes = array('value' => $key);
181
+            $text = $value;
182
+        }
183
+
184
+        $element = Element::create('option', $text, $attributes);
185
+        if ($this->hasValue($attributes['value'])) {
186
+            $element->selected('selected');
187
+        }
188
+
189
+        return $element;
190
+    }
191
+
192
+    public function getCheckables($choiceType)
193
+    {
194
+        if (!(is_array($this->value) || $this->value instanceof \ArrayAccess)) {
195
+            $this->value = explode(',', $this->value);
196
+        }
197
+
198
+        $disabled = isset($this->attributes['disabled']);
199
+        unset($this->attributes['disabled']);
200
+
201
+        $field = Element::create('div', null, $this->attributes);
202
+
203
+        $children = [];
204
+        foreach ($this->choices as $key => $value) {
205
+            $attributes = [];
206
+
207
+            if (is_array($value) and isset($value['value'])) {
208
+                $attributes = $value;
209
+                $label = $key;
210
+                $inputValue = $value['value'];
211
+            } else {
212
+                $attributes = [];
213
+                $label = $value;
214
+                $inputValue = $key;
215
+            }
216
+
217
+            if ($disabled) {
218
+                $attributes['disabled'] = true;
219
+            }
220
+
221
+            if(isset($attributes['name'])) {
222
+                $name = $attributes['name'];
223
+                unset($attributes['name']);
224
+            } else {
225
+                $name = $this->name;
226
+            }
227
+            if ($this->options['isMultiple']) {
228
+                $name .= '[]';
229
+            }
230
+
231
+            if(!isset($attributes['id'])) {
232
+                $attributes['id'] = $this->id.'_'.count($children);
233
+            }
234
+
235
+            // If inline items, add class
236
+            $isInline = $this->inline ? ' '.$this->app['former.framework']->getInlineLabelClass($this) : null;
237
+
238
+            // In Bootsrap 3, don't append the the checkable type (radio/checkbox) as a class if
239
+            // rendering inline.
240
+            $class = $this->app['former']->framework() == 'TwitterBootstrap3' ? trim($isInline) : $choiceType.$isInline;
241
+
242
+            $element = Input::create($choiceType, $name, $inputValue, $attributes);
243
+
244
+            // $element->setAttribute('name', $name);
245
+
246
+            if ($this->hasValue($inputValue)) {
247
+                $element->checked('checked');
248
+            }
249
+            // $attributes['value'] = $key;
250
+            if (!$label) {
251
+                $element = (is_object($field)) ? $field->render() : $field;
252
+            } else {
253
+                $rendered = $element->render();
254
+                $labelElement = Element::create('label', $rendered.$label);
255
+                $element = $labelElement->for($attributes['id'])->class($class);
256
+            }
257
+
258
+            // If BS3, if checkables are stacked, wrap them in a div with the checkable type
259
+            if (!$isInline && $this->app['former']->framework() == 'TwitterBootstrap3') {
260
+                $wrapper = Element::create('div', $element->render())->class($choiceType);
261
+                if ($disabled) {
262
+                    $wrapper->addClass('disabled');
263
+                }
264
+                $element = $wrapper;
265
+            }
266
+
267
+            $children[] = $element;
268
+        }
269
+        $field->nest($children);
270
+
271
+        return $field;
272
+    }
273
+
274
+    /**
275
+     * Get the choice's placeholder
276
+     *
277
+     * @return Element
278
+     */
279
+    protected function getPlaceholder()
280
+    {
281
+        if (!$this->placeholder) {
282
+            return false;
283
+        }
284
+
285
+        $attributes = array('value' => '', 'disabled' => 'disabled');
286
+        if (!(array)$this->value) {
287
+            $attributes['selected'] = 'selected';
288
+        }
289
+
290
+        return Element::create('option', $this->placeholder, $attributes);
291
+    }
292
+
293
+    /**
294
+     * Sets the element's type based on options
295
+     *
296
+     * @return this
297
+     */
298
+    protected function setChoiceType()
299
+    {
300
+        if ($this->options['isExpanded'] && !$this->options['isMultiple']) {
301
+            $this->setType('radio');
302
+        } elseif ($this->options['isExpanded'] && $this->options['isMultiple']) {
303
+            $this->setType('checkbox');
304
+        } else {
305
+            $this->setType('select');
306
+        }
307
+        return $this;
308
+    }
309
+
310
+    /**
311
+     * Select a value in the field's children
312
+     *
313
+     * @param mixed   $value
314
+     *
315
+     * @return bool
316
+     */
317
+    protected function hasValue($choiceValue)
318
+    {
319
+        foreach ((array)$this->value as $key => $value) {
320
+            if (is_object($value) && method_exists($value, 'getKey')) {
321
+                $value = $value->getKey();
322
+            }
323
+            if ($choiceValue === $value || is_numeric($value) && $choiceValue === (int)$value) {
324
+                return true;
325
+            }
326
+        }
327
+        return false;
328
+    }
329
+
330
+    ////////////////////////////////////////////////////////////////////
331
+    ////////////////////////// FIELD METHODS ///////////////////////////
332
+    ////////////////////////////////////////////////////////////////////
333
+
334
+    /**
335
+     * Set the choices
336
+     *
337
+     * @param  array   $_choices     The choices as an array
338
+     * @param  mixed   $selected     Facultative selected entry
339
+     * @param  boolean $valuesAsKeys Whether the array's values should be used as
340
+     *                               the option's values instead of the array's keys
341
+     */
342
+    public function addChoice($value, $key = null)
343
+    {
344
+        $this->choices[$key ?? $value] = $value;
345
+
346
+        return $this;
347
+    }
348
+
349
+    /**
350
+     * Set the choices
351
+     *
352
+     * @param  array   $_choices     The choices as an array
353
+     * @param  mixed   $selected     Facultative selected entry
354
+     * @param  boolean $valuesAsKeys Whether the array's values should be used as
355
+     *                               the option's values instead of the array's keys
356
+     */
357
+    public function choices($_choices, $valuesAsKeys = false)
358
+    {
359
+        $choices = (array) $_choices;
360
+
361
+        // If valuesAsKeys is true, use the values as keys
362
+        if ($valuesAsKeys) {
363
+            foreach ($choices as $value) {
364
+                $this->addChoice($value, $value);
365
+            }
366
+        } else {
367
+            foreach ($choices as $key => $value) {
368
+                $this->addChoice($value, $key);
369
+            }
370
+        }
371
+
372
+        return $this;
373
+    }
374
+
375
+    /**
376
+     * Creates a list of choices from a range
377
+     *
378
+     * @param  integer $from
379
+     * @param  integer $to
380
+     * @param  integer $step
381
+     */
382
+    public function range($from, $to, $step = 1)
383
+    {
384
+        $range = range($from, $to, $step);
385
+        $this->choices($range, true);
386
+
387
+        return $this;
388
+    }
389
+
390
+    /**
391
+     * Use the results from a Fluent/Eloquent query as choices
392
+     *
393
+     * @param  array           $results    An array of Eloquent models
394
+     * @param  string|function $text       The value to use as text
395
+     * @param  string|array    $attributes The data to use as attributes
396
+     * @param  string	       $selected   The default selected item
397
+     */
398
+    public function fromQuery($results, $text = null, $attributes = null, $selected = null)
399
+    {
400
+        $this->choices(Helpers::queryToArray($results, $text, $attributes))->value($selected);
401
+
402
+        return $this;
403
+    }
404
+
405
+    /**
406
+     * Add a placeholder to the current select
407
+     *
408
+     * @param  string $placeholder The placeholder text
409
+     */
410
+    public function placeholder($placeholder)
411
+    {
412
+        $this->placeholder = Helpers::translate($placeholder);
413
+
414
+        return $this;
415
+    }
416
+
417
+    /**
418
+     * Set isMultiple
419
+     *
420
+     * @param boolean $isMultiple
421
+     * @return $this
422
+     */
423
+    public function multiple($isMultiple = true)
424
+    {
425
+        $this->options['isMultiple'] = $isMultiple;
426
+        $this->setChoiceType();
427
+
428
+        return $this;
429
+    }
430
+
431
+    /**
432
+     * Set isExpanded
433
+     *
434
+     * @param boolean $isExpanded
435
+     * @return $this
436
+     */
437
+    public function expanded($isExpanded = true)
438
+    {
439
+        $this->options['isExpanded'] = $isExpanded;
440
+        $this->setChoiceType();
441
+
442
+        return $this;
443
+    }
444
+
445
+    /**
446
+     * Set the choices as inline (for expanded items)
447
+     */
448
+    public function inline($isInline = true)
449
+    {
450
+        $this->inline = $isInline;
451
+
452
+        return $this;
453
+    }
454
+
455
+    /**
456
+     * Set the choices as stacked (for expanded items)
457
+     */
458
+    public function stacked($isStacked = true)
459
+    {
460
+        $this->inline = !$isStacked;
461
+
462
+        return $this;
463
+    }
464
+
465
+    /**
466
+     * Check if field is a checkbox or a radio
467
+     *
468
+     * @return boolean
469
+     */
470
+    public function isCheckable()
471
+    {
472
+        return $this->options['isExpanded'];
473
+    }
474
+
475
+    ////////////////////////////////////////////////////////////////////
476
+    ////////////////////////////// HELPERS /////////////////////////////
477
+    ////////////////////////////////////////////////////////////////////
478
+
479
+    /**
480
+     * Returns the current choices in memory for manipulations
481
+     *
482
+     * @return array The current choices array
483
+     */
484
+    public function getChoices()
485
+    {
486
+        return $this->choices;
487
+    }
488 488
 
489 489
 }
Please login to merge, or discard this patch.
src/Former/Traits/FormerObject.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -181,7 +181,7 @@
 block discarded – undo
181 181
 	/**
182 182
 	 * Set the modifiers from initial method call
183 183
 	 *
184
-	 * @return $this
184
+	 * @return string
185 185
 	 */
186 186
 	public function getModifiers()
187 187
 	{
Please login to merge, or discard this patch.
Indentation   +187 added lines, -187 removed lines patch added patch discarded remove patch
@@ -10,192 +10,192 @@
 block discarded – undo
10 10
  */
11 11
 abstract class FormerObject extends Element
12 12
 {
13
-	/**
14
-	 * The field's name
15
-	 *
16
-	 * @var string
17
-	 */
18
-	protected $name;
19
-
20
-	/**
21
-	 * The field type
22
-	 *
23
-	 * @var string
24
-	 */
25
-	protected $type;
26
-
27
-	/**
28
-	 * A list of class properties to be added to attributes
29
-	 *
30
-	 * @var array
31
-	 */
32
-	protected $injectedProperties = array('name');
33
-
34
-	/**
35
-	 * The field's modifiers from method call
36
-	 *
37
-	 * @var string
38
-	 */
39
-	protected $modifiers;
40
-
41
-	////////////////////////////////////////////////////////////////////
42
-	/////////////////////////// ID AND LABELS //////////////////////////
43
-	////////////////////////////////////////////////////////////////////
44
-
45
-	/**
46
-	 * Create an unique ID and return it
47
-	 *
48
-	 * @return string
49
-	 */
50
-	public function getCreatedId()
51
-	{
52
-		$this->setId();
53
-
54
-		return $this->attributes['id'];
55
-	}
56
-
57
-	/**
58
-	 * Set the matching ID on a field if possible
59
-	 */
60
-	protected function setId()
61
-	{
62
-		if (!array_key_exists('id', $this->attributes) and
63
-			in_array($this->name, $this->app['former']->labels)
64
-		) {
65
-			// Set and save the field's ID
66
-			$id                         = $this->getUniqueId($this->name);
67
-			$this->attributes['id']     = $id;
68
-			$this->app['former']->ids[] = $id;
69
-		}
70
-	}
71
-
72
-	/**
73
-	 * Get an unique ID for a field from its name
74
-	 *
75
-	 * @param string $name
76
-	 *
77
-	 * @return string
78
-	 */
79
-	protected function getUniqueId($name)
80
-	{
81
-		$names = &$this->app['former']->names;
82
-
83
-		if (array_key_exists($name, $names)) {
84
-			$count = $names[$name] + 1;
85
-			$names[$name] = $count;
86
-			return $name . '-' . $count;
87
-		}
88
-
89
-		$names[$name] = 1;
90
-		return $name;
91
-	}
92
-
93
-	/**
94
-	 * Runs the frameworks getFieldClasses method on this
95
-	 *
96
-	 * @return $this
97
-	 */
98
-	protected function setFieldClasses()
99
-	{
100
-		$framework = isset($this->app['former.form.framework']) ? $this->app['former.form.framework'] : $this->app['former.framework'];
101
-		$framework->getFieldClasses($this, $this->modifiers);
102
-
103
-		return $this;
104
-	}
105
-
106
-	/**
107
-	 * Render the FormerObject and set its id
108
-	 *
109
-	 * @return string
110
-	 */
111
-	public function render()
112
-	{
113
-		// Set the proper ID according to the label
114
-		$this->setId();
115
-
116
-		if($this instanceof Field) {
117
-			$this->setFieldClasses();
118
-		}
119
-
120
-		// Encode HTML value
121
-		$isButton = ($this instanceof Field) ? $this->isButton() : false;
122
-		if (!$isButton and is_string($this->value)) {
123
-			$this->value = Helpers::encode($this->value);
124
-		}
125
-
126
-		return parent::render();
127
-	}
128
-
129
-	////////////////////////////////////////////////////////////////////
130
-	////////////////////////////// GETTERS /////////////////////////////
131
-	////////////////////////////////////////////////////////////////////
132
-
133
-	/**
134
-	 * Get the object's name
135
-	 *
136
-	 * @return string
137
-	 */
138
-	public function getName()
139
-	{
140
-		return $this->name;
141
-	}
142
-
143
-	////////////////////////////////////////////////////////////////////
144
-	//////////////////////////// OBJECT TYPE ///////////////////////////
145
-	////////////////////////////////////////////////////////////////////
146
-
147
-	/**
148
-	 * Get the object's type
149
-	 *
150
-	 * @return string
151
-	 */
152
-	public function getType()
153
-	{
154
-		return $this->type;
155
-	}
156
-
157
-	/**
158
-	 * Change a object's type
159
-	 *
160
-	 * @param string $type
161
-	 */
162
-	public function setType($type)
163
-	{
164
-		$this->type = $type;
165
-
166
-		return $this;
167
-	}
168
-
169
-	/**
170
-	 * Check if an object is of a certain type
171
-	 *
172
-	 * @return boolean
173
-	 */
174
-	public function isOfType()
175
-	{
176
-		$types = func_get_args();
177
-
178
-		return in_array($this->type, $types);
179
-	}
13
+    /**
14
+     * The field's name
15
+     *
16
+     * @var string
17
+     */
18
+    protected $name;
19
+
20
+    /**
21
+     * The field type
22
+     *
23
+     * @var string
24
+     */
25
+    protected $type;
26
+
27
+    /**
28
+     * A list of class properties to be added to attributes
29
+     *
30
+     * @var array
31
+     */
32
+    protected $injectedProperties = array('name');
33
+
34
+    /**
35
+     * The field's modifiers from method call
36
+     *
37
+     * @var string
38
+     */
39
+    protected $modifiers;
40
+
41
+    ////////////////////////////////////////////////////////////////////
42
+    /////////////////////////// ID AND LABELS //////////////////////////
43
+    ////////////////////////////////////////////////////////////////////
44
+
45
+    /**
46
+     * Create an unique ID and return it
47
+     *
48
+     * @return string
49
+     */
50
+    public function getCreatedId()
51
+    {
52
+        $this->setId();
53
+
54
+        return $this->attributes['id'];
55
+    }
56
+
57
+    /**
58
+     * Set the matching ID on a field if possible
59
+     */
60
+    protected function setId()
61
+    {
62
+        if (!array_key_exists('id', $this->attributes) and
63
+            in_array($this->name, $this->app['former']->labels)
64
+        ) {
65
+            // Set and save the field's ID
66
+            $id                         = $this->getUniqueId($this->name);
67
+            $this->attributes['id']     = $id;
68
+            $this->app['former']->ids[] = $id;
69
+        }
70
+    }
71
+
72
+    /**
73
+     * Get an unique ID for a field from its name
74
+     *
75
+     * @param string $name
76
+     *
77
+     * @return string
78
+     */
79
+    protected function getUniqueId($name)
80
+    {
81
+        $names = &$this->app['former']->names;
82
+
83
+        if (array_key_exists($name, $names)) {
84
+            $count = $names[$name] + 1;
85
+            $names[$name] = $count;
86
+            return $name . '-' . $count;
87
+        }
88
+
89
+        $names[$name] = 1;
90
+        return $name;
91
+    }
92
+
93
+    /**
94
+     * Runs the frameworks getFieldClasses method on this
95
+     *
96
+     * @return $this
97
+     */
98
+    protected function setFieldClasses()
99
+    {
100
+        $framework = isset($this->app['former.form.framework']) ? $this->app['former.form.framework'] : $this->app['former.framework'];
101
+        $framework->getFieldClasses($this, $this->modifiers);
102
+
103
+        return $this;
104
+    }
105
+
106
+    /**
107
+     * Render the FormerObject and set its id
108
+     *
109
+     * @return string
110
+     */
111
+    public function render()
112
+    {
113
+        // Set the proper ID according to the label
114
+        $this->setId();
115
+
116
+        if($this instanceof Field) {
117
+            $this->setFieldClasses();
118
+        }
119
+
120
+        // Encode HTML value
121
+        $isButton = ($this instanceof Field) ? $this->isButton() : false;
122
+        if (!$isButton and is_string($this->value)) {
123
+            $this->value = Helpers::encode($this->value);
124
+        }
125
+
126
+        return parent::render();
127
+    }
128
+
129
+    ////////////////////////////////////////////////////////////////////
130
+    ////////////////////////////// GETTERS /////////////////////////////
131
+    ////////////////////////////////////////////////////////////////////
132
+
133
+    /**
134
+     * Get the object's name
135
+     *
136
+     * @return string
137
+     */
138
+    public function getName()
139
+    {
140
+        return $this->name;
141
+    }
142
+
143
+    ////////////////////////////////////////////////////////////////////
144
+    //////////////////////////// OBJECT TYPE ///////////////////////////
145
+    ////////////////////////////////////////////////////////////////////
146
+
147
+    /**
148
+     * Get the object's type
149
+     *
150
+     * @return string
151
+     */
152
+    public function getType()
153
+    {
154
+        return $this->type;
155
+    }
156
+
157
+    /**
158
+     * Change a object's type
159
+     *
160
+     * @param string $type
161
+     */
162
+    public function setType($type)
163
+    {
164
+        $this->type = $type;
165
+
166
+        return $this;
167
+    }
168
+
169
+    /**
170
+     * Check if an object is of a certain type
171
+     *
172
+     * @return boolean
173
+     */
174
+    public function isOfType()
175
+    {
176
+        $types = func_get_args();
177
+
178
+        return in_array($this->type, $types);
179
+    }
180 180
 	
181
-	/**
182
-	 * Set the modifiers from initial method call
183
-	 *
184
-	 * @return $this
185
-	 */
186
-	public function getModifiers()
187
-	{
188
-		return $this->modifiers;
189
-	}
190
-
191
-	/**
192
-	 * Set the modifiers from initial method call
193
-	 *
194
-	 * @return $this
195
-	 */
196
-	public function setModifiers($modifiers)
197
-	{
198
-		$this->modifiers = $modifiers;
199
-		return $this;
200
-	}
181
+    /**
182
+     * Set the modifiers from initial method call
183
+     *
184
+     * @return $this
185
+     */
186
+    public function getModifiers()
187
+    {
188
+        return $this->modifiers;
189
+    }
190
+
191
+    /**
192
+     * Set the modifiers from initial method call
193
+     *
194
+     * @return $this
195
+     */
196
+    public function setModifiers($modifiers)
197
+    {
198
+        $this->modifiers = $modifiers;
199
+        return $this;
200
+    }
201 201
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 		if (array_key_exists($name, $names)) {
84 84
 			$count = $names[$name] + 1;
85 85
 			$names[$name] = $count;
86
-			return $name . '-' . $count;
86
+			return $name.'-'.$count;
87 87
 		}
88 88
 
89 89
 		$names[$name] = 1;
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 		// Set the proper ID according to the label
114 114
 		$this->setId();
115 115
 
116
-		if($this instanceof Field) {
116
+		if ($this instanceof Field) {
117 117
 			$this->setFieldClasses();
118 118
 		}
119 119
 
Please login to merge, or discard this patch.
src/Former/Former.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -147,10 +147,10 @@  discard block
 block discarded – undo
147 147
 
148 148
 		// Checking for any supplementary classes
149 149
 		$modifiers = explode('_', $method);
150
-		$method  = array_pop($modifiers);
150
+		$method = array_pop($modifiers);
151 151
 		
152 152
 		// Dispatch to the different Form\Fields
153
-		$field     = $this->dispatch->toFields($method, $parameters);
153
+		$field = $this->dispatch->toFields($method, $parameters);
154 154
 		$field->setModifiers($modifiers);
155 155
 		$field->addClass('');
156 156
 		
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 		$this->setOption('framework', $framework);
351 351
 
352 352
 		$framework = $this->getFrameworkInstance($framework);
353
-		$this->app->bind('former.framework', function ($app) use ($framework) {
353
+		$this->app->bind('former.framework', function($app) use ($framework) {
354 354
 			return $framework;
355 355
 		});
356 356
 	}
@@ -370,9 +370,9 @@  discard block
 block discarded – undo
370 370
 		//get interfaces of the given framework
371 371
 		$interfaces = class_exists($framework) ? class_implements($framework) : array();
372 372
 
373
-		if(class_exists($formerClass)) {
373
+		if (class_exists($formerClass)) {
374 374
 			$returnClass = $formerClass;
375
-		} elseif(class_exists($framework) && isset($interfaces['Former\Interfaces\FrameworkInterface'])) {
375
+		} elseif (class_exists($framework) && isset($interfaces['Former\Interfaces\FrameworkInterface'])) {
376 376
 			// We have some outside class, lets return it.
377 377
 			$returnClass = $framework;
378 378
 		} else {
Please login to merge, or discard this patch.
Indentation   +479 added lines, -479 removed lines patch added patch discarded remove patch
@@ -14,483 +14,483 @@
 block discarded – undo
14 14
  */
15 15
 class Former
16 16
 {
17
-	// Instances
18
-	////////////////////////////////////////////////////////////////////
19
-
20
-
21
-	/**
22
-	 * The current environment
23
-	 *
24
-	 * @var \Illuminate\Container\Container
25
-	 */
26
-	protected $app;
27
-
28
-	/**
29
-	 * The Method Dispatcher
30
-	 *
31
-	 * @var MethodDispatcher
32
-	 */
33
-	protected $dispatch;
34
-
35
-	// Informations
36
-	////////////////////////////////////////////////////////////////////
37
-
38
-	/**
39
-	 * The form's errors
40
-	 *
41
-	 * @var Message
42
-	 */
43
-	protected $errors;
44
-
45
-	/**
46
-	 * An array of rules to use
47
-	 *
48
-	 * @var array
49
-	 */
50
-	protected $rules = array();
51
-
52
-	/**
53
-	 * An array of field macros
54
-	 *
55
-	 * @var array
56
-	 */
57
-	protected $macros = array();
58
-
59
-	/**
60
-	 * The labels created so far
61
-	 *
62
-	 * @var array
63
-	 */
64
-	public $labels = array();
65
-
66
-	/**
67
-	 * The IDs created so far
68
-	 *
69
-	 * @var array
70
-	 */
71
-	public $ids = array();
72
-
73
-	/**
74
-	 * A lookup table where the key is the input name,
75
-	 * and the value is number of times seen. This is
76
-	 * used to calculate unique ids.
77
-	 *
78
-	 * @var array
79
-	 */
80
-	public $names = array();
81
-
82
-	// Namespaces
83
-	////////////////////////////////////////////////////////////////////
84
-
85
-	/**
86
-	 * The namespace of Form elements
87
-	 */
88
-	const FORMSPACE = 'Former\Form\\';
89
-
90
-	/**
91
-	 * The namespace of fields
92
-	 */
93
-	const FIELDSPACE = 'Former\Form\Fields\\';
94
-
95
-	/**
96
-	 * Build a new Former instance
97
-	 *
98
-	 * @param Container        $app
99
-	 * @param MethodDispatcher $dispatcher
100
-	 */
101
-	public function __construct(Container $app, MethodDispatcher $dispatcher)
102
-	{
103
-		$this->app      = $app;
104
-		$this->dispatch = $dispatcher;
105
-	}
106
-
107
-	////////////////////////////////////////////////////////////////////
108
-	//////////////////////////// INTERFACE /////////////////////////////
109
-	////////////////////////////////////////////////////////////////////
110
-
111
-	/**
112
-	 * Acts as a router that redirects methods to all of Former classes
113
-	 *
114
-	 * @param  string $method     The method called
115
-	 * @param  array  $parameters An array of parameters
116
-	 *
117
-	 * @return mixed
118
-	 */
119
-	public function __call($method, $parameters)
120
-	{
121
-		// Dispatch to Form\Elements
122
-		// Explicitly check false since closeGroup() may return an empty string
123
-		if (($element = $this->dispatch->toElements($method, $parameters)) !== false) {
124
-			return $element;
125
-		}
126
-
127
-		// Dispatch to Form\Form
128
-		if ($form = $this->dispatch->toForm($method, $parameters)) {
129
-			$this->app->instance('former.form', $form);
130
-
131
-			return $this->app['former.form'];
132
-		}
133
-
134
-		// Dispatch to Form\Group
135
-		if ($group = $this->dispatch->toGroup($method, $parameters)) {
136
-			return $group;
137
-		}
138
-
139
-		// Dispatch to Form\Actions
140
-		if ($actions = $this->dispatch->toActions($method, $parameters)) {
141
-			return $actions;
142
-		}
143
-
144
-		// Dispatch to macros
145
-		if ($macro = $this->dispatch->toMacros($method, $parameters)) {
146
-			return $macro;
147
-		}
148
-
149
-		// Checking for any supplementary classes
150
-		$modifiers = explode('_', $method);
151
-		$method  = array_pop($modifiers);
152
-
153
-		// Dispatch to the different Form\Fields
154
-		$field     = $this->dispatch->toFields($method, $parameters);
155
-		$field->setModifiers($modifiers);
156
-		$field->addClass('');
157
-
158
-		// Else bind field
159
-		$this->app->instance('former.field', $field);
160
-
161
-		return $this->app['former.field'];
162
-	}
163
-
164
-	////////////////////////////////////////////////////////////////////
165
-	//////////////////////////////// MACROS ////////////////////////////
166
-	////////////////////////////////////////////////////////////////////
167
-
168
-	/**
169
-	 * Register a macro with Former
170
-	 *
171
-	 * @param  string   $name  The name of the macro
172
-	 * @param  Callable $macro The macro itself
173
-	 *
174
-	 * @return mixed
175
-	 */
176
-	public function macro($name, $macro)
177
-	{
178
-		$this->macros[$name] = $macro;
179
-	}
180
-
181
-	/**
182
-	 * Check if a macro exists
183
-	 *
184
-	 * @param  string $name
185
-	 *
186
-	 * @return boolean
187
-	 */
188
-	public function hasMacro($name)
189
-	{
190
-		return isset($this->macros[$name]);
191
-	}
192
-
193
-	/**
194
-	 * Get a registered macro
195
-	 *
196
-	 * @param  string $name
197
-	 *
198
-	 * @return Closure
199
-	 */
200
-	public function getMacro($name)
201
-	{
202
-		return $this->macros[$name];
203
-	}
204
-
205
-	////////////////////////////////////////////////////////////////////
206
-	///////////////////////////// POPULATOR ////////////////////////////
207
-	////////////////////////////////////////////////////////////////////
208
-
209
-	/**
210
-	 * Add values to populate the array
211
-	 *
212
-	 * @param mixed $values Can be an Eloquent object or an array
213
-	 */
214
-	public function populate($values)
215
-	{
216
-		$this->app['former.populator']->replace($values);
217
-	}
218
-
219
-	/**
220
-	 * Set the value of a particular field
221
-	 *
222
-	 * @param string $field The field's name
223
-	 * @param mixed  $value Its new value
224
-	 */
225
-	public function populateField($field, $value)
226
-	{
227
-		$this->app['former.populator']->put($field, $value);
228
-	}
229
-
230
-	/**
231
-	 * Get the value of a field
232
-	 *
233
-	 * @param string $field The field's name
234
-	 * @param null   $fallback
235
-	 *
236
-	 * @return mixed
237
-	 */
238
-	public function getValue($field, $fallback = null)
239
-	{
240
-		return $this->app['former.populator']->get($field, $fallback);
241
-	}
242
-
243
-	/**
244
-	 * Fetch a field value from both the new and old POST array
245
-	 *
246
-	 * @param  string $name     A field name
247
-	 * @param  string $fallback A fallback if nothing was found
248
-	 *
249
-	 * @return string           The results
250
-	 */
251
-	public function getPost($name, $fallback = null)
252
-	{
253
-		$name     = str_replace(array('[', ']'), array('.', ''), $name);
254
-		$name     = trim($name, '.');
255
-		$oldValue = $this->app['request']->old($name, $fallback);
256
-
257
-		return $this->app['request']->input($name, $oldValue, true);
258
-	}
259
-
260
-	////////////////////////////////////////////////////////////////////
261
-	////////////////////////////// TOOLKIT /////////////////////////////
262
-	////////////////////////////////////////////////////////////////////
263
-
264
-	/**
265
-	 * Set the errors to use for validations
266
-	 *
267
-	 * @param Message $validator The result from a validation
268
-	 *
269
-	 * @return  void
270
-	 */
271
-	public function withErrors($validator = null)
272
-	{
273
-		// Try to get the errors form the session
274
-		if ($this->app['session']->has('errors')) {
275
-			$this->errors = $this->app['session']->get('errors');
276
-		}
277
-
278
-		// If we're given a raw Validator, go fetch the errors in it
279
-		if ($validator instanceof Validator) {
280
-			$this->errors = $validator->getMessageBag();
281
-		} else {
282
-			if ($validator instanceof MessageBag) {
283
-				$this->errors = $validator;
284
-			}
285
-		}
286
-
287
-		return $this->errors;
288
-	}
289
-
290
-	/**
291
-	 * Add live validation rules
292
-	 *
293
-	 * @param  array *$rules An array of Laravel rules
294
-	 *
295
-	 * @return  void
296
-	 */
297
-	public function withRules()
298
-	{
299
-		$rules = call_user_func_array('array_merge', func_get_args());
300
-
301
-		// Parse the rules according to Laravel conventions
302
-		foreach ($rules as $name => $fieldRules) {
303
-			$expFieldRules = $fieldRules;
304
-			if (!is_array($expFieldRules)) {
305
-				$expFieldRules = explode('|', $expFieldRules);
306
-				$expFieldRules = array_map('trim', $expFieldRules);
307
-			}
308
-
309
-			foreach ($expFieldRules as $rule) {
310
-
311
-				$parameters = null;
312
-
313
-				if (($colon = strpos($rule, ':')) !== false) {
314
-					$rulename = substr($rule, 0, $colon);
315
-
316
-					/**
317
-					 * Regular expressions may contain commas and should not be divided by str_getcsv.
318
-					 * For regular expressions we are just using the complete expression as a parameter.
319
-					 */
320
-					if ($rulename !== 'regex') {
321
-						$parameters = str_getcsv(substr($rule, $colon + 1));
322
-					} else {
323
-						$parameters = [substr($rule, $colon + 1)];
324
-					}
325
-				}
326
-
327
-				// Exclude unsupported rules
328
-				$rule = is_numeric($colon) ? substr($rule, 0, $colon) : $rule;
329
-
330
-				// Store processed rule in Former's array
331
-				if (!isset($parameters)) {
332
-					$parameters = array();
333
-				}
334
-
335
-				$this->rules[$name][$rule] = $parameters;
336
-			}
337
-		}
338
-	}
339
-
340
-	/**
341
-	 * Switch the framework used by Former
342
-	 *
343
-	 * @param string $framework The name of the framework to use
344
-	 */
345
-	public function framework($framework = null)
346
-	{
347
-		if (!$framework) {
348
-			return $this->app['former.framework']->current();
349
-		}
350
-
351
-		$this->setOption('framework', $framework);
352
-
353
-		$framework = $this->getFrameworkInstance($framework);
354
-		$this->app->bind('former.framework', function ($app) use ($framework) {
355
-			return $framework;
356
-		});
357
-	}
358
-
359
-	/**
360
-	 * Get a new framework instance
361
-	 *
362
-	 * @param string $framework
363
-	 *
364
-	 * @throws Exceptions\InvalidFrameworkException
365
-	 * @return \Former\Interfaces\FrameworkInterface
366
-	 */
367
-	public function getFrameworkInstance($framework)
368
-	{
369
-		$formerClass = __NAMESPACE__.'\Framework\\'.$framework;
370
-
371
-		//get interfaces of the given framework
372
-		$interfaces = class_exists($framework) ? class_implements($framework) : array();
373
-
374
-		if(class_exists($formerClass)) {
375
-			$returnClass = $formerClass;
376
-		} elseif(class_exists($framework) && isset($interfaces['Former\Interfaces\FrameworkInterface'])) {
377
-			// We have some outside class, lets return it.
378
-			$returnClass = $framework;
379
-		} else {
380
-			throw (new InvalidFrameworkException())->setFramework($framework);
381
-		}
382
-
383
-		return new $returnClass($this->app);
384
-	}
385
-
386
-	/**
387
-	 * Get an option from the config
388
-	 *
389
-	 * @param string $option  The option
390
-	 * @param mixed  $default Optional fallback
391
-	 *
392
-	 * @return mixed
393
-	 */
394
-	public function getOption($option, $default = null)
395
-	{
396
-		return $this->app['config']->get('former.'.$option, $default);
397
-	}
398
-
399
-	/**
400
-	 * Set an option on the config
401
-	 *
402
-	 * @param string $option
403
-	 * @param string $value
404
-	 */
405
-	public function setOption($option, $value)
406
-	{
407
-		return $this->app['config']->set('former.'.$option, $value);
408
-	}
409
-
410
-	////////////////////////////////////////////////////////////////////
411
-	////////////////////////////// BUILDERS ////////////////////////////
412
-	////////////////////////////////////////////////////////////////////
413
-
414
-	/**
415
-	 * Closes a form
416
-	 *
417
-	 * @return string A form closing tag
418
-	 */
419
-	public function close()
420
-	{
421
-		if ($this->app->bound('former.form')) {
422
-			$closing = $this->app['former.form']->close();
423
-		}
424
-
425
-		// Destroy instances
426
-		$instances = array('former.form', 'former.form.framework');
427
-		foreach ($instances as $instance) {
428
-			$this->app[$instance] = null;
429
-			unset($this->app[$instance]);
430
-		}
431
-
432
-		// Reset populator
433
-		$this->app['former.populator']->reset();
434
-
435
-		// Reset all values
436
-		$this->errors = null;
437
-		$this->rules  = array();
438
-
439
-		return isset($closing) ? $closing : null;
440
-	}
441
-
442
-	////////////////////////////////////////////////////////////////////
443
-	////////////////////////////// HELPERS /////////////////////////////
444
-	////////////////////////////////////////////////////////////////////
445
-
446
-	/**
447
-	 * Get the errors for the current field
448
-	 *
449
-	 * @param  string $name A field name
450
-	 *
451
-	 * @return string       An error message
452
-	 */
453
-	public function getErrors($name = null)
454
-	{
455
-		// Get name and translate array notation
456
-		if (!$name and $this->app['former.field']) {
457
-			$name = $this->app['former.field']->getName();
458
-
459
-			// Always return empty string for anonymous fields (i.e. fields with no name/id)
460
-			if (!$name) {
461
-				return '';
462
-			}
463
-		}
464
-
465
-		if ($this->errors and $name) {
466
-			$name = str_replace(array('[', ']'), array('.', ''), $name);
467
-			$name = trim($name, '.');
468
-
469
-			return $this->errors->first($name);
470
-		}
471
-
472
-		return $this->errors;
473
-	}
474
-
475
-	/**
476
-	 * Get a rule from the Rules array
477
-	 *
478
-	 * @param  string $name The field to fetch
479
-	 *
480
-	 * @return array        An array of rules
481
-	 */
482
-	public function getRules($name)
483
-	{
484
-		// Check the rules for the name as given
485
-		$ruleset = Arr::get($this->rules, $name);
486
-
487
-		// If no rules found, convert to dot notation and try again
488
-		if (is_null($ruleset)) {
489
-			$name = str_replace(array('[', ']'), array('.', ''), $name);
490
-			$name = trim($name, '.');
491
-			$ruleset = Arr::get($this->rules, $name);
492
-		}
493
-
494
-		return $ruleset;
495
-	}
17
+    // Instances
18
+    ////////////////////////////////////////////////////////////////////
19
+
20
+
21
+    /**
22
+     * The current environment
23
+     *
24
+     * @var \Illuminate\Container\Container
25
+     */
26
+    protected $app;
27
+
28
+    /**
29
+     * The Method Dispatcher
30
+     *
31
+     * @var MethodDispatcher
32
+     */
33
+    protected $dispatch;
34
+
35
+    // Informations
36
+    ////////////////////////////////////////////////////////////////////
37
+
38
+    /**
39
+     * The form's errors
40
+     *
41
+     * @var Message
42
+     */
43
+    protected $errors;
44
+
45
+    /**
46
+     * An array of rules to use
47
+     *
48
+     * @var array
49
+     */
50
+    protected $rules = array();
51
+
52
+    /**
53
+     * An array of field macros
54
+     *
55
+     * @var array
56
+     */
57
+    protected $macros = array();
58
+
59
+    /**
60
+     * The labels created so far
61
+     *
62
+     * @var array
63
+     */
64
+    public $labels = array();
65
+
66
+    /**
67
+     * The IDs created so far
68
+     *
69
+     * @var array
70
+     */
71
+    public $ids = array();
72
+
73
+    /**
74
+     * A lookup table where the key is the input name,
75
+     * and the value is number of times seen. This is
76
+     * used to calculate unique ids.
77
+     *
78
+     * @var array
79
+     */
80
+    public $names = array();
81
+
82
+    // Namespaces
83
+    ////////////////////////////////////////////////////////////////////
84
+
85
+    /**
86
+     * The namespace of Form elements
87
+     */
88
+    const FORMSPACE = 'Former\Form\\';
89
+
90
+    /**
91
+     * The namespace of fields
92
+     */
93
+    const FIELDSPACE = 'Former\Form\Fields\\';
94
+
95
+    /**
96
+     * Build a new Former instance
97
+     *
98
+     * @param Container        $app
99
+     * @param MethodDispatcher $dispatcher
100
+     */
101
+    public function __construct(Container $app, MethodDispatcher $dispatcher)
102
+    {
103
+        $this->app      = $app;
104
+        $this->dispatch = $dispatcher;
105
+    }
106
+
107
+    ////////////////////////////////////////////////////////////////////
108
+    //////////////////////////// INTERFACE /////////////////////////////
109
+    ////////////////////////////////////////////////////////////////////
110
+
111
+    /**
112
+     * Acts as a router that redirects methods to all of Former classes
113
+     *
114
+     * @param  string $method     The method called
115
+     * @param  array  $parameters An array of parameters
116
+     *
117
+     * @return mixed
118
+     */
119
+    public function __call($method, $parameters)
120
+    {
121
+        // Dispatch to Form\Elements
122
+        // Explicitly check false since closeGroup() may return an empty string
123
+        if (($element = $this->dispatch->toElements($method, $parameters)) !== false) {
124
+            return $element;
125
+        }
126
+
127
+        // Dispatch to Form\Form
128
+        if ($form = $this->dispatch->toForm($method, $parameters)) {
129
+            $this->app->instance('former.form', $form);
130
+
131
+            return $this->app['former.form'];
132
+        }
133
+
134
+        // Dispatch to Form\Group
135
+        if ($group = $this->dispatch->toGroup($method, $parameters)) {
136
+            return $group;
137
+        }
138
+
139
+        // Dispatch to Form\Actions
140
+        if ($actions = $this->dispatch->toActions($method, $parameters)) {
141
+            return $actions;
142
+        }
143
+
144
+        // Dispatch to macros
145
+        if ($macro = $this->dispatch->toMacros($method, $parameters)) {
146
+            return $macro;
147
+        }
148
+
149
+        // Checking for any supplementary classes
150
+        $modifiers = explode('_', $method);
151
+        $method  = array_pop($modifiers);
152
+
153
+        // Dispatch to the different Form\Fields
154
+        $field     = $this->dispatch->toFields($method, $parameters);
155
+        $field->setModifiers($modifiers);
156
+        $field->addClass('');
157
+
158
+        // Else bind field
159
+        $this->app->instance('former.field', $field);
160
+
161
+        return $this->app['former.field'];
162
+    }
163
+
164
+    ////////////////////////////////////////////////////////////////////
165
+    //////////////////////////////// MACROS ////////////////////////////
166
+    ////////////////////////////////////////////////////////////////////
167
+
168
+    /**
169
+     * Register a macro with Former
170
+     *
171
+     * @param  string   $name  The name of the macro
172
+     * @param  Callable $macro The macro itself
173
+     *
174
+     * @return mixed
175
+     */
176
+    public function macro($name, $macro)
177
+    {
178
+        $this->macros[$name] = $macro;
179
+    }
180
+
181
+    /**
182
+     * Check if a macro exists
183
+     *
184
+     * @param  string $name
185
+     *
186
+     * @return boolean
187
+     */
188
+    public function hasMacro($name)
189
+    {
190
+        return isset($this->macros[$name]);
191
+    }
192
+
193
+    /**
194
+     * Get a registered macro
195
+     *
196
+     * @param  string $name
197
+     *
198
+     * @return Closure
199
+     */
200
+    public function getMacro($name)
201
+    {
202
+        return $this->macros[$name];
203
+    }
204
+
205
+    ////////////////////////////////////////////////////////////////////
206
+    ///////////////////////////// POPULATOR ////////////////////////////
207
+    ////////////////////////////////////////////////////////////////////
208
+
209
+    /**
210
+     * Add values to populate the array
211
+     *
212
+     * @param mixed $values Can be an Eloquent object or an array
213
+     */
214
+    public function populate($values)
215
+    {
216
+        $this->app['former.populator']->replace($values);
217
+    }
218
+
219
+    /**
220
+     * Set the value of a particular field
221
+     *
222
+     * @param string $field The field's name
223
+     * @param mixed  $value Its new value
224
+     */
225
+    public function populateField($field, $value)
226
+    {
227
+        $this->app['former.populator']->put($field, $value);
228
+    }
229
+
230
+    /**
231
+     * Get the value of a field
232
+     *
233
+     * @param string $field The field's name
234
+     * @param null   $fallback
235
+     *
236
+     * @return mixed
237
+     */
238
+    public function getValue($field, $fallback = null)
239
+    {
240
+        return $this->app['former.populator']->get($field, $fallback);
241
+    }
242
+
243
+    /**
244
+     * Fetch a field value from both the new and old POST array
245
+     *
246
+     * @param  string $name     A field name
247
+     * @param  string $fallback A fallback if nothing was found
248
+     *
249
+     * @return string           The results
250
+     */
251
+    public function getPost($name, $fallback = null)
252
+    {
253
+        $name     = str_replace(array('[', ']'), array('.', ''), $name);
254
+        $name     = trim($name, '.');
255
+        $oldValue = $this->app['request']->old($name, $fallback);
256
+
257
+        return $this->app['request']->input($name, $oldValue, true);
258
+    }
259
+
260
+    ////////////////////////////////////////////////////////////////////
261
+    ////////////////////////////// TOOLKIT /////////////////////////////
262
+    ////////////////////////////////////////////////////////////////////
263
+
264
+    /**
265
+     * Set the errors to use for validations
266
+     *
267
+     * @param Message $validator The result from a validation
268
+     *
269
+     * @return  void
270
+     */
271
+    public function withErrors($validator = null)
272
+    {
273
+        // Try to get the errors form the session
274
+        if ($this->app['session']->has('errors')) {
275
+            $this->errors = $this->app['session']->get('errors');
276
+        }
277
+
278
+        // If we're given a raw Validator, go fetch the errors in it
279
+        if ($validator instanceof Validator) {
280
+            $this->errors = $validator->getMessageBag();
281
+        } else {
282
+            if ($validator instanceof MessageBag) {
283
+                $this->errors = $validator;
284
+            }
285
+        }
286
+
287
+        return $this->errors;
288
+    }
289
+
290
+    /**
291
+     * Add live validation rules
292
+     *
293
+     * @param  array *$rules An array of Laravel rules
294
+     *
295
+     * @return  void
296
+     */
297
+    public function withRules()
298
+    {
299
+        $rules = call_user_func_array('array_merge', func_get_args());
300
+
301
+        // Parse the rules according to Laravel conventions
302
+        foreach ($rules as $name => $fieldRules) {
303
+            $expFieldRules = $fieldRules;
304
+            if (!is_array($expFieldRules)) {
305
+                $expFieldRules = explode('|', $expFieldRules);
306
+                $expFieldRules = array_map('trim', $expFieldRules);
307
+            }
308
+
309
+            foreach ($expFieldRules as $rule) {
310
+
311
+                $parameters = null;
312
+
313
+                if (($colon = strpos($rule, ':')) !== false) {
314
+                    $rulename = substr($rule, 0, $colon);
315
+
316
+                    /**
317
+                     * Regular expressions may contain commas and should not be divided by str_getcsv.
318
+                     * For regular expressions we are just using the complete expression as a parameter.
319
+                     */
320
+                    if ($rulename !== 'regex') {
321
+                        $parameters = str_getcsv(substr($rule, $colon + 1));
322
+                    } else {
323
+                        $parameters = [substr($rule, $colon + 1)];
324
+                    }
325
+                }
326
+
327
+                // Exclude unsupported rules
328
+                $rule = is_numeric($colon) ? substr($rule, 0, $colon) : $rule;
329
+
330
+                // Store processed rule in Former's array
331
+                if (!isset($parameters)) {
332
+                    $parameters = array();
333
+                }
334
+
335
+                $this->rules[$name][$rule] = $parameters;
336
+            }
337
+        }
338
+    }
339
+
340
+    /**
341
+     * Switch the framework used by Former
342
+     *
343
+     * @param string $framework The name of the framework to use
344
+     */
345
+    public function framework($framework = null)
346
+    {
347
+        if (!$framework) {
348
+            return $this->app['former.framework']->current();
349
+        }
350
+
351
+        $this->setOption('framework', $framework);
352
+
353
+        $framework = $this->getFrameworkInstance($framework);
354
+        $this->app->bind('former.framework', function ($app) use ($framework) {
355
+            return $framework;
356
+        });
357
+    }
358
+
359
+    /**
360
+     * Get a new framework instance
361
+     *
362
+     * @param string $framework
363
+     *
364
+     * @throws Exceptions\InvalidFrameworkException
365
+     * @return \Former\Interfaces\FrameworkInterface
366
+     */
367
+    public function getFrameworkInstance($framework)
368
+    {
369
+        $formerClass = __NAMESPACE__.'\Framework\\'.$framework;
370
+
371
+        //get interfaces of the given framework
372
+        $interfaces = class_exists($framework) ? class_implements($framework) : array();
373
+
374
+        if(class_exists($formerClass)) {
375
+            $returnClass = $formerClass;
376
+        } elseif(class_exists($framework) && isset($interfaces['Former\Interfaces\FrameworkInterface'])) {
377
+            // We have some outside class, lets return it.
378
+            $returnClass = $framework;
379
+        } else {
380
+            throw (new InvalidFrameworkException())->setFramework($framework);
381
+        }
382
+
383
+        return new $returnClass($this->app);
384
+    }
385
+
386
+    /**
387
+     * Get an option from the config
388
+     *
389
+     * @param string $option  The option
390
+     * @param mixed  $default Optional fallback
391
+     *
392
+     * @return mixed
393
+     */
394
+    public function getOption($option, $default = null)
395
+    {
396
+        return $this->app['config']->get('former.'.$option, $default);
397
+    }
398
+
399
+    /**
400
+     * Set an option on the config
401
+     *
402
+     * @param string $option
403
+     * @param string $value
404
+     */
405
+    public function setOption($option, $value)
406
+    {
407
+        return $this->app['config']->set('former.'.$option, $value);
408
+    }
409
+
410
+    ////////////////////////////////////////////////////////////////////
411
+    ////////////////////////////// BUILDERS ////////////////////////////
412
+    ////////////////////////////////////////////////////////////////////
413
+
414
+    /**
415
+     * Closes a form
416
+     *
417
+     * @return string A form closing tag
418
+     */
419
+    public function close()
420
+    {
421
+        if ($this->app->bound('former.form')) {
422
+            $closing = $this->app['former.form']->close();
423
+        }
424
+
425
+        // Destroy instances
426
+        $instances = array('former.form', 'former.form.framework');
427
+        foreach ($instances as $instance) {
428
+            $this->app[$instance] = null;
429
+            unset($this->app[$instance]);
430
+        }
431
+
432
+        // Reset populator
433
+        $this->app['former.populator']->reset();
434
+
435
+        // Reset all values
436
+        $this->errors = null;
437
+        $this->rules  = array();
438
+
439
+        return isset($closing) ? $closing : null;
440
+    }
441
+
442
+    ////////////////////////////////////////////////////////////////////
443
+    ////////////////////////////// HELPERS /////////////////////////////
444
+    ////////////////////////////////////////////////////////////////////
445
+
446
+    /**
447
+     * Get the errors for the current field
448
+     *
449
+     * @param  string $name A field name
450
+     *
451
+     * @return string       An error message
452
+     */
453
+    public function getErrors($name = null)
454
+    {
455
+        // Get name and translate array notation
456
+        if (!$name and $this->app['former.field']) {
457
+            $name = $this->app['former.field']->getName();
458
+
459
+            // Always return empty string for anonymous fields (i.e. fields with no name/id)
460
+            if (!$name) {
461
+                return '';
462
+            }
463
+        }
464
+
465
+        if ($this->errors and $name) {
466
+            $name = str_replace(array('[', ']'), array('.', ''), $name);
467
+            $name = trim($name, '.');
468
+
469
+            return $this->errors->first($name);
470
+        }
471
+
472
+        return $this->errors;
473
+    }
474
+
475
+    /**
476
+     * Get a rule from the Rules array
477
+     *
478
+     * @param  string $name The field to fetch
479
+     *
480
+     * @return array        An array of rules
481
+     */
482
+    public function getRules($name)
483
+    {
484
+        // Check the rules for the name as given
485
+        $ruleset = Arr::get($this->rules, $name);
486
+
487
+        // If no rules found, convert to dot notation and try again
488
+        if (is_null($ruleset)) {
489
+            $name = str_replace(array('[', ']'), array('.', ''), $name);
490
+            $name = trim($name, '.');
491
+            $ruleset = Arr::get($this->rules, $name);
492
+        }
493
+
494
+        return $ruleset;
495
+    }
496 496
 }
Please login to merge, or discard this patch.
src/Former/Framework/TwitterBootstrap4.php 3 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -139,7 +139,7 @@
 block discarded – undo
139 139
 		$classes = array_intersect($classes, $this->fields);
140 140
 
141 141
 		// Prepend field type
142
-		$classes = array_map(function ($class) {
142
+		$classes = array_map(function($class) {
143 143
 			return Str::startsWith($class, 'col') ? $class : 'input-'.$class;
144 144
 		}, $classes);
145 145
 
Please login to merge, or discard this patch.
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -345,7 +345,7 @@
 block discarded – undo
345 345
 	 * @param string $text
346 346
 	 * @param array  $attributes
347 347
 	 *
348
-	 * @return string
348
+	 * @return Element
349 349
 	 */
350 350
 	public function createValidationError($text, $attributes = array())
351 351
 	{
Please login to merge, or discard this patch.
Indentation   +457 added lines, -457 removed lines patch added patch discarded remove patch
@@ -13,461 +13,461 @@
 block discarded – undo
13 13
  */
14 14
 class TwitterBootstrap4 extends Framework implements FrameworkInterface
15 15
 {
16
-	/**
17
-	 * Form types that trigger special styling for this Framework
18
-	 *
19
-	 * @var array
20
-	 */
21
-	protected $availableTypes = array('horizontal', 'vertical', 'inline');
22
-
23
-	/**
24
-	 * The button types available
25
-	 *
26
-	 * @var array
27
-	 */
28
-	private $buttons = array(
29
-		'lg',
30
-		'sm',
31
-		'xs',
32
-		'block',
33
-		'link',
34
-		'primary',
35
-		'secondary',
36
-		'warning',
37
-		'danger',
38
-		'success',
39
-		'info',
40
-		'light',
41
-		'dark',
42
-	);
43
-
44
-	/**
45
-	 * The field sizes available
46
-	 *
47
-	 * @var array
48
-	 */
49
-	private $fields = array(
50
-		'lg',
51
-		'sm',
52
-		// 'col-xs-1', 'col-xs-2', 'col-xs-3', 'col-xs-4', 'col-xs-5', 'col-xs-6',
53
-		// 'col-xs-7', 'col-xs-8', 'col-xs-9', 'col-xs-10', 'col-xs-11', 'col-xs-12',
54
-		// 'col-sm-1', 'col-sm-2', 'col-sm-3', 'col-sm-4', 'col-sm-5', 'col-sm-6',
55
-		// 'col-sm-7', 'col-sm-8', 'col-sm-9', 'col-sm-10', 'col-sm-11', 'col-sm-12',
56
-		// 'col-md-1', 'col-md-2', 'col-md-3', 'col-md-4', 'col-md-5', 'col-md-6',
57
-		// 'col-md-7', 'col-md-8', 'col-md-9', 'col-md-10', 'col-md-11', 'col-md-12',
58
-		// 'col-lg-1', 'col-lg-2', 'col-lg-3', 'col-lg-4', 'col-lg-5', 'col-lg-6',
59
-		// 'col-lg-7', 'col-lg-8', 'col-lg-9', 'col-lg-10', 'col-lg-11', 'col-lg-12',
60
-	);
61
-
62
-	/**
63
-	 * The field states available
64
-	 *
65
-	 * @var array
66
-	 */
67
-	protected $states = array(
68
-		'is-invalid',
69
-	);
70
-
71
-	/**
72
-	 * The default HTML tag used for icons
73
-	 *
74
-	 * @var string
75
-	 */
76
-	protected $iconTag = 'i';
77
-
78
-	/**
79
-	 * The default set for icon fonts
80
-	 * By default Bootstrap 4 offers no fonts, but we'll add Font Awesome
81
-	 *
82
-	 * @var string
83
-	 */
84
-	protected $iconSet = 'fa';
85
-
86
-	/**
87
-	 * The default prefix icon names
88
-	 * Using Font Awesome 5, this can be 'fa' or 'fas' for solid, 'far' for regular
89
-	 *
90
-	 * @var string
91
-	 */
92
-	protected $iconPrefix = 'fa';
93
-
94
-	/**
95
-	 * Create a new TwitterBootstrap instance
96
-	 *
97
-	 * @param \Illuminate\Container\Container $app
98
-	 */
99
-	public function __construct(Container $app)
100
-	{
101
-		$this->app = $app;
102
-		$this->setFrameworkDefaults();
103
-	}
104
-
105
-	////////////////////////////////////////////////////////////////////
106
-	/////////////////////////// FILTER ARRAYS //////////////////////////
107
-	////////////////////////////////////////////////////////////////////
108
-
109
-	/**
110
-	 * Filter buttons classes
111
-	 *
112
-	 * @param  array $classes An array of classes
113
-	 *
114
-	 * @return string[] A filtered array
115
-	 */
116
-	public function filterButtonClasses($classes)
117
-	{
118
-		// Filter classes
119
-		// $classes = array_intersect($classes, $this->buttons);
120
-
121
-		// Prepend button type
122
-		$classes   = $this->prependWith($classes, 'btn-');
123
-		$classes[] = 'btn';
124
-
125
-		return $classes;
126
-	}
127
-
128
-	/**
129
-	 * Filter field classes
130
-	 *
131
-	 * @param  array $classes An array of classes
132
-	 *
133
-	 * @return array A filtered array
134
-	 */
135
-	public function filterFieldClasses($classes)
136
-	{
137
-		// Filter classes
138
-		$classes = array_intersect($classes, $this->fields);
139
-
140
-		// Prepend field type
141
-		$classes = array_map(function ($class) {
142
-			return Str::startsWith($class, 'col') ? $class : 'input-'.$class;
143
-		}, $classes);
144
-
145
-		return $classes;
146
-	}
147
-
148
-	////////////////////////////////////////////////////////////////////
149
-	///////////////////// EXPOSE FRAMEWORK SPECIFICS ///////////////////
150
-	////////////////////////////////////////////////////////////////////
151
-
152
-	/**
153
-	 * Framework error state
154
-	 *
155
-	 * @return string
156
-	 */
157
-	public function errorState()
158
-	{
159
-		return 'is-invalid';
160
-	}
161
-
162
-	/**
163
-	 * Returns corresponding inline class of a field
164
-	 *
165
-	 * @param Field $field
166
-	 *
167
-	 * @return string
168
-	 */
169
-	public function getInlineLabelClass($field)
170
-	{
171
-		$inlineClass = parent::getInlineLabelClass($field);
172
-		if ($field->isOfType('checkbox', 'checkboxes', 'radio', 'radios')) {
173
-			$inlineClass = 'form-check-label';
174
-		}
175
-
176
-		return $inlineClass;
177
-	}
178
-
179
-	/**
180
-	 * Set the fields width from a label width
181
-	 *
182
-	 * @param array $labelWidths
183
-	 */
184
-	protected function setFieldWidths($labelWidths)
185
-	{
186
-		$labelWidthClass = $fieldWidthClass = $fieldOffsetClass = '';
187
-
188
-		$viewports = $this->getFrameworkOption('viewports');
189
-		foreach ($labelWidths as $viewport => $columns) {
190
-			if ($viewport) {
191
-				$labelWidthClass .= " col-$viewports[$viewport]-$columns";
192
-				$fieldWidthClass .= " col-$viewports[$viewport]-".(12 - $columns);
193
-				$fieldOffsetClass .= " col-$viewports[$viewport]-offset-$columns";
194
-			}
195
-		}
196
-
197
-		$this->labelWidth  = ltrim($labelWidthClass);
198
-		$this->fieldWidth  = ltrim($fieldWidthClass);
199
-		$this->fieldOffset = ltrim($fieldOffsetClass);
200
-	}
201
-
202
-	////////////////////////////////////////////////////////////////////
203
-	///////////////////////////// ADD CLASSES //////////////////////////
204
-	////////////////////////////////////////////////////////////////////
205
-
206
-	/**
207
-	 * Add classes to a field
208
-	 *
209
-	 * @param Field $field
210
-	 * @param array $classes The possible classes to add
211
-	 *
212
-	 * @return Field
213
-	 */
214
-	public function getFieldClasses(Field $field, $classes)
215
-	{
216
-		// Add inline class for checkables
217
-		if ($field->isCheckable()) {
218
-			// Adds correct checkbox input class when is a checkbox (or radio)
219
-			$field->addClass('form-check-input');
220
-			$classes[] = 'form-check';
221
-
222
-			if (in_array('inline', $classes)) {
223
-				$field->inline();
224
-			}
225
-		}
226
-
227
-		// Filter classes according to field type
228
-		if ($field->isButton()) {
229
-			$classes = $this->filterButtonClasses($classes);
230
-		} else {
231
-			$classes = $this->filterFieldClasses($classes);
232
-		}
233
-
234
-		// Add form-control class for text-type, textarea and select fields
235
-		// As text-type is open-ended we instead exclude those that shouldn't receive the class
236
-		if (!$field->isCheckable() and !$field->isButton() and !in_array($field->getType(), array(
237
-					'file',
238
-					'plaintext',
239
-				)) and !in_array('form-control', $classes)
240
-		) {
241
-			$classes[] = 'form-control';
242
-		}
243
-
244
-		if ($this->app['former']->getErrors($field->getName())) {
245
-			$classes[] = $this->errorState();
246
-		}
247
-
248
-		return $this->addClassesToField($field, $classes);
249
-	}
250
-
251
-	/**
252
-	 * Add group classes
253
-	 *
254
-	 * @return string A list of group classes
255
-	 */
256
-	public function getGroupClasses()
257
-	{
258
-		if ($this->app['former.form']->isOfType('horizontal')) {
259
-			return 'form-group row';
260
-		} else {
261
-			return 'form-group';
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * Add label classes
267
-	 *
268
-	 * @return string[] An array of attributes with the label class
269
-	 */
270
-	public function getLabelClasses()
271
-	{
272
-		if ($this->app['former.form']->isOfType('horizontal')) {
273
-			return array('control-label', $this->labelWidth);
274
-		} elseif ($this->app['former.form']->isOfType('inline')) {
275
-			return array('sr-only');
276
-		} else {
277
-			return array('control-label');
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * Add uneditable field classes
283
-	 *
284
-	 * @return string An array of attributes with the uneditable class
285
-	 */
286
-	public function getUneditableClasses()
287
-	{
288
-		return '';
289
-	}
290
-
291
-	/**
292
-	 * Add plain text field classes
293
-	 *
294
-	 * @return string An array of attributes with the plain text class
295
-	 */
296
-	public function getPlainTextClasses()
297
-	{
298
-		return 'form-control-static';
299
-	}
300
-
301
-	/**
302
-	 * Add form class
303
-	 *
304
-	 * @param  string $type The type of form to add
305
-	 *
306
-	 * @return string|null
307
-	 */
308
-	public function getFormClasses($type)
309
-	{
310
-		return $type ? 'form-'.$type : null;
311
-	}
312
-
313
-	/**
314
-	 * Add actions block class
315
-	 *
316
-	 * @return string|null
317
-	 */
318
-	public function getActionClasses()
319
-	{
320
-		if ($this->app['former.form']->isOfType('horizontal') || $this->app['former.form']->isOfType('inline')) {
321
-			return 'form-group row';
322
-		}
323
-
324
-		return null;
325
-	}
326
-
327
-	////////////////////////////////////////////////////////////////////
328
-	//////////////////////////// RENDER BLOCKS /////////////////////////
329
-	////////////////////////////////////////////////////////////////////
330
-
331
-	/**
332
-	 * Render an help text
333
-	 *
334
-	 * @param string $text
335
-	 * @param array  $attributes
336
-	 *
337
-	 * @return Element
338
-	 */
339
-	public function createHelp($text, $attributes = array())
340
-	{
341
-		return Element::create('small', $text, $attributes)->addClass('text-muted');
342
-	}
343
-
344
-	/**
345
-	 * Render an validation error text
346
-	 *
347
-	 * @param string $text
348
-	 * @param array  $attributes
349
-	 *
350
-	 * @return string
351
-	 */
352
-	public function createValidationError($text, $attributes = array())
353
-	{
354
-		return Element::create('div', $text, $attributes)->addClass('invalid-feedback');
355
-	}
356
-
357
-	/**
358
-	 * Render an help text
359
-	 *
360
-	 * @param string $text
361
-	 * @param array  $attributes
362
-	 *
363
-	 * @return Element
364
-	 */
365
-	public function createBlockHelp($text, $attributes = array())
366
-	{
367
-		return Element::create('small', $text, $attributes)->addClass('form-text text-muted');
368
-	}
369
-
370
-	/**
371
-	 * Render a disabled field
372
-	 *
373
-	 * @param Field $field
374
-	 *
375
-	 * @return Element
376
-	 */
377
-	public function createDisabledField(Field $field)
378
-	{
379
-		return Element::create('span', $field->getValue(), $field->getAttributes());
380
-	}
381
-
382
-	/**
383
-	 * Render a plain text field
384
-	 *
385
-	 * @param Field $field
386
-	 *
387
-	 * @return Element
388
-	 */
389
-	public function createPlainTextField(Field $field)
390
-	{
391
-		$label = $field->getLabel();
392
-		if ($label) {
393
-			$label->for('');
394
-		}
395
-
396
-		return Element::create('div', $field->getValue(), $field->getAttributes());
397
-	}
398
-
399
-	////////////////////////////////////////////////////////////////////
400
-	//////////////////////////// WRAP BLOCKS ///////////////////////////
401
-	////////////////////////////////////////////////////////////////////
402
-
403
-	/**
404
-	 * Wrap an item to be prepended or appended to the current field
405
-	 *
406
-	 * @return Element A wrapped item
407
-	 */
408
-	public function placeAround($item)
409
-	{
410
-		// Render object
411
-		if (is_object($item) and method_exists($item, '__toString')) {
412
-			$item = $item->__toString();
413
-		}
414
-
415
-		// Get class to use
416
-		$class = (strpos($item, '<button') !== false) ? 'btn' : 'addon';
417
-
418
-		return Element::create('span', $item)->addClass('input-group-'.$class);
419
-	}
420
-
421
-	/**
422
-	 * Wrap a field with prepended and appended items
423
-	 *
424
-	 * @param  Field $field
425
-	 * @param  array $prepend
426
-	 * @param  array $append
427
-	 *
428
-	 * @return string A field concatented with prepended and/or appended items
429
-	 */
430
-	public function prependAppend($field, $prepend, $append)
431
-	{
432
-		$return = '<div class="input-group">';
433
-		$return .= join(null, $prepend);
434
-		$return .= $field->render();
435
-		$return .= join(null, $append);
436
-		$return .= '</div>';
437
-
438
-		return $return;
439
-	}
440
-
441
-	/**
442
-	 * Wrap a field with potential additional tags
443
-	 *
444
-	 * @param  Field $field
445
-	 *
446
-	 * @return Element A wrapped field
447
-	 */
448
-	public function wrapField($field)
449
-	{
450
-		if ($this->app['former.form']->isOfType('horizontal')) {
451
-			return Element::create('div', $field)->addClass($this->fieldWidth);
452
-		}
453
-
454
-		return $field;
455
-	}
456
-
457
-	/**
458
-	 * Wrap actions block with potential additional tags
459
-	 *
460
-	 * @param  Actions $actions
461
-	 *
462
-	 * @return string A wrapped actions block
463
-	 */
464
-	public function wrapActions($actions)
465
-	{
466
-		// For horizontal forms, we wrap the actions in a div
467
-		if ($this->app['former.form']->isOfType('horizontal')) {
468
-			return Element::create('div', $actions)->addClass(array($this->fieldOffset, $this->fieldWidth));
469
-		}
470
-
471
-		return $actions;
472
-	}
16
+    /**
17
+     * Form types that trigger special styling for this Framework
18
+     *
19
+     * @var array
20
+     */
21
+    protected $availableTypes = array('horizontal', 'vertical', 'inline');
22
+
23
+    /**
24
+     * The button types available
25
+     *
26
+     * @var array
27
+     */
28
+    private $buttons = array(
29
+        'lg',
30
+        'sm',
31
+        'xs',
32
+        'block',
33
+        'link',
34
+        'primary',
35
+        'secondary',
36
+        'warning',
37
+        'danger',
38
+        'success',
39
+        'info',
40
+        'light',
41
+        'dark',
42
+    );
43
+
44
+    /**
45
+     * The field sizes available
46
+     *
47
+     * @var array
48
+     */
49
+    private $fields = array(
50
+        'lg',
51
+        'sm',
52
+        // 'col-xs-1', 'col-xs-2', 'col-xs-3', 'col-xs-4', 'col-xs-5', 'col-xs-6',
53
+        // 'col-xs-7', 'col-xs-8', 'col-xs-9', 'col-xs-10', 'col-xs-11', 'col-xs-12',
54
+        // 'col-sm-1', 'col-sm-2', 'col-sm-3', 'col-sm-4', 'col-sm-5', 'col-sm-6',
55
+        // 'col-sm-7', 'col-sm-8', 'col-sm-9', 'col-sm-10', 'col-sm-11', 'col-sm-12',
56
+        // 'col-md-1', 'col-md-2', 'col-md-3', 'col-md-4', 'col-md-5', 'col-md-6',
57
+        // 'col-md-7', 'col-md-8', 'col-md-9', 'col-md-10', 'col-md-11', 'col-md-12',
58
+        // 'col-lg-1', 'col-lg-2', 'col-lg-3', 'col-lg-4', 'col-lg-5', 'col-lg-6',
59
+        // 'col-lg-7', 'col-lg-8', 'col-lg-9', 'col-lg-10', 'col-lg-11', 'col-lg-12',
60
+    );
61
+
62
+    /**
63
+     * The field states available
64
+     *
65
+     * @var array
66
+     */
67
+    protected $states = array(
68
+        'is-invalid',
69
+    );
70
+
71
+    /**
72
+     * The default HTML tag used for icons
73
+     *
74
+     * @var string
75
+     */
76
+    protected $iconTag = 'i';
77
+
78
+    /**
79
+     * The default set for icon fonts
80
+     * By default Bootstrap 4 offers no fonts, but we'll add Font Awesome
81
+     *
82
+     * @var string
83
+     */
84
+    protected $iconSet = 'fa';
85
+
86
+    /**
87
+     * The default prefix icon names
88
+     * Using Font Awesome 5, this can be 'fa' or 'fas' for solid, 'far' for regular
89
+     *
90
+     * @var string
91
+     */
92
+    protected $iconPrefix = 'fa';
93
+
94
+    /**
95
+     * Create a new TwitterBootstrap instance
96
+     *
97
+     * @param \Illuminate\Container\Container $app
98
+     */
99
+    public function __construct(Container $app)
100
+    {
101
+        $this->app = $app;
102
+        $this->setFrameworkDefaults();
103
+    }
104
+
105
+    ////////////////////////////////////////////////////////////////////
106
+    /////////////////////////// FILTER ARRAYS //////////////////////////
107
+    ////////////////////////////////////////////////////////////////////
108
+
109
+    /**
110
+     * Filter buttons classes
111
+     *
112
+     * @param  array $classes An array of classes
113
+     *
114
+     * @return string[] A filtered array
115
+     */
116
+    public function filterButtonClasses($classes)
117
+    {
118
+        // Filter classes
119
+        // $classes = array_intersect($classes, $this->buttons);
120
+
121
+        // Prepend button type
122
+        $classes   = $this->prependWith($classes, 'btn-');
123
+        $classes[] = 'btn';
124
+
125
+        return $classes;
126
+    }
127
+
128
+    /**
129
+     * Filter field classes
130
+     *
131
+     * @param  array $classes An array of classes
132
+     *
133
+     * @return array A filtered array
134
+     */
135
+    public function filterFieldClasses($classes)
136
+    {
137
+        // Filter classes
138
+        $classes = array_intersect($classes, $this->fields);
139
+
140
+        // Prepend field type
141
+        $classes = array_map(function ($class) {
142
+            return Str::startsWith($class, 'col') ? $class : 'input-'.$class;
143
+        }, $classes);
144
+
145
+        return $classes;
146
+    }
147
+
148
+    ////////////////////////////////////////////////////////////////////
149
+    ///////////////////// EXPOSE FRAMEWORK SPECIFICS ///////////////////
150
+    ////////////////////////////////////////////////////////////////////
151
+
152
+    /**
153
+     * Framework error state
154
+     *
155
+     * @return string
156
+     */
157
+    public function errorState()
158
+    {
159
+        return 'is-invalid';
160
+    }
161
+
162
+    /**
163
+     * Returns corresponding inline class of a field
164
+     *
165
+     * @param Field $field
166
+     *
167
+     * @return string
168
+     */
169
+    public function getInlineLabelClass($field)
170
+    {
171
+        $inlineClass = parent::getInlineLabelClass($field);
172
+        if ($field->isOfType('checkbox', 'checkboxes', 'radio', 'radios')) {
173
+            $inlineClass = 'form-check-label';
174
+        }
175
+
176
+        return $inlineClass;
177
+    }
178
+
179
+    /**
180
+     * Set the fields width from a label width
181
+     *
182
+     * @param array $labelWidths
183
+     */
184
+    protected function setFieldWidths($labelWidths)
185
+    {
186
+        $labelWidthClass = $fieldWidthClass = $fieldOffsetClass = '';
187
+
188
+        $viewports = $this->getFrameworkOption('viewports');
189
+        foreach ($labelWidths as $viewport => $columns) {
190
+            if ($viewport) {
191
+                $labelWidthClass .= " col-$viewports[$viewport]-$columns";
192
+                $fieldWidthClass .= " col-$viewports[$viewport]-".(12 - $columns);
193
+                $fieldOffsetClass .= " col-$viewports[$viewport]-offset-$columns";
194
+            }
195
+        }
196
+
197
+        $this->labelWidth  = ltrim($labelWidthClass);
198
+        $this->fieldWidth  = ltrim($fieldWidthClass);
199
+        $this->fieldOffset = ltrim($fieldOffsetClass);
200
+    }
201
+
202
+    ////////////////////////////////////////////////////////////////////
203
+    ///////////////////////////// ADD CLASSES //////////////////////////
204
+    ////////////////////////////////////////////////////////////////////
205
+
206
+    /**
207
+     * Add classes to a field
208
+     *
209
+     * @param Field $field
210
+     * @param array $classes The possible classes to add
211
+     *
212
+     * @return Field
213
+     */
214
+    public function getFieldClasses(Field $field, $classes)
215
+    {
216
+        // Add inline class for checkables
217
+        if ($field->isCheckable()) {
218
+            // Adds correct checkbox input class when is a checkbox (or radio)
219
+            $field->addClass('form-check-input');
220
+            $classes[] = 'form-check';
221
+
222
+            if (in_array('inline', $classes)) {
223
+                $field->inline();
224
+            }
225
+        }
226
+
227
+        // Filter classes according to field type
228
+        if ($field->isButton()) {
229
+            $classes = $this->filterButtonClasses($classes);
230
+        } else {
231
+            $classes = $this->filterFieldClasses($classes);
232
+        }
233
+
234
+        // Add form-control class for text-type, textarea and select fields
235
+        // As text-type is open-ended we instead exclude those that shouldn't receive the class
236
+        if (!$field->isCheckable() and !$field->isButton() and !in_array($field->getType(), array(
237
+                    'file',
238
+                    'plaintext',
239
+                )) and !in_array('form-control', $classes)
240
+        ) {
241
+            $classes[] = 'form-control';
242
+        }
243
+
244
+        if ($this->app['former']->getErrors($field->getName())) {
245
+            $classes[] = $this->errorState();
246
+        }
247
+
248
+        return $this->addClassesToField($field, $classes);
249
+    }
250
+
251
+    /**
252
+     * Add group classes
253
+     *
254
+     * @return string A list of group classes
255
+     */
256
+    public function getGroupClasses()
257
+    {
258
+        if ($this->app['former.form']->isOfType('horizontal')) {
259
+            return 'form-group row';
260
+        } else {
261
+            return 'form-group';
262
+        }
263
+    }
264
+
265
+    /**
266
+     * Add label classes
267
+     *
268
+     * @return string[] An array of attributes with the label class
269
+     */
270
+    public function getLabelClasses()
271
+    {
272
+        if ($this->app['former.form']->isOfType('horizontal')) {
273
+            return array('control-label', $this->labelWidth);
274
+        } elseif ($this->app['former.form']->isOfType('inline')) {
275
+            return array('sr-only');
276
+        } else {
277
+            return array('control-label');
278
+        }
279
+    }
280
+
281
+    /**
282
+     * Add uneditable field classes
283
+     *
284
+     * @return string An array of attributes with the uneditable class
285
+     */
286
+    public function getUneditableClasses()
287
+    {
288
+        return '';
289
+    }
290
+
291
+    /**
292
+     * Add plain text field classes
293
+     *
294
+     * @return string An array of attributes with the plain text class
295
+     */
296
+    public function getPlainTextClasses()
297
+    {
298
+        return 'form-control-static';
299
+    }
300
+
301
+    /**
302
+     * Add form class
303
+     *
304
+     * @param  string $type The type of form to add
305
+     *
306
+     * @return string|null
307
+     */
308
+    public function getFormClasses($type)
309
+    {
310
+        return $type ? 'form-'.$type : null;
311
+    }
312
+
313
+    /**
314
+     * Add actions block class
315
+     *
316
+     * @return string|null
317
+     */
318
+    public function getActionClasses()
319
+    {
320
+        if ($this->app['former.form']->isOfType('horizontal') || $this->app['former.form']->isOfType('inline')) {
321
+            return 'form-group row';
322
+        }
323
+
324
+        return null;
325
+    }
326
+
327
+    ////////////////////////////////////////////////////////////////////
328
+    //////////////////////////// RENDER BLOCKS /////////////////////////
329
+    ////////////////////////////////////////////////////////////////////
330
+
331
+    /**
332
+     * Render an help text
333
+     *
334
+     * @param string $text
335
+     * @param array  $attributes
336
+     *
337
+     * @return Element
338
+     */
339
+    public function createHelp($text, $attributes = array())
340
+    {
341
+        return Element::create('small', $text, $attributes)->addClass('text-muted');
342
+    }
343
+
344
+    /**
345
+     * Render an validation error text
346
+     *
347
+     * @param string $text
348
+     * @param array  $attributes
349
+     *
350
+     * @return string
351
+     */
352
+    public function createValidationError($text, $attributes = array())
353
+    {
354
+        return Element::create('div', $text, $attributes)->addClass('invalid-feedback');
355
+    }
356
+
357
+    /**
358
+     * Render an help text
359
+     *
360
+     * @param string $text
361
+     * @param array  $attributes
362
+     *
363
+     * @return Element
364
+     */
365
+    public function createBlockHelp($text, $attributes = array())
366
+    {
367
+        return Element::create('small', $text, $attributes)->addClass('form-text text-muted');
368
+    }
369
+
370
+    /**
371
+     * Render a disabled field
372
+     *
373
+     * @param Field $field
374
+     *
375
+     * @return Element
376
+     */
377
+    public function createDisabledField(Field $field)
378
+    {
379
+        return Element::create('span', $field->getValue(), $field->getAttributes());
380
+    }
381
+
382
+    /**
383
+     * Render a plain text field
384
+     *
385
+     * @param Field $field
386
+     *
387
+     * @return Element
388
+     */
389
+    public function createPlainTextField(Field $field)
390
+    {
391
+        $label = $field->getLabel();
392
+        if ($label) {
393
+            $label->for('');
394
+        }
395
+
396
+        return Element::create('div', $field->getValue(), $field->getAttributes());
397
+    }
398
+
399
+    ////////////////////////////////////////////////////////////////////
400
+    //////////////////////////// WRAP BLOCKS ///////////////////////////
401
+    ////////////////////////////////////////////////////////////////////
402
+
403
+    /**
404
+     * Wrap an item to be prepended or appended to the current field
405
+     *
406
+     * @return Element A wrapped item
407
+     */
408
+    public function placeAround($item)
409
+    {
410
+        // Render object
411
+        if (is_object($item) and method_exists($item, '__toString')) {
412
+            $item = $item->__toString();
413
+        }
414
+
415
+        // Get class to use
416
+        $class = (strpos($item, '<button') !== false) ? 'btn' : 'addon';
417
+
418
+        return Element::create('span', $item)->addClass('input-group-'.$class);
419
+    }
420
+
421
+    /**
422
+     * Wrap a field with prepended and appended items
423
+     *
424
+     * @param  Field $field
425
+     * @param  array $prepend
426
+     * @param  array $append
427
+     *
428
+     * @return string A field concatented with prepended and/or appended items
429
+     */
430
+    public function prependAppend($field, $prepend, $append)
431
+    {
432
+        $return = '<div class="input-group">';
433
+        $return .= join(null, $prepend);
434
+        $return .= $field->render();
435
+        $return .= join(null, $append);
436
+        $return .= '</div>';
437
+
438
+        return $return;
439
+    }
440
+
441
+    /**
442
+     * Wrap a field with potential additional tags
443
+     *
444
+     * @param  Field $field
445
+     *
446
+     * @return Element A wrapped field
447
+     */
448
+    public function wrapField($field)
449
+    {
450
+        if ($this->app['former.form']->isOfType('horizontal')) {
451
+            return Element::create('div', $field)->addClass($this->fieldWidth);
452
+        }
453
+
454
+        return $field;
455
+    }
456
+
457
+    /**
458
+     * Wrap actions block with potential additional tags
459
+     *
460
+     * @param  Actions $actions
461
+     *
462
+     * @return string A wrapped actions block
463
+     */
464
+    public function wrapActions($actions)
465
+    {
466
+        // For horizontal forms, we wrap the actions in a div
467
+        if ($this->app['former.form']->isOfType('horizontal')) {
468
+            return Element::create('div', $actions)->addClass(array($this->fieldOffset, $this->fieldWidth));
469
+        }
470
+
471
+        return $actions;
472
+    }
473 473
 }
Please login to merge, or discard this patch.
src/Former/Traits/Checkable.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 
351 351
 		// In Bootsrap 3 or 4, don't append the the checkable type (radio/checkbox) as a class if
352 352
 		// rendering inline.
353
-		$class =  ($this->app['former']->framework() == 'TwitterBootstrap3' ||
353
+		$class = ($this->app['former']->framework() == 'TwitterBootstrap3' ||
354 354
 			$this->app['former']->framework() == 'TwitterBootstrap4') ? trim($isInline) : $this->checkable.$isInline;
355 355
 
356 356
 		// Merge custom attributes with global attributes
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
 			$element = (is_object($field)) ? $field->render() : $field;
382 382
 		} elseif ($this->app['former']->framework() == 'TwitterBootstrap4') {
383 383
 			// Revised for Bootstrap 4, move the 'input' outside of the 'label'
384
-			$element = $field . Element::create('label', $label)->for($attributes['id'])->class($class)->render();
384
+			$element = $field.Element::create('label', $label)->for($attributes['id'])->class($class)->render();
385 385
 
386 386
 			$wrapper_class = $this->inline ? 'form-check form-check-inline' : 'form-check';
387 387
 			
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 		$this->app['former']->labels[] = $name;
422 422
 
423 423
 		// Count number of fields with the same ID
424
-		$where  = array_filter($this->app['former']->labels, function ($label) use ($name) {
424
+		$where  = array_filter($this->app['former']->labels, function($label) use ($name) {
425 425
 			return $label == $name;
426 426
 		});
427 427
 		$unique = sizeof($where);
Please login to merge, or discard this patch.
Indentation   +556 added lines, -556 removed lines patch added patch discarded remove patch
@@ -14,560 +14,560 @@
 block discarded – undo
14 14
  */
15 15
 abstract class Checkable extends Field
16 16
 {
17
-	/**
18
-	 * Renders the checkables as inline
19
-	 *
20
-	 * @var boolean
21
-	 */
22
-	protected $inline = false;
23
-
24
-	/**
25
-	 * Add a text to a single element
26
-	 *
27
-	 * @var string
28
-	 */
29
-	protected $text = null;
30
-
31
-	/**
32
-	 * Renders the checkables as grouped
33
-	 *
34
-	 * @var boolean
35
-	 */
36
-	protected $grouped = false;
37
-
38
-	/**
39
-	 * The checkable items currently stored
40
-	 *
41
-	 * @var array
42
-	 */
43
-	protected $items = array();
44
-
45
-	/**
46
-	 * The type of checkable item
47
-	 *
48
-	 * @var string
49
-	 */
50
-	protected $checkable = null;
51
-
52
-	/**
53
-	 * An array of checked items
54
-	 *
55
-	 * @var array
56
-	 */
57
-	protected $checked = array();
58
-
59
-	/**
60
-	 * The checkable currently being focused on
61
-	 *
62
-	 * @var integer
63
-	 */
64
-	protected $focus = null;
65
-
66
-	/**
67
-	 * Whether this particular checkable is to be pushed
68
-	 *
69
-	 * @var boolean
70
-	 */
71
-	protected $isPushed = null;
72
-
73
-	////////////////////////////////////////////////////////////////////
74
-	//////////////////////////// CORE METHODS //////////////////////////
75
-	////////////////////////////////////////////////////////////////////
76
-
77
-	/**
78
-	 * Build a new checkable
79
-	 *
80
-	 * @param Container $app
81
-	 * @param string    $type
82
-	 * @param array     $name
83
-	 * @param           $label
84
-	 * @param           $value
85
-	 * @param           $attributes
86
-	 */
87
-	public function __construct(Container $app, $type, $name, $label, $value, $attributes)
88
-	{
89
-		// Unify auto and chained methods of grouping checkboxes
90
-		if (Str::endsWith($name, '[]')) {
91
-			$name = substr($name, 0, -2);
92
-			$this->grouped();
93
-		}
94
-		parent::__construct($app, $type, $name, $label, $value, $attributes);
95
-
96
-		if (is_array($this->value)) {
97
-			$this->items($this->value);
98
-		}
99
-	}
100
-
101
-	/**
102
-	 * Apply methods to focused checkable
103
-	 *
104
-	 * @param string $method
105
-	 * @param array  $parameters
106
-	 *
107
-	 * @return $this
108
-	 */
109
-	public function __call($method, $parameters)
110
-	{
111
-		$focused = $this->setOnFocused('attributes.'.$method, Arr::get($parameters, 0));
112
-		if ($focused) {
113
-			return $this;
114
-		}
115
-
116
-		return parent::__call($method, $parameters);
117
-	}
118
-
119
-	/**
120
-	 * Prints out the currently stored checkables
121
-	 */
122
-	public function render()
123
-	{
124
-		$html = null;
125
-
126
-		$this->setFieldClasses();
127
-
128
-		// Multiple items
129
-		if ($this->items) {
130
-			unset($this->app['former']->labels[array_search($this->name, $this->app['former']->labels)]);
131
-			foreach ($this->items as $key => $item) {
132
-				$value = $this->isCheckbox() && !$this->isGrouped() ? 1 : $key;
133
-				$html .= $this->createCheckable($item, $value);
134
-			}
135
-
136
-			return $html;
137
-		}
138
-
139
-		// Single item
140
-		return $this->createCheckable(array(
141
-			'name'  => $this->name,
142
-			'label' => $this->text,
143
-			'value' => $this->value,
144
-			'attributes' => $this->attributes,
145
-		));
146
-	}
147
-
148
-	////////////////////////////////////////////////////////////////////
149
-	////////////////////////// FIELD METHODS ///////////////////////////
150
-	////////////////////////////////////////////////////////////////////
151
-
152
-	/**
153
-	 * Focus on a particular checkable
154
-	 *
155
-	 * @param integer $on The checkable to focus on
156
-	 *
157
-	 * @return $this
158
-	 */
159
-	public function on($on)
160
-	{
161
-		if (!isset($this->items[$on])) {
162
-			return $this;
163
-		} else {
164
-			$this->focus = $on;
165
-		}
166
-
167
-		return $this;
168
-	}
169
-
170
-	/**
171
-	 * Set the checkables as inline
172
-	 */
173
-	public function inline($isInline = true)
174
-	{
175
-		$this->inline = $isInline;
176
-
177
-		return $this;
178
-	}
179
-
180
-	/**
181
-	 * Set the checkables as stacked
182
-	 */
183
-	public function stacked($isStacked = true)
184
-	{
185
-		$this->inline = !$isStacked;
186
-
187
-		return $this;
188
-	}
189
-
190
-	/**
191
-	 * Set the checkables as grouped
192
-	 */
193
-	public function grouped($isGrouped = true)
194
-	{
195
-		$this->grouped = $isGrouped;
196
-
197
-		return $this;
198
-	}
199
-
200
-	/**
201
-	 * Add text to a single checkable
202
-	 *
203
-	 * @param  string $text The checkable label
204
-	 *
205
-	 * @return $this
206
-	 */
207
-	public function text($text)
208
-	{
209
-		// Translate and format
210
-		$text = Helpers::translate($text);
211
-
212
-		// Apply on focused if any
213
-		$focused = $this->setOnFocused('label', $text);
214
-		if ($focused) {
215
-			return $this;
216
-		}
217
-
218
-		$this->text = $text;
219
-
220
-		return $this;
221
-	}
222
-
223
-	/**
224
-	 * Push this particular checkbox
225
-	 *
226
-	 * @param boolean $pushed
227
-	 *
228
-	 * @return $this
229
-	 */
230
-	public function push($pushed = true)
231
-	{
232
-		$this->isPushed = $pushed;
233
-
234
-		return $this;
235
-	}
236
-
237
-	/**
238
-	 * Check a specific item
239
-	 *
240
-	 * @param bool|string $checked The checkable to check, or an array of checked items
241
-	 *
242
-	 * @return $this
243
-	 */
244
-	public function check($checked = true)
245
-	{
246
-		// If we're setting all the checked items at once
247
-		if (is_array($checked)) {
248
-			$this->checked = $checked;
249
-			// Checking an item in particular
250
-		} elseif (is_string($checked) or is_int($checked)) {
251
-			$this->checked[$checked] = true;
252
-			// Only setting a single item
253
-		} else {
254
-			$this->checked[$this->name] = (bool) $checked;
255
-		}
256
-
257
-		return $this;
258
-	}
259
-
260
-	////////////////////////////////////////////////////////////////////
261
-	////////////////////////// INTERNAL METHODS ////////////////////////
262
-	////////////////////////////////////////////////////////////////////
263
-
264
-	/**
265
-	 * Creates a series of checkable items
266
-	 *
267
-	 * @param array $_items Items to create
268
-	 */
269
-	protected function items($_items)
270
-	{
271
-		// If passing an array
272
-		if (sizeof($_items) == 1 and
273
-			isset($_items[0]) and
274
-			is_array($_items[0])
275
-		) {
276
-			$_items = $_items[0];
277
-		}
278
-
279
-		// Fetch models if that's what we were passed
280
-		if (isset($_items[0]) and is_object($_items[0])) {
281
-			$_items = Helpers::queryToArray($_items);
282
-			$_items = array_flip($_items);
283
-		}
284
-
285
-		// Iterate through items, assign a name and a label to each
286
-		$count = 0;
287
-		foreach ($_items as $label => $name) {
288
-
289
-			// Define a fallback name in case none is found
290
-			$fallback = $this->isCheckbox()
291
-				? $this->name.'_'.$count
292
-				: $this->name;
293
-
294
-			// Grouped fields
295
-			if ($this->isGrouped()) {
296
-				$attributes['id'] = str_replace('[]', null, $fallback);
297
-				$fallback         = str_replace('[]', null, $this->name).'[]';
298
-			}
299
-
300
-			// If we haven't any name defined for the checkable, try to compute some
301
-			if (!is_string($label) and !is_array($name)) {
302
-				$label = $name;
303
-				$name  = $fallback;
304
-			}
305
-
306
-			// If we gave custom information on the item, add them
307
-			if (is_array($name)) {
308
-				$attributes = $name;
309
-				$name       = Arr::get($attributes, 'name', $fallback);
310
-				unset($attributes['name']);
311
-			}
312
-
313
-			// Store all informations we have in an array
314
-			$item = array(
315
-				'name'  => $name,
316
-				'label' => Helpers::translate($label),
317
-				'count' => $count,
318
-			);
319
-			if (isset($attributes)) {
320
-				$item['attributes'] = $attributes;
321
-			}
322
-
323
-			$this->items[] = $item;
324
-			$count++;
325
-		}
326
-	}
327
-
328
-	/**
329
-	 * Renders a checkable
330
-	 *
331
-	 * @param string|array $item          A checkable item
332
-	 * @param integer      $fallbackValue A fallback value if none is set
333
-	 *
334
-	 * @return string
335
-	 */
336
-	protected function createCheckable($item, $fallbackValue = 1)
337
-	{
338
-		// Extract informations
339
-		extract($item);
340
-
341
-		// Set default values
342
-		if (!isset($attributes)) {
343
-			$attributes = array();
344
-		}
345
-		if (isset($attributes['value'])) {
346
-			$value = $attributes['value'];
347
-		}
348
-		if (!isset($value) or $value === $this->app['former']->getOption('unchecked_value')) {
349
-			$value = $fallbackValue;
350
-		}
351
-
352
-		// If inline items, add class
353
-		$isInline = $this->inline ? ' '.$this->app['former.framework']->getInlineLabelClass($this) : null;
354
-
355
-		// In Bootsrap 3 or 4, don't append the the checkable type (radio/checkbox) as a class if
356
-		// rendering inline.
357
-		$class =  ($this->app['former']->framework() == 'TwitterBootstrap3' ||
358
-			$this->app['former']->framework() == 'TwitterBootstrap4') ? trim($isInline) : $this->checkable.$isInline;
359
-
360
-		// Merge custom attributes with global attributes
361
-		$attributes = array_merge($this->attributes, $attributes);
362
-		if (!isset($attributes['id'])) {
363
-			$attributes['id'] = $name.$this->unique($name);
364
-		}
365
-
366
-		// Create field
367
-		$field = Input::create($this->checkable, $name, Helpers::encode($value), $attributes);
368
-		if ($this->isChecked($item, $value)) {
369
-			$field->checked('checked');
370
-		}
371
-
372
-		// Add hidden checkbox if requested
373
-		if ($this->isOfType('checkbox', 'checkboxes')) {
374
-			if ($this->isPushed or ($this->app['former']->getOption('push_checkboxes') and $this->isPushed !== false)) {
375
-				$field = $this->app['former']->hidden($name)->forceValue($this->app['former']->getOption('unchecked_value')).$field->render();
376
-
377
-				// app['former.field'] was overwritten by Former::hidden() call in the line above, so here
378
-				// we reset it to $this to enable $this->app['former']->getErrors() to retrieve the correct object
379
-				$this->app->instance('former.field', $this);
380
-			}
381
-		}
382
-
383
-		// If no label to wrap, return plain checkable
384
-		if (!$label) {
385
-			$element = (is_object($field)) ? $field->render() : $field;
386
-		} elseif ($this->app['former']->framework() == 'TwitterBootstrap4') {
387
-			// Revised for Bootstrap 4, move the 'input' outside of the 'label'
388
-			$element = $field . Element::create('label', $label)->for($attributes['id'])->class($class)->render();
389
-
390
-			$wrapper_class = $this->inline ? 'form-check form-check-inline' : 'form-check';
391
-
392
-			$element = Element::create('div', $element)->class($wrapper_class)->render();
393
-
394
-		} else {
395
-			// Original way is to add the 'input' inside the 'label'
396
-			$element = Element::create('label', $field.$label)->for($attributes['id'])->class($class)->render();
397
-		}
398
-
399
-		// If BS3, if checkables are stacked, wrap them in a div with the checkable type
400
-		if (!$isInline && $this->app['former']->framework() == 'TwitterBootstrap3') {
401
-			$wrapper = Element::create('div', $element)->class($this->checkable);
402
-			if ($this->getAttribute('disabled')) {
403
-				$wrapper->addClass('disabled');
404
-			}
405
-			$element = $wrapper->render();
406
-		}
407
-
408
-		// Return the field
409
-		return $element;
410
-	}
411
-
412
-	////////////////////////////////////////////////////////////////////
413
-	///////////////////////////// HELPERS //////////////////////////////
414
-	////////////////////////////////////////////////////////////////////
415
-
416
-	/**
417
-	 * Generate an unique ID for a field
418
-	 *
419
-	 * @param string $name The field's name
420
-	 *
421
-	 * @return string A field number to use
422
-	 */
423
-	protected function unique($name)
424
-	{
425
-		$this->app['former']->labels[] = $name;
426
-
427
-		// Count number of fields with the same ID
428
-		$where  = array_filter($this->app['former']->labels, function ($label) use ($name) {
429
-			return $label == $name;
430
-		});
431
-		$unique = sizeof($where);
432
-
433
-		// In case the field doesn't need to be numbered
434
-		if ($unique < 2 or empty($this->items)) {
435
-			return false;
436
-		}
437
-
438
-		return $unique;
439
-	}
440
-
441
-	/**
442
-	 * Set something on the currently focused checkable
443
-	 *
444
-	 * @param string $attribute The key to set
445
-	 * @param string $value     Its value
446
-	 *
447
-	 * @return $this|bool
448
-	 */
449
-	protected function setOnFocused($attribute, $value)
450
-	{
451
-		if (is_null($this->focus)) {
452
-			return false;
453
-		}
454
-
455
-		$this->items[$this->focus] = Arr::set($this->items[$this->focus], $attribute, $value);
456
-
457
-		return $this;
458
-	}
459
-
460
-	/**
461
-	 * Check if a checkable is checked
462
-	 *
463
-	 * @return boolean Checked or not
464
-	 */
465
-	protected function isChecked($item = null, $value = null)
466
-	{
467
-		if (isset($item['name'])) {
468
-			$name = $item['name'];
469
-		}
470
-		if (empty($name)) {
471
-			$name = $this->name;
472
-		}
473
-
474
-		// If it's a checkbox, see if we marqued that one as checked in the array
475
-		// Or if it's a single radio, simply see if we called check
476
-		if ($this->isCheckbox() or
477
-			!$this->isCheckbox() and !$this->items
478
-		) {
479
-			$checked = Arr::get($this->checked, $name, false);
480
-
481
-			// If there are multiple, search for the value
482
-			// as the name are the same between radios
483
-		} else {
484
-			$checked = Arr::get($this->checked, $value, false);
485
-		}
486
-
487
-		// Check the values and POST array
488
-		if ($this->isGrouped()) {
489
-			// The group index. (e.g. 'bar' if the item name is foo[bar], or the item index for foo[])
490
-			$groupIndex = self::getGroupIndexFromItem($item);
491
-
492
-			// Search using the bare name, not the individual item name
493
-			$post   = $this->app['former']->getPost($this->name);
494
-			$static = $this->app['former']->getValue($this->bind ?: $this->name);
495
-
496
-			if (isset($post[$groupIndex])) {
497
-				$post = $post[$groupIndex];
498
-			}
499
-
500
-			/**
501
-			 * Support for Laravel Collection repopulating for grouped checkboxes. Note that the groupIndex must
502
-			 * match the value in order for the checkbox to be considered checked, e.g.:
503
-			 *
504
-			 *  array(
505
-			 *    'name' = 'roles[foo]',
506
-			 *    'value' => 'foo',
507
-			 *  )
508
-			 */
509
-			if ($static instanceof Collection) {
510
-				// If the repopulate value is a collection, search for an item matching the $groupIndex
511
-				foreach ($static as $staticItem) {
512
-					$staticItemValue = method_exists($staticItem, 'getKey') ? $staticItem->getKey() : $staticItem;
513
-					if ($staticItemValue == $groupIndex) {
514
-						$static = $staticItemValue;
515
-						break;
516
-					}
517
-				}
518
-			} else if (isset($static[$groupIndex])) {
519
-				$static = $static[$groupIndex];
520
-			}
521
-		} else {
522
-			$post   = $this->app['former']->getPost($name);
523
-			$static = $this->app['former']->getValue($this->bind ?: $name);
524
-		}
525
-
526
-		if (!is_null($post) and $post !== $this->app['former']->getOption('unchecked_value')) {
527
-			$isChecked = ($post == $value);
528
-		} elseif (!is_null($static)) {
529
-			$isChecked = ($static == $value);
530
-		} else {
531
-			$isChecked = $checked;
532
-		}
533
-
534
-		return $isChecked ? true : false;
535
-	}
536
-
537
-	/**
538
-	 * Check if the current element is a checkbox
539
-	 *
540
-	 * @return boolean Checkbox or radio
541
-	 */
542
-	protected function isCheckbox()
543
-	{
544
-		return $this->checkable == 'checkbox';
545
-	}
546
-
547
-	/**
548
-	 * Check if the checkables are grouped or not
549
-	 *
550
-	 * @return boolean
551
-	 */
552
-	protected function isGrouped()
553
-	{
554
-		return
555
-			$this->grouped == true or
556
-			strpos($this->name, '[]') !== false;
557
-	}
558
-
559
-	/**
560
-	 * @param array $item The item array, containing at least name and count keys.
561
-	 *
562
-	 * @return mixed The group index. (e.g. returns bar if the item name is foo[bar], or the item count for foo[])
563
-	 */
564
-	public static function getGroupIndexFromItem($item)
565
-	{
566
-		$groupIndex = preg_replace('/^.*?\[(.*)\]$/', '$1', $item['name']);
567
-		if (empty($groupIndex) or $groupIndex == $item['name']) {
568
-			return $item['count'];
569
-		}
570
-
571
-		return $groupIndex;
572
-	}
17
+    /**
18
+     * Renders the checkables as inline
19
+     *
20
+     * @var boolean
21
+     */
22
+    protected $inline = false;
23
+
24
+    /**
25
+     * Add a text to a single element
26
+     *
27
+     * @var string
28
+     */
29
+    protected $text = null;
30
+
31
+    /**
32
+     * Renders the checkables as grouped
33
+     *
34
+     * @var boolean
35
+     */
36
+    protected $grouped = false;
37
+
38
+    /**
39
+     * The checkable items currently stored
40
+     *
41
+     * @var array
42
+     */
43
+    protected $items = array();
44
+
45
+    /**
46
+     * The type of checkable item
47
+     *
48
+     * @var string
49
+     */
50
+    protected $checkable = null;
51
+
52
+    /**
53
+     * An array of checked items
54
+     *
55
+     * @var array
56
+     */
57
+    protected $checked = array();
58
+
59
+    /**
60
+     * The checkable currently being focused on
61
+     *
62
+     * @var integer
63
+     */
64
+    protected $focus = null;
65
+
66
+    /**
67
+     * Whether this particular checkable is to be pushed
68
+     *
69
+     * @var boolean
70
+     */
71
+    protected $isPushed = null;
72
+
73
+    ////////////////////////////////////////////////////////////////////
74
+    //////////////////////////// CORE METHODS //////////////////////////
75
+    ////////////////////////////////////////////////////////////////////
76
+
77
+    /**
78
+     * Build a new checkable
79
+     *
80
+     * @param Container $app
81
+     * @param string    $type
82
+     * @param array     $name
83
+     * @param           $label
84
+     * @param           $value
85
+     * @param           $attributes
86
+     */
87
+    public function __construct(Container $app, $type, $name, $label, $value, $attributes)
88
+    {
89
+        // Unify auto and chained methods of grouping checkboxes
90
+        if (Str::endsWith($name, '[]')) {
91
+            $name = substr($name, 0, -2);
92
+            $this->grouped();
93
+        }
94
+        parent::__construct($app, $type, $name, $label, $value, $attributes);
95
+
96
+        if (is_array($this->value)) {
97
+            $this->items($this->value);
98
+        }
99
+    }
100
+
101
+    /**
102
+     * Apply methods to focused checkable
103
+     *
104
+     * @param string $method
105
+     * @param array  $parameters
106
+     *
107
+     * @return $this
108
+     */
109
+    public function __call($method, $parameters)
110
+    {
111
+        $focused = $this->setOnFocused('attributes.'.$method, Arr::get($parameters, 0));
112
+        if ($focused) {
113
+            return $this;
114
+        }
115
+
116
+        return parent::__call($method, $parameters);
117
+    }
118
+
119
+    /**
120
+     * Prints out the currently stored checkables
121
+     */
122
+    public function render()
123
+    {
124
+        $html = null;
125
+
126
+        $this->setFieldClasses();
127
+
128
+        // Multiple items
129
+        if ($this->items) {
130
+            unset($this->app['former']->labels[array_search($this->name, $this->app['former']->labels)]);
131
+            foreach ($this->items as $key => $item) {
132
+                $value = $this->isCheckbox() && !$this->isGrouped() ? 1 : $key;
133
+                $html .= $this->createCheckable($item, $value);
134
+            }
135
+
136
+            return $html;
137
+        }
138
+
139
+        // Single item
140
+        return $this->createCheckable(array(
141
+            'name'  => $this->name,
142
+            'label' => $this->text,
143
+            'value' => $this->value,
144
+            'attributes' => $this->attributes,
145
+        ));
146
+    }
147
+
148
+    ////////////////////////////////////////////////////////////////////
149
+    ////////////////////////// FIELD METHODS ///////////////////////////
150
+    ////////////////////////////////////////////////////////////////////
151
+
152
+    /**
153
+     * Focus on a particular checkable
154
+     *
155
+     * @param integer $on The checkable to focus on
156
+     *
157
+     * @return $this
158
+     */
159
+    public function on($on)
160
+    {
161
+        if (!isset($this->items[$on])) {
162
+            return $this;
163
+        } else {
164
+            $this->focus = $on;
165
+        }
166
+
167
+        return $this;
168
+    }
169
+
170
+    /**
171
+     * Set the checkables as inline
172
+     */
173
+    public function inline($isInline = true)
174
+    {
175
+        $this->inline = $isInline;
176
+
177
+        return $this;
178
+    }
179
+
180
+    /**
181
+     * Set the checkables as stacked
182
+     */
183
+    public function stacked($isStacked = true)
184
+    {
185
+        $this->inline = !$isStacked;
186
+
187
+        return $this;
188
+    }
189
+
190
+    /**
191
+     * Set the checkables as grouped
192
+     */
193
+    public function grouped($isGrouped = true)
194
+    {
195
+        $this->grouped = $isGrouped;
196
+
197
+        return $this;
198
+    }
199
+
200
+    /**
201
+     * Add text to a single checkable
202
+     *
203
+     * @param  string $text The checkable label
204
+     *
205
+     * @return $this
206
+     */
207
+    public function text($text)
208
+    {
209
+        // Translate and format
210
+        $text = Helpers::translate($text);
211
+
212
+        // Apply on focused if any
213
+        $focused = $this->setOnFocused('label', $text);
214
+        if ($focused) {
215
+            return $this;
216
+        }
217
+
218
+        $this->text = $text;
219
+
220
+        return $this;
221
+    }
222
+
223
+    /**
224
+     * Push this particular checkbox
225
+     *
226
+     * @param boolean $pushed
227
+     *
228
+     * @return $this
229
+     */
230
+    public function push($pushed = true)
231
+    {
232
+        $this->isPushed = $pushed;
233
+
234
+        return $this;
235
+    }
236
+
237
+    /**
238
+     * Check a specific item
239
+     *
240
+     * @param bool|string $checked The checkable to check, or an array of checked items
241
+     *
242
+     * @return $this
243
+     */
244
+    public function check($checked = true)
245
+    {
246
+        // If we're setting all the checked items at once
247
+        if (is_array($checked)) {
248
+            $this->checked = $checked;
249
+            // Checking an item in particular
250
+        } elseif (is_string($checked) or is_int($checked)) {
251
+            $this->checked[$checked] = true;
252
+            // Only setting a single item
253
+        } else {
254
+            $this->checked[$this->name] = (bool) $checked;
255
+        }
256
+
257
+        return $this;
258
+    }
259
+
260
+    ////////////////////////////////////////////////////////////////////
261
+    ////////////////////////// INTERNAL METHODS ////////////////////////
262
+    ////////////////////////////////////////////////////////////////////
263
+
264
+    /**
265
+     * Creates a series of checkable items
266
+     *
267
+     * @param array $_items Items to create
268
+     */
269
+    protected function items($_items)
270
+    {
271
+        // If passing an array
272
+        if (sizeof($_items) == 1 and
273
+            isset($_items[0]) and
274
+            is_array($_items[0])
275
+        ) {
276
+            $_items = $_items[0];
277
+        }
278
+
279
+        // Fetch models if that's what we were passed
280
+        if (isset($_items[0]) and is_object($_items[0])) {
281
+            $_items = Helpers::queryToArray($_items);
282
+            $_items = array_flip($_items);
283
+        }
284
+
285
+        // Iterate through items, assign a name and a label to each
286
+        $count = 0;
287
+        foreach ($_items as $label => $name) {
288
+
289
+            // Define a fallback name in case none is found
290
+            $fallback = $this->isCheckbox()
291
+                ? $this->name.'_'.$count
292
+                : $this->name;
293
+
294
+            // Grouped fields
295
+            if ($this->isGrouped()) {
296
+                $attributes['id'] = str_replace('[]', null, $fallback);
297
+                $fallback         = str_replace('[]', null, $this->name).'[]';
298
+            }
299
+
300
+            // If we haven't any name defined for the checkable, try to compute some
301
+            if (!is_string($label) and !is_array($name)) {
302
+                $label = $name;
303
+                $name  = $fallback;
304
+            }
305
+
306
+            // If we gave custom information on the item, add them
307
+            if (is_array($name)) {
308
+                $attributes = $name;
309
+                $name       = Arr::get($attributes, 'name', $fallback);
310
+                unset($attributes['name']);
311
+            }
312
+
313
+            // Store all informations we have in an array
314
+            $item = array(
315
+                'name'  => $name,
316
+                'label' => Helpers::translate($label),
317
+                'count' => $count,
318
+            );
319
+            if (isset($attributes)) {
320
+                $item['attributes'] = $attributes;
321
+            }
322
+
323
+            $this->items[] = $item;
324
+            $count++;
325
+        }
326
+    }
327
+
328
+    /**
329
+     * Renders a checkable
330
+     *
331
+     * @param string|array $item          A checkable item
332
+     * @param integer      $fallbackValue A fallback value if none is set
333
+     *
334
+     * @return string
335
+     */
336
+    protected function createCheckable($item, $fallbackValue = 1)
337
+    {
338
+        // Extract informations
339
+        extract($item);
340
+
341
+        // Set default values
342
+        if (!isset($attributes)) {
343
+            $attributes = array();
344
+        }
345
+        if (isset($attributes['value'])) {
346
+            $value = $attributes['value'];
347
+        }
348
+        if (!isset($value) or $value === $this->app['former']->getOption('unchecked_value')) {
349
+            $value = $fallbackValue;
350
+        }
351
+
352
+        // If inline items, add class
353
+        $isInline = $this->inline ? ' '.$this->app['former.framework']->getInlineLabelClass($this) : null;
354
+
355
+        // In Bootsrap 3 or 4, don't append the the checkable type (radio/checkbox) as a class if
356
+        // rendering inline.
357
+        $class =  ($this->app['former']->framework() == 'TwitterBootstrap3' ||
358
+            $this->app['former']->framework() == 'TwitterBootstrap4') ? trim($isInline) : $this->checkable.$isInline;
359
+
360
+        // Merge custom attributes with global attributes
361
+        $attributes = array_merge($this->attributes, $attributes);
362
+        if (!isset($attributes['id'])) {
363
+            $attributes['id'] = $name.$this->unique($name);
364
+        }
365
+
366
+        // Create field
367
+        $field = Input::create($this->checkable, $name, Helpers::encode($value), $attributes);
368
+        if ($this->isChecked($item, $value)) {
369
+            $field->checked('checked');
370
+        }
371
+
372
+        // Add hidden checkbox if requested
373
+        if ($this->isOfType('checkbox', 'checkboxes')) {
374
+            if ($this->isPushed or ($this->app['former']->getOption('push_checkboxes') and $this->isPushed !== false)) {
375
+                $field = $this->app['former']->hidden($name)->forceValue($this->app['former']->getOption('unchecked_value')).$field->render();
376
+
377
+                // app['former.field'] was overwritten by Former::hidden() call in the line above, so here
378
+                // we reset it to $this to enable $this->app['former']->getErrors() to retrieve the correct object
379
+                $this->app->instance('former.field', $this);
380
+            }
381
+        }
382
+
383
+        // If no label to wrap, return plain checkable
384
+        if (!$label) {
385
+            $element = (is_object($field)) ? $field->render() : $field;
386
+        } elseif ($this->app['former']->framework() == 'TwitterBootstrap4') {
387
+            // Revised for Bootstrap 4, move the 'input' outside of the 'label'
388
+            $element = $field . Element::create('label', $label)->for($attributes['id'])->class($class)->render();
389
+
390
+            $wrapper_class = $this->inline ? 'form-check form-check-inline' : 'form-check';
391
+
392
+            $element = Element::create('div', $element)->class($wrapper_class)->render();
393
+
394
+        } else {
395
+            // Original way is to add the 'input' inside the 'label'
396
+            $element = Element::create('label', $field.$label)->for($attributes['id'])->class($class)->render();
397
+        }
398
+
399
+        // If BS3, if checkables are stacked, wrap them in a div with the checkable type
400
+        if (!$isInline && $this->app['former']->framework() == 'TwitterBootstrap3') {
401
+            $wrapper = Element::create('div', $element)->class($this->checkable);
402
+            if ($this->getAttribute('disabled')) {
403
+                $wrapper->addClass('disabled');
404
+            }
405
+            $element = $wrapper->render();
406
+        }
407
+
408
+        // Return the field
409
+        return $element;
410
+    }
411
+
412
+    ////////////////////////////////////////////////////////////////////
413
+    ///////////////////////////// HELPERS //////////////////////////////
414
+    ////////////////////////////////////////////////////////////////////
415
+
416
+    /**
417
+     * Generate an unique ID for a field
418
+     *
419
+     * @param string $name The field's name
420
+     *
421
+     * @return string A field number to use
422
+     */
423
+    protected function unique($name)
424
+    {
425
+        $this->app['former']->labels[] = $name;
426
+
427
+        // Count number of fields with the same ID
428
+        $where  = array_filter($this->app['former']->labels, function ($label) use ($name) {
429
+            return $label == $name;
430
+        });
431
+        $unique = sizeof($where);
432
+
433
+        // In case the field doesn't need to be numbered
434
+        if ($unique < 2 or empty($this->items)) {
435
+            return false;
436
+        }
437
+
438
+        return $unique;
439
+    }
440
+
441
+    /**
442
+     * Set something on the currently focused checkable
443
+     *
444
+     * @param string $attribute The key to set
445
+     * @param string $value     Its value
446
+     *
447
+     * @return $this|bool
448
+     */
449
+    protected function setOnFocused($attribute, $value)
450
+    {
451
+        if (is_null($this->focus)) {
452
+            return false;
453
+        }
454
+
455
+        $this->items[$this->focus] = Arr::set($this->items[$this->focus], $attribute, $value);
456
+
457
+        return $this;
458
+    }
459
+
460
+    /**
461
+     * Check if a checkable is checked
462
+     *
463
+     * @return boolean Checked or not
464
+     */
465
+    protected function isChecked($item = null, $value = null)
466
+    {
467
+        if (isset($item['name'])) {
468
+            $name = $item['name'];
469
+        }
470
+        if (empty($name)) {
471
+            $name = $this->name;
472
+        }
473
+
474
+        // If it's a checkbox, see if we marqued that one as checked in the array
475
+        // Or if it's a single radio, simply see if we called check
476
+        if ($this->isCheckbox() or
477
+            !$this->isCheckbox() and !$this->items
478
+        ) {
479
+            $checked = Arr::get($this->checked, $name, false);
480
+
481
+            // If there are multiple, search for the value
482
+            // as the name are the same between radios
483
+        } else {
484
+            $checked = Arr::get($this->checked, $value, false);
485
+        }
486
+
487
+        // Check the values and POST array
488
+        if ($this->isGrouped()) {
489
+            // The group index. (e.g. 'bar' if the item name is foo[bar], or the item index for foo[])
490
+            $groupIndex = self::getGroupIndexFromItem($item);
491
+
492
+            // Search using the bare name, not the individual item name
493
+            $post   = $this->app['former']->getPost($this->name);
494
+            $static = $this->app['former']->getValue($this->bind ?: $this->name);
495
+
496
+            if (isset($post[$groupIndex])) {
497
+                $post = $post[$groupIndex];
498
+            }
499
+
500
+            /**
501
+             * Support for Laravel Collection repopulating for grouped checkboxes. Note that the groupIndex must
502
+             * match the value in order for the checkbox to be considered checked, e.g.:
503
+             *
504
+             *  array(
505
+             *    'name' = 'roles[foo]',
506
+             *    'value' => 'foo',
507
+             *  )
508
+             */
509
+            if ($static instanceof Collection) {
510
+                // If the repopulate value is a collection, search for an item matching the $groupIndex
511
+                foreach ($static as $staticItem) {
512
+                    $staticItemValue = method_exists($staticItem, 'getKey') ? $staticItem->getKey() : $staticItem;
513
+                    if ($staticItemValue == $groupIndex) {
514
+                        $static = $staticItemValue;
515
+                        break;
516
+                    }
517
+                }
518
+            } else if (isset($static[$groupIndex])) {
519
+                $static = $static[$groupIndex];
520
+            }
521
+        } else {
522
+            $post   = $this->app['former']->getPost($name);
523
+            $static = $this->app['former']->getValue($this->bind ?: $name);
524
+        }
525
+
526
+        if (!is_null($post) and $post !== $this->app['former']->getOption('unchecked_value')) {
527
+            $isChecked = ($post == $value);
528
+        } elseif (!is_null($static)) {
529
+            $isChecked = ($static == $value);
530
+        } else {
531
+            $isChecked = $checked;
532
+        }
533
+
534
+        return $isChecked ? true : false;
535
+    }
536
+
537
+    /**
538
+     * Check if the current element is a checkbox
539
+     *
540
+     * @return boolean Checkbox or radio
541
+     */
542
+    protected function isCheckbox()
543
+    {
544
+        return $this->checkable == 'checkbox';
545
+    }
546
+
547
+    /**
548
+     * Check if the checkables are grouped or not
549
+     *
550
+     * @return boolean
551
+     */
552
+    protected function isGrouped()
553
+    {
554
+        return
555
+            $this->grouped == true or
556
+            strpos($this->name, '[]') !== false;
557
+    }
558
+
559
+    /**
560
+     * @param array $item The item array, containing at least name and count keys.
561
+     *
562
+     * @return mixed The group index. (e.g. returns bar if the item name is foo[bar], or the item count for foo[])
563
+     */
564
+    public static function getGroupIndexFromItem($item)
565
+    {
566
+        $groupIndex = preg_replace('/^.*?\[(.*)\]$/', '$1', $item['name']);
567
+        if (empty($groupIndex) or $groupIndex == $item['name']) {
568
+            return $item['count'];
569
+        }
570
+
571
+        return $groupIndex;
572
+    }
573 573
 }
Please login to merge, or discard this patch.
src/config/former.php 1 patch
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -1,207 +1,207 @@
 block discarded – undo
1 1
 <?php return array(
2 2
 
3
-	// Markup
4
-	////////////////////////////////////////////////////////////////////
5
-
6
-	// Whether labels should be automatically computed from name
7
-	'automatic_label'         => true,
8
-
9
-	// The default form type
10
-	'default_form_type'       => 'horizontal',
11
-
12
-	// Validation
13
-	////////////////////////////////////////////////////////////////////
14
-
15
-	// Whether Former should fetch errors from Session
16
-	'fetch_errors'            => true,
17
-
18
-	// Whether Former should try to apply Validator rules as attributes
19
-	'live_validation'         => true,
20
-
21
-	// Whether Former should automatically fetch error messages and
22
-	// display them next to the matching fields
23
-	'error_messages'          => true,
24
-
25
-	// Checkables
26
-	////////////////////////////////////////////////////////////////////
27
-
28
-	// Whether checkboxes should always be present in the POST data,
29
-	// no matter if you checked them or not
30
-	'push_checkboxes'         => false,
31
-
32
-	// The value a checkbox will have in the POST array if unchecked
33
-	'unchecked_value'         => 0,
34
-
35
-	// Required fields
36
-	////////////////////////////////////////////////////////////////////
37
-
38
-	// The class to be added to required fields
39
-	'required_class'          => 'required',
40
-
41
-	// A facultative text to append to the labels of required fields
42
-	'required_text'           => '<sup>*</sup>',
43
-
44
-	// Translations
45
-	////////////////////////////////////////////////////////////////////
46
-
47
-	// Where Former should look for translations
48
-	'translate_from'          => 'validation.attributes',
49
-
50
-	// Whether text that comes out of the translated
51
-	// should be capitalized (ex: email => Email) automatically
52
-	'capitalize_translations' => true,
53
-
54
-	// An array of attributes to automatically translate
55
-	'translatable'            => array(
56
-		'help',
57
-		'inlineHelp',
58
-		'blockHelp',
59
-		'placeholder',
60
-		'data_placeholder',
61
-		'label',
62
-	),
63
-
64
-	// Framework
65
-	////////////////////////////////////////////////////////////////////
66
-
67
-	// The framework to be used by Former
68
-	'framework'               => 'TwitterBootstrap3',
69
-
70
-	'TwitterBootstrap4'       => array(
71
-
72
-		// Map Former-supported viewports to Bootstrap 4 equivalents
73
-		'viewports'   => array(
74
-			'large'  => 'lg',
75
-			'medium' => 'md',
76
-			'small'  => 'sm',
77
-			'mini'   => 'xs',
78
-		),
79
-		// Width of labels for horizontal forms expressed as viewport => grid columns
80
-		'labelWidths' => array(
81
-			'large' => 2,
82
-			'small' => 4,
83
-		),
84
-		// HTML markup and classes used by Bootstrap 5 for icons
85
-		'icon'        => array(
86
-			'tag'    => 'i',
87
-			'set'    => 'fa',
88
-			'prefix' => 'fa',
89
-		),
90
-
91
-	),
92
-
93
-	'TwitterBootstrap3'       => array(
94
-
95
-		// Map Former-supported viewports to Bootstrap 3 equivalents
96
-		'viewports'   => array(
97
-			'large'  => 'lg',
98
-			'medium' => 'md',
99
-			'small'  => 'sm',
100
-			'mini'   => 'xs',
101
-		),
102
-		// Width of labels for horizontal forms expressed as viewport => grid columns
103
-		'labelWidths' => array(
104
-			'large' => 2,
105
-			'small' => 4,
106
-		),
107
-		// HTML markup and classes used by Bootstrap 3 for icons
108
-		'icon'        => array(
109
-			'tag'    => 'span',
110
-			'set'    => 'glyphicon',
111
-			'prefix' => 'glyphicon',
112
-		),
113
-
114
-	),
115
-
116
-	'Nude'                    => array(  // No-framework markup
117
-		'icon' => array(
118
-			'tag'    => 'i',
119
-			'set'    => null,
120
-			'prefix' => 'icon',
121
-		),
122
-	),
123
-
124
-	'TwitterBootstrap'        => array( // Twitter Bootstrap version 2
125
-		'icon' => array(
126
-			'tag'    => 'i',
127
-			'set'    => null,
128
-			'prefix' => 'icon',
129
-		),
130
-	),
131
-
132
-	'ZurbFoundation5'         => array(
133
-		// Map Former-supported viewports to Foundation 5 equivalents
134
-		'viewports'           => array(
135
-			'large'  => 'large',
136
-			'medium' => null,
137
-			'small'  => 'small',
138
-			'mini'   => null,
139
-		),
140
-		// Width of labels for horizontal forms expressed as viewport => grid columns
141
-		'labelWidths'         => array(
142
-			'small' => 3,
143
-		),
144
-		// Classes to be applied to wrapped labels in horizontal forms
145
-		'wrappedLabelClasses' => array('right', 'inline'),
146
-		// HTML markup and classes used by Foundation 5 for icons
147
-		'icon'                => array(
148
-			'tag'    => 'i',
149
-			'set'    => null,
150
-			'prefix' => 'fi',
151
-		),
152
-		// CSS for inline validation errors
153
-		'error_classes'       => array('class' => 'error'),
154
-	),
155
-
156
-	'ZurbFoundation4'         => array(
157
-		// Foundation 4 also has an experimental "medium" breakpoint
158
-		// explained at http://foundation.zurb.com/docs/components/grid.html
159
-		'viewports'           => array(
160
-			'large'  => 'large',
161
-			'medium' => null,
162
-			'small'  => 'small',
163
-			'mini'   => null,
164
-		),
165
-		// Width of labels for horizontal forms expressed as viewport => grid columns
166
-		'labelWidths'         => array(
167
-			'small' => 3,
168
-		),
169
-		// Classes to be applied to wrapped labels in horizontal forms
170
-		'wrappedLabelClasses' => array('right', 'inline'),
171
-		// HTML markup and classes used by Foundation 4 for icons
172
-		'icon'                => array(
173
-			'tag'    => 'i',
174
-			'set'    => 'general',
175
-			'prefix' => 'foundicon',
176
-		),
177
-		// CSS for inline validation errors
178
-		'error_classes'       => array('class' => 'alert-box radius warning'),
179
-	),
180
-
181
-	'ZurbFoundation'          => array( // Foundation 3
182
-		'viewports'           => array(
183
-			'large'  => '',
184
-			'medium' => null,
185
-			'small'  => 'mobile-',
186
-			'mini'   => null,
187
-		),
188
-		// Width of labels for horizontal forms expressed as viewport => grid columns
189
-		'labelWidths'         => array(
190
-			'large' => 2,
191
-			'small' => 4,
192
-		),
193
-		// Classes to be applied to wrapped labels in horizontal forms
194
-		'wrappedLabelClasses' => array('right', 'inline'),
195
-		// HTML markup and classes used by Foundation 3 for icons
196
-		'icon'                => array(
197
-			'tag'    => 'i',
198
-			'set'    => null,
199
-			'prefix' => 'fi',
200
-		),
201
-		// CSS for inline validation errors
202
-		// should work for Zurb 2 and 3
203
-		'error_classes'       => array('class' => 'alert-box alert error'),
204
-	),
3
+    // Markup
4
+    ////////////////////////////////////////////////////////////////////
5
+
6
+    // Whether labels should be automatically computed from name
7
+    'automatic_label'         => true,
8
+
9
+    // The default form type
10
+    'default_form_type'       => 'horizontal',
11
+
12
+    // Validation
13
+    ////////////////////////////////////////////////////////////////////
14
+
15
+    // Whether Former should fetch errors from Session
16
+    'fetch_errors'            => true,
17
+
18
+    // Whether Former should try to apply Validator rules as attributes
19
+    'live_validation'         => true,
20
+
21
+    // Whether Former should automatically fetch error messages and
22
+    // display them next to the matching fields
23
+    'error_messages'          => true,
24
+
25
+    // Checkables
26
+    ////////////////////////////////////////////////////////////////////
27
+
28
+    // Whether checkboxes should always be present in the POST data,
29
+    // no matter if you checked them or not
30
+    'push_checkboxes'         => false,
31
+
32
+    // The value a checkbox will have in the POST array if unchecked
33
+    'unchecked_value'         => 0,
34
+
35
+    // Required fields
36
+    ////////////////////////////////////////////////////////////////////
37
+
38
+    // The class to be added to required fields
39
+    'required_class'          => 'required',
40
+
41
+    // A facultative text to append to the labels of required fields
42
+    'required_text'           => '<sup>*</sup>',
43
+
44
+    // Translations
45
+    ////////////////////////////////////////////////////////////////////
46
+
47
+    // Where Former should look for translations
48
+    'translate_from'          => 'validation.attributes',
49
+
50
+    // Whether text that comes out of the translated
51
+    // should be capitalized (ex: email => Email) automatically
52
+    'capitalize_translations' => true,
53
+
54
+    // An array of attributes to automatically translate
55
+    'translatable'            => array(
56
+        'help',
57
+        'inlineHelp',
58
+        'blockHelp',
59
+        'placeholder',
60
+        'data_placeholder',
61
+        'label',
62
+    ),
63
+
64
+    // Framework
65
+    ////////////////////////////////////////////////////////////////////
66
+
67
+    // The framework to be used by Former
68
+    'framework'               => 'TwitterBootstrap3',
69
+
70
+    'TwitterBootstrap4'       => array(
71
+
72
+        // Map Former-supported viewports to Bootstrap 4 equivalents
73
+        'viewports'   => array(
74
+            'large'  => 'lg',
75
+            'medium' => 'md',
76
+            'small'  => 'sm',
77
+            'mini'   => 'xs',
78
+        ),
79
+        // Width of labels for horizontal forms expressed as viewport => grid columns
80
+        'labelWidths' => array(
81
+            'large' => 2,
82
+            'small' => 4,
83
+        ),
84
+        // HTML markup and classes used by Bootstrap 5 for icons
85
+        'icon'        => array(
86
+            'tag'    => 'i',
87
+            'set'    => 'fa',
88
+            'prefix' => 'fa',
89
+        ),
90
+
91
+    ),
92
+
93
+    'TwitterBootstrap3'       => array(
94
+
95
+        // Map Former-supported viewports to Bootstrap 3 equivalents
96
+        'viewports'   => array(
97
+            'large'  => 'lg',
98
+            'medium' => 'md',
99
+            'small'  => 'sm',
100
+            'mini'   => 'xs',
101
+        ),
102
+        // Width of labels for horizontal forms expressed as viewport => grid columns
103
+        'labelWidths' => array(
104
+            'large' => 2,
105
+            'small' => 4,
106
+        ),
107
+        // HTML markup and classes used by Bootstrap 3 for icons
108
+        'icon'        => array(
109
+            'tag'    => 'span',
110
+            'set'    => 'glyphicon',
111
+            'prefix' => 'glyphicon',
112
+        ),
113
+
114
+    ),
115
+
116
+    'Nude'                    => array(  // No-framework markup
117
+        'icon' => array(
118
+            'tag'    => 'i',
119
+            'set'    => null,
120
+            'prefix' => 'icon',
121
+        ),
122
+    ),
123
+
124
+    'TwitterBootstrap'        => array( // Twitter Bootstrap version 2
125
+        'icon' => array(
126
+            'tag'    => 'i',
127
+            'set'    => null,
128
+            'prefix' => 'icon',
129
+        ),
130
+    ),
131
+
132
+    'ZurbFoundation5'         => array(
133
+        // Map Former-supported viewports to Foundation 5 equivalents
134
+        'viewports'           => array(
135
+            'large'  => 'large',
136
+            'medium' => null,
137
+            'small'  => 'small',
138
+            'mini'   => null,
139
+        ),
140
+        // Width of labels for horizontal forms expressed as viewport => grid columns
141
+        'labelWidths'         => array(
142
+            'small' => 3,
143
+        ),
144
+        // Classes to be applied to wrapped labels in horizontal forms
145
+        'wrappedLabelClasses' => array('right', 'inline'),
146
+        // HTML markup and classes used by Foundation 5 for icons
147
+        'icon'                => array(
148
+            'tag'    => 'i',
149
+            'set'    => null,
150
+            'prefix' => 'fi',
151
+        ),
152
+        // CSS for inline validation errors
153
+        'error_classes'       => array('class' => 'error'),
154
+    ),
155
+
156
+    'ZurbFoundation4'         => array(
157
+        // Foundation 4 also has an experimental "medium" breakpoint
158
+        // explained at http://foundation.zurb.com/docs/components/grid.html
159
+        'viewports'           => array(
160
+            'large'  => 'large',
161
+            'medium' => null,
162
+            'small'  => 'small',
163
+            'mini'   => null,
164
+        ),
165
+        // Width of labels for horizontal forms expressed as viewport => grid columns
166
+        'labelWidths'         => array(
167
+            'small' => 3,
168
+        ),
169
+        // Classes to be applied to wrapped labels in horizontal forms
170
+        'wrappedLabelClasses' => array('right', 'inline'),
171
+        // HTML markup and classes used by Foundation 4 for icons
172
+        'icon'                => array(
173
+            'tag'    => 'i',
174
+            'set'    => 'general',
175
+            'prefix' => 'foundicon',
176
+        ),
177
+        // CSS for inline validation errors
178
+        'error_classes'       => array('class' => 'alert-box radius warning'),
179
+    ),
180
+
181
+    'ZurbFoundation'          => array( // Foundation 3
182
+        'viewports'           => array(
183
+            'large'  => '',
184
+            'medium' => null,
185
+            'small'  => 'mobile-',
186
+            'mini'   => null,
187
+        ),
188
+        // Width of labels for horizontal forms expressed as viewport => grid columns
189
+        'labelWidths'         => array(
190
+            'large' => 2,
191
+            'small' => 4,
192
+        ),
193
+        // Classes to be applied to wrapped labels in horizontal forms
194
+        'wrappedLabelClasses' => array('right', 'inline'),
195
+        // HTML markup and classes used by Foundation 3 for icons
196
+        'icon'                => array(
197
+            'tag'    => 'i',
198
+            'set'    => null,
199
+            'prefix' => 'fi',
200
+        ),
201
+        // CSS for inline validation errors
202
+        // should work for Zurb 2 and 3
203
+        'error_classes'       => array('class' => 'alert-box alert error'),
204
+    ),
205 205
 
206 206
 
207 207
 );
Please login to merge, or discard this patch.
src/Former/MethodDispatcher.php 1 patch
Indentation   +235 added lines, -235 removed lines patch added patch discarded remove patch
@@ -12,239 +12,239 @@
 block discarded – undo
12 12
  */
13 13
 class MethodDispatcher
14 14
 {
15
-	/**
16
-	 * The IoC Container
17
-	 *
18
-	 * @var Container
19
-	 */
20
-	protected $app;
21
-
22
-	/**
23
-	 * An array of fields repositories
24
-	 *
25
-	 * @var array
26
-	 */
27
-	protected $repositories = array();
28
-
29
-	/**
30
-	 * Build a new Dispatcher
31
-	 *
32
-	 * @param Container $app
33
-	 * @param array     $repositories
34
-	 */
35
-	public function __construct(Container $app, $repositories)
36
-	{
37
-		$this->app          = $app;
38
-		$this->repositories = (array) $repositories;
39
-	}
40
-
41
-	////////////////////////////////////////////////////////////////////
42
-	///////////////////////////// REPOSITORIES /////////////////////////
43
-	////////////////////////////////////////////////////////////////////
44
-
45
-	/**
46
-	 * Add a fields repository
47
-	 *
48
-	 * @param string $repository
49
-	 *
50
-	 * @return $this
51
-	 */
52
-	public function addRepository($repository)
53
-	{
54
-		array_unshift($this->repositories, $repository);
55
-
56
-		return $this;
57
-	}
58
-
59
-	////////////////////////////////////////////////////////////////////
60
-	///////////////////////////// DISPATCHERS //////////////////////////
61
-	////////////////////////////////////////////////////////////////////
62
-
63
-	/**
64
-	 * Dispatch a call to a registered macro
65
-	 *
66
-	 * @param  string $method     The macro's name
67
-	 * @param  array  $parameters The macro's arguments
68
-	 *
69
-	 * @return mixed
70
-	 */
71
-	public function toMacros($method, $parameters)
72
-	{
73
-		if (!$this->app['former']->hasMacro($method)) {
74
-			return false;
75
-		}
76
-
77
-		// Get and format macro
78
-		$callback = $this->app['former']->getMacro($method);
79
-		if ($callback instanceof Closure) {
80
-			return call_user_func_array($callback, $parameters);
81
-		} // Cancel if the macro is invalid
82
-		elseif (!is_string($callback)) {
83
-			return false;
84
-		}
85
-
86
-		// Get class and method
87
-		list($class, $method) = explode('@', $callback);
88
-		$this->app->instance('Illuminate\Container\Container', $this->app);
89
-
90
-		return call_user_func_array(array($this->app->make($class), $method), $parameters);
91
-	}
92
-
93
-	/**
94
-	 * Dispatch a call over to Elements
95
-	 *
96
-	 * @param string $method     The method called
97
-	 * @param array  $parameters Its parameters
98
-	 *
99
-	 * @return string
100
-	 */
101
-	public function toElements($method, $parameters)
102
-	{
103
-		// Disregards if the method isn't an element
104
-		if (!method_exists($elements = new Form\Elements($this->app, $this->app['session']), $method)) {
105
-			return false;
106
-		}
107
-
108
-		return call_user_func_array(array($elements, $method), $parameters);
109
-	}
110
-
111
-	/**
112
-	 * Dispatch a call over to Form
113
-	 *
114
-	 * @param string $method     The method called
115
-	 * @param array  $parameters Its parameters
116
-	 *
117
-	 * @return Form
118
-	 */
119
-	public function toForm($method, $parameters)
120
-	{
121
-		// Disregards if the method doesn't contain 'open'
122
-		if (!Str::contains($method, 'open') and !Str::contains($method, 'Open')) {
123
-			return false;
124
-		}
125
-
126
-		$form = new Form\Form($this->app, $this->app['url'], $this->app['former.populator']);
127
-
128
-		return $form->openForm($method, $parameters);
129
-	}
130
-
131
-	/**
132
-	 * Dispatch a call over to Group
133
-	 *
134
-	 * @param string $method     The method called
135
-	 * @param array  $parameters Its parameters
136
-	 *
137
-	 * @return Group
138
-	 */
139
-	public function toGroup($method, $parameters)
140
-	{
141
-		// Disregards if the method isn't "group"
142
-		if ($method != 'group') {
143
-			return false;
144
-		}
145
-
146
-		// Create opener
147
-		$group = new Form\Group(
148
-			$this->app,
149
-			Arr::get($parameters, 0, null),
150
-			Arr::get($parameters, 1, null)
151
-		);
152
-
153
-		// Set custom group as true
154
-		Form\Group::$opened = true;
155
-
156
-		// Set custom group reference
157
-		Form\Group::$openGroup = $group;
158
-
159
-		return $group;
160
-	}
161
-
162
-	/**
163
-	 * Dispatch a call over to Actions
164
-	 *
165
-	 * @param string $method     The method called
166
-	 * @param array  $parameters Its parameters
167
-	 *
168
-	 * @return Actions
169
-	 */
170
-	public function toActions($method, $parameters)
171
-	{
172
-		if ($method != 'actions') {
173
-			return false;
174
-		}
175
-
176
-		return new Form\Actions($this->app, $parameters);
177
-	}
178
-
179
-	/**
180
-	 * Dispatch a call over to the Fields
181
-	 *
182
-	 * @param string $method     The method called
183
-	 * @param array  $parameters Its parameters
184
-	 *
185
-	 * @return Field
186
-	 */
187
-	public function toFields($method, $parameters)
188
-	{
189
-		// Listing parameters
190
-		$class = $this->getClassFromMethod($method);
191
-		$field = new $class(
192
-			$this->app,
193
-			$method,
194
-			Arr::get($parameters, 0),
195
-			Arr::get($parameters, 1),
196
-			Arr::get($parameters, 2),
197
-			Arr::get($parameters, 3),
198
-			Arr::get($parameters, 4),
199
-			Arr::get($parameters, 5)
200
-		);
201
-
202
-		return $field;
203
-	}
204
-
205
-	////////////////////////////////////////////////////////////////////
206
-	///////////////////////////// HELPERS //////////////////////////////
207
-	////////////////////////////////////////////////////////////////////
208
-
209
-	/**
210
-	 * Get the correct class to call according to the created field
211
-	 *
212
-	 * @param  string $method The field created
213
-	 *
214
-	 * @return string The correct class
215
-	 */
216
-	protected function getClassFromMethod($method)
217
-	{
218
-		// If the field's name directly match a class, call it
219
-		$class        = Str::singular(Str::title($method));
220
-		$studly_class = Str::singular(Str::studly($method));
221
-		foreach ($this->repositories as $repository) {
222
-			if (class_exists($repository.$studly_class)) {
223
-				return $repository.$studly_class;
224
-			} else {
225
-				if (class_exists($repository.$class)) {
226
-					return $repository.$class;
227
-				}
228
-			}
229
-		}
230
-
231
-		// Else convert known fields to their classes
232
-		switch ($method) {
233
-			case 'submit':
234
-			case 'link':
235
-			case 'reset':
236
-				$class = Former::FIELDSPACE.'Button';
237
-				break;
238
-
239
-			case 'multiselect':
240
-				$class = Former::FIELDSPACE.'Select';
241
-				break;
242
-
243
-			default:
244
-				$class = Former::FIELDSPACE.'Input';
245
-				break;
246
-		}
247
-
248
-		return $class;
249
-	}
15
+    /**
16
+     * The IoC Container
17
+     *
18
+     * @var Container
19
+     */
20
+    protected $app;
21
+
22
+    /**
23
+     * An array of fields repositories
24
+     *
25
+     * @var array
26
+     */
27
+    protected $repositories = array();
28
+
29
+    /**
30
+     * Build a new Dispatcher
31
+     *
32
+     * @param Container $app
33
+     * @param array     $repositories
34
+     */
35
+    public function __construct(Container $app, $repositories)
36
+    {
37
+        $this->app          = $app;
38
+        $this->repositories = (array) $repositories;
39
+    }
40
+
41
+    ////////////////////////////////////////////////////////////////////
42
+    ///////////////////////////// REPOSITORIES /////////////////////////
43
+    ////////////////////////////////////////////////////////////////////
44
+
45
+    /**
46
+     * Add a fields repository
47
+     *
48
+     * @param string $repository
49
+     *
50
+     * @return $this
51
+     */
52
+    public function addRepository($repository)
53
+    {
54
+        array_unshift($this->repositories, $repository);
55
+
56
+        return $this;
57
+    }
58
+
59
+    ////////////////////////////////////////////////////////////////////
60
+    ///////////////////////////// DISPATCHERS //////////////////////////
61
+    ////////////////////////////////////////////////////////////////////
62
+
63
+    /**
64
+     * Dispatch a call to a registered macro
65
+     *
66
+     * @param  string $method     The macro's name
67
+     * @param  array  $parameters The macro's arguments
68
+     *
69
+     * @return mixed
70
+     */
71
+    public function toMacros($method, $parameters)
72
+    {
73
+        if (!$this->app['former']->hasMacro($method)) {
74
+            return false;
75
+        }
76
+
77
+        // Get and format macro
78
+        $callback = $this->app['former']->getMacro($method);
79
+        if ($callback instanceof Closure) {
80
+            return call_user_func_array($callback, $parameters);
81
+        } // Cancel if the macro is invalid
82
+        elseif (!is_string($callback)) {
83
+            return false;
84
+        }
85
+
86
+        // Get class and method
87
+        list($class, $method) = explode('@', $callback);
88
+        $this->app->instance('Illuminate\Container\Container', $this->app);
89
+
90
+        return call_user_func_array(array($this->app->make($class), $method), $parameters);
91
+    }
92
+
93
+    /**
94
+     * Dispatch a call over to Elements
95
+     *
96
+     * @param string $method     The method called
97
+     * @param array  $parameters Its parameters
98
+     *
99
+     * @return string
100
+     */
101
+    public function toElements($method, $parameters)
102
+    {
103
+        // Disregards if the method isn't an element
104
+        if (!method_exists($elements = new Form\Elements($this->app, $this->app['session']), $method)) {
105
+            return false;
106
+        }
107
+
108
+        return call_user_func_array(array($elements, $method), $parameters);
109
+    }
110
+
111
+    /**
112
+     * Dispatch a call over to Form
113
+     *
114
+     * @param string $method     The method called
115
+     * @param array  $parameters Its parameters
116
+     *
117
+     * @return Form
118
+     */
119
+    public function toForm($method, $parameters)
120
+    {
121
+        // Disregards if the method doesn't contain 'open'
122
+        if (!Str::contains($method, 'open') and !Str::contains($method, 'Open')) {
123
+            return false;
124
+        }
125
+
126
+        $form = new Form\Form($this->app, $this->app['url'], $this->app['former.populator']);
127
+
128
+        return $form->openForm($method, $parameters);
129
+    }
130
+
131
+    /**
132
+     * Dispatch a call over to Group
133
+     *
134
+     * @param string $method     The method called
135
+     * @param array  $parameters Its parameters
136
+     *
137
+     * @return Group
138
+     */
139
+    public function toGroup($method, $parameters)
140
+    {
141
+        // Disregards if the method isn't "group"
142
+        if ($method != 'group') {
143
+            return false;
144
+        }
145
+
146
+        // Create opener
147
+        $group = new Form\Group(
148
+            $this->app,
149
+            Arr::get($parameters, 0, null),
150
+            Arr::get($parameters, 1, null)
151
+        );
152
+
153
+        // Set custom group as true
154
+        Form\Group::$opened = true;
155
+
156
+        // Set custom group reference
157
+        Form\Group::$openGroup = $group;
158
+
159
+        return $group;
160
+    }
161
+
162
+    /**
163
+     * Dispatch a call over to Actions
164
+     *
165
+     * @param string $method     The method called
166
+     * @param array  $parameters Its parameters
167
+     *
168
+     * @return Actions
169
+     */
170
+    public function toActions($method, $parameters)
171
+    {
172
+        if ($method != 'actions') {
173
+            return false;
174
+        }
175
+
176
+        return new Form\Actions($this->app, $parameters);
177
+    }
178
+
179
+    /**
180
+     * Dispatch a call over to the Fields
181
+     *
182
+     * @param string $method     The method called
183
+     * @param array  $parameters Its parameters
184
+     *
185
+     * @return Field
186
+     */
187
+    public function toFields($method, $parameters)
188
+    {
189
+        // Listing parameters
190
+        $class = $this->getClassFromMethod($method);
191
+        $field = new $class(
192
+            $this->app,
193
+            $method,
194
+            Arr::get($parameters, 0),
195
+            Arr::get($parameters, 1),
196
+            Arr::get($parameters, 2),
197
+            Arr::get($parameters, 3),
198
+            Arr::get($parameters, 4),
199
+            Arr::get($parameters, 5)
200
+        );
201
+
202
+        return $field;
203
+    }
204
+
205
+    ////////////////////////////////////////////////////////////////////
206
+    ///////////////////////////// HELPERS //////////////////////////////
207
+    ////////////////////////////////////////////////////////////////////
208
+
209
+    /**
210
+     * Get the correct class to call according to the created field
211
+     *
212
+     * @param  string $method The field created
213
+     *
214
+     * @return string The correct class
215
+     */
216
+    protected function getClassFromMethod($method)
217
+    {
218
+        // If the field's name directly match a class, call it
219
+        $class        = Str::singular(Str::title($method));
220
+        $studly_class = Str::singular(Str::studly($method));
221
+        foreach ($this->repositories as $repository) {
222
+            if (class_exists($repository.$studly_class)) {
223
+                return $repository.$studly_class;
224
+            } else {
225
+                if (class_exists($repository.$class)) {
226
+                    return $repository.$class;
227
+                }
228
+            }
229
+        }
230
+
231
+        // Else convert known fields to their classes
232
+        switch ($method) {
233
+            case 'submit':
234
+            case 'link':
235
+            case 'reset':
236
+                $class = Former::FIELDSPACE.'Button';
237
+                break;
238
+
239
+            case 'multiselect':
240
+                $class = Former::FIELDSPACE.'Select';
241
+                break;
242
+
243
+            default:
244
+                $class = Former::FIELDSPACE.'Input';
245
+                break;
246
+        }
247
+
248
+        return $class;
249
+    }
250 250
 }
Please login to merge, or discard this patch.
src/Former/Populator.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -11,171 +11,171 @@
 block discarded – undo
11 11
  */
12 12
 class Populator extends Collection
13 13
 {
14
-	/**
15
-	 * Create a new collection.
16
-	 *
17
-	 * @param  array|Model $items
18
-	 *
19
-	 * @return void
20
-	 */
21
-	public function __construct($items = array())
22
-	{
23
-		$this->items = $items;
24
-	}
25
-
26
-	////////////////////////////////////////////////////////////////////
27
-	///////////////////////// INDIVIDUAL VALUES ////////////////////////
28
-	////////////////////////////////////////////////////////////////////
29
-
30
-	/**
31
-	 * Get the value of a field
32
-	 *
33
-	 * @param string $field The field's name
34
-	 *
35
-	 * @return mixed
36
-	 */
37
-	public function get($field, $fallback = null)
38
-	{
39
-		// Anonymous fields should not return any value
40
-		if ($field == null) {
41
-			return null;
42
-		}
43
-
44
-		// Plain array
45
-		if (is_array($this->items) and !Str::contains($field, '[')) {
46
-			return parent::get($field, $fallback);
47
-		}
48
-
49
-		// Transform the name into an array
50
-		$value = $this->items;
51
-		$field = $this->parseFieldAsArray($field);
52
-
53
-		// Dive into the model
54
-		foreach ($field as $relationship) {
55
-
56
-			// Get attribute from model
57
-			if (!is_array($value)) {
58
-				$value = $this->getAttributeFromModel($value, $relationship, $fallback);
59
-
60
-				continue;
61
-			}
62
-
63
-			// Get attribute from model
64
-			if (array_key_exists($relationship, $value)) {
65
-				$value = $value[$relationship];
66
-			} else {
67
-				// Check array for submodels that may contain the relationship
68
-				$inSubmodel = false;
69
-
70
-				foreach ($value as $key => $submodel) {
71
-					$value[$key] = $this->getAttributeFromModel($submodel, $relationship, $fallback);
72
-
73
-					if ($value[$key] !== $fallback) {
74
-						$inSubmodel = true;
75
-					}
76
-				}
77
-
78
-				// If no submodels contained the relationship, return the fallback, not an array of fallbacks
79
-				if (!$inSubmodel) {
80
-					$value = $fallback;
81
-					break;
82
-				}
83
-			}
84
-		}
85
-
86
-		return $value;
87
-	}
88
-
89
-	////////////////////////////////////////////////////////////////////
90
-	///////////////////////////// SWAPPERS /////////////////////////////
91
-	////////////////////////////////////////////////////////////////////
92
-
93
-	/**
94
-	 * Replace the items
95
-	 *
96
-	 * @param  mixed $items
97
-	 *
98
-	 * @return void
99
-	 */
100
-	public function replace($items)
101
-	{
102
-		$this->items = $items;
103
-	}
104
-
105
-	/**
106
-	 * Reset the current values array
107
-	 *
108
-	 * @return void
109
-	 */
110
-	public function reset()
111
-	{
112
-		$this->items = array();
113
-	}
114
-
115
-	////////////////////////////////////////////////////////////////////
116
-	////////////////////////////// HELPERS /////////////////////////////
117
-	////////////////////////////////////////////////////////////////////
118
-
119
-	/**
120
-	 * Parses the name of a field to a tree of fields
121
-	 *
122
-	 * @param string $field The field's name
123
-	 *
124
-	 * @return array A tree of field
125
-	 */
126
-	protected function parseFieldAsArray($field)
127
-	{
128
-		if (Str::contains($field, '[]')) {
129
-			return (array) $field;
130
-		}
131
-
132
-		// Transform array notation to dot notation
133
-		if (Str::contains($field, '[')) {
134
-			$field = preg_replace("/[\[\]]/", '.', $field);
135
-			$field = str_replace('..', '.', $field);
136
-			$field = trim($field, '.');
137
-		}
138
-
139
-		// Parse dot notation
140
-		if (Str::contains($field, '.')) {
141
-			$field = explode('.', $field);
142
-		} else {
143
-			$field = (array) $field;
144
-		}
145
-
146
-		return $field;
147
-	}
148
-
149
-	/**
150
-	 * Get an attribute from a model
151
-	 *
152
-	 * @param object $model     The model
153
-	 * @param string $attribute The attribute's name
154
-	 * @param string $fallback  Fallback value
155
-	 *
156
-	 * @return mixed
157
-	 */
158
-	public function getAttributeFromModel($model, $attribute, $fallback)
159
-	{
160
-		if ($model instanceof Model) {
161
-			// Return fallback if attribute is null
162
-			$value = $model->getAttribute($attribute);
163
-			return is_null($value) ? $fallback : $value;
164
-		}
165
-
166
-		if ($model instanceof Collection) {
167
-			return $model->get($attribute, $fallback);
168
-		}
169
-
170
-		if (is_object($model) && method_exists($model, 'toArray')) {
171
-			$model = $model->toArray();
172
-		} else {
173
-			$model = (array) $model;
174
-		}
175
-		if (array_key_exists($attribute, $model)) {
176
-			return $model[$attribute];
177
-		}
178
-
179
-		return $fallback;
180
-	}
14
+    /**
15
+     * Create a new collection.
16
+     *
17
+     * @param  array|Model $items
18
+     *
19
+     * @return void
20
+     */
21
+    public function __construct($items = array())
22
+    {
23
+        $this->items = $items;
24
+    }
25
+
26
+    ////////////////////////////////////////////////////////////////////
27
+    ///////////////////////// INDIVIDUAL VALUES ////////////////////////
28
+    ////////////////////////////////////////////////////////////////////
29
+
30
+    /**
31
+     * Get the value of a field
32
+     *
33
+     * @param string $field The field's name
34
+     *
35
+     * @return mixed
36
+     */
37
+    public function get($field, $fallback = null)
38
+    {
39
+        // Anonymous fields should not return any value
40
+        if ($field == null) {
41
+            return null;
42
+        }
43
+
44
+        // Plain array
45
+        if (is_array($this->items) and !Str::contains($field, '[')) {
46
+            return parent::get($field, $fallback);
47
+        }
48
+
49
+        // Transform the name into an array
50
+        $value = $this->items;
51
+        $field = $this->parseFieldAsArray($field);
52
+
53
+        // Dive into the model
54
+        foreach ($field as $relationship) {
55
+
56
+            // Get attribute from model
57
+            if (!is_array($value)) {
58
+                $value = $this->getAttributeFromModel($value, $relationship, $fallback);
59
+
60
+                continue;
61
+            }
62
+
63
+            // Get attribute from model
64
+            if (array_key_exists($relationship, $value)) {
65
+                $value = $value[$relationship];
66
+            } else {
67
+                // Check array for submodels that may contain the relationship
68
+                $inSubmodel = false;
69
+
70
+                foreach ($value as $key => $submodel) {
71
+                    $value[$key] = $this->getAttributeFromModel($submodel, $relationship, $fallback);
72
+
73
+                    if ($value[$key] !== $fallback) {
74
+                        $inSubmodel = true;
75
+                    }
76
+                }
77
+
78
+                // If no submodels contained the relationship, return the fallback, not an array of fallbacks
79
+                if (!$inSubmodel) {
80
+                    $value = $fallback;
81
+                    break;
82
+                }
83
+            }
84
+        }
85
+
86
+        return $value;
87
+    }
88
+
89
+    ////////////////////////////////////////////////////////////////////
90
+    ///////////////////////////// SWAPPERS /////////////////////////////
91
+    ////////////////////////////////////////////////////////////////////
92
+
93
+    /**
94
+     * Replace the items
95
+     *
96
+     * @param  mixed $items
97
+     *
98
+     * @return void
99
+     */
100
+    public function replace($items)
101
+    {
102
+        $this->items = $items;
103
+    }
104
+
105
+    /**
106
+     * Reset the current values array
107
+     *
108
+     * @return void
109
+     */
110
+    public function reset()
111
+    {
112
+        $this->items = array();
113
+    }
114
+
115
+    ////////////////////////////////////////////////////////////////////
116
+    ////////////////////////////// HELPERS /////////////////////////////
117
+    ////////////////////////////////////////////////////////////////////
118
+
119
+    /**
120
+     * Parses the name of a field to a tree of fields
121
+     *
122
+     * @param string $field The field's name
123
+     *
124
+     * @return array A tree of field
125
+     */
126
+    protected function parseFieldAsArray($field)
127
+    {
128
+        if (Str::contains($field, '[]')) {
129
+            return (array) $field;
130
+        }
131
+
132
+        // Transform array notation to dot notation
133
+        if (Str::contains($field, '[')) {
134
+            $field = preg_replace("/[\[\]]/", '.', $field);
135
+            $field = str_replace('..', '.', $field);
136
+            $field = trim($field, '.');
137
+        }
138
+
139
+        // Parse dot notation
140
+        if (Str::contains($field, '.')) {
141
+            $field = explode('.', $field);
142
+        } else {
143
+            $field = (array) $field;
144
+        }
145
+
146
+        return $field;
147
+    }
148
+
149
+    /**
150
+     * Get an attribute from a model
151
+     *
152
+     * @param object $model     The model
153
+     * @param string $attribute The attribute's name
154
+     * @param string $fallback  Fallback value
155
+     *
156
+     * @return mixed
157
+     */
158
+    public function getAttributeFromModel($model, $attribute, $fallback)
159
+    {
160
+        if ($model instanceof Model) {
161
+            // Return fallback if attribute is null
162
+            $value = $model->getAttribute($attribute);
163
+            return is_null($value) ? $fallback : $value;
164
+        }
165
+
166
+        if ($model instanceof Collection) {
167
+            return $model->get($attribute, $fallback);
168
+        }
169
+
170
+        if (is_object($model) && method_exists($model, 'toArray')) {
171
+            $model = $model->toArray();
172
+        } else {
173
+            $model = (array) $model;
174
+        }
175
+        if (array_key_exists($attribute, $model)) {
176
+            return $model[$attribute];
177
+        }
178
+
179
+        return $fallback;
180
+    }
181 181
 }
Please login to merge, or discard this patch.