Completed
Push — master ( 4f8f5b...7f2e84 )
by Ben
16s
created
src/Former/Framework/ZurbFoundation.php 1 patch
Indentation   +270 added lines, -270 removed lines patch added patch discarded remove patch
@@ -13,274 +13,274 @@
 block discarded – undo
13 13
  */
14 14
 class ZurbFoundation 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');
22
-
23
-	/**
24
-	 * The field sizes available
25
-	 *
26
-	 * @var array
27
-	 */
28
-	private $fields = array(
29
-		1  => 'one',
30
-		2  => 'two',
31
-		3  => 'three',
32
-		4  => 'four',
33
-		5  => 'five',
34
-		6  => 'six',
35
-		7  => 'seven',
36
-		8  => 'eight',
37
-		9  => 'nine',
38
-		10 => 'ten',
39
-		11 => 'eleven',
40
-		12 => 'twelve',
41
-	);
42
-
43
-	/**
44
-	 * The field states available
45
-	 *
46
-	 * @var array
47
-	 */
48
-	protected $states = array(
49
-		'error',
50
-	);
51
-
52
-	/**
53
-	 * Create a new ZurbFoundation instance
54
-	 *
55
-	 * @param Container $app
56
-	 */
57
-	public function __construct(Container $app)
58
-	{
59
-		$this->app = $app;
60
-		$this->setFrameworkDefaults();
61
-	}
62
-
63
-	////////////////////////////////////////////////////////////////////
64
-	/////////////////////////// FILTER ARRAYS //////////////////////////
65
-	////////////////////////////////////////////////////////////////////
66
-
67
-	public function filterButtonClasses($classes)
68
-	{
69
-		return $classes;
70
-	}
71
-
72
-	public function filterFieldClasses($classes)
73
-	{
74
-		// Filter classes
75
-		$classes = array_intersect($classes, $this->fields);
76
-
77
-		return $classes;
78
-	}
79
-
80
-	////////////////////////////////////////////////////////////////////
81
-	///////////////////// EXPOSE FRAMEWORK SPECIFICS ///////////////////
82
-	////////////////////////////////////////////////////////////////////
83
-
84
-	protected function setFieldWidths($labelWidths)
85
-	{
86
-		$labelWidthClass = $fieldWidthClass = $fieldOffsetClass = '';
87
-
88
-		$viewports = $this->getFrameworkOption('viewports');
89
-
90
-		foreach ($labelWidths as $viewport => $columns) {
91
-			if ($viewport) {
92
-				$labelWidthClass .= $viewports[$viewport].$this->fields[$columns].' ';
93
-				$fieldWidthClass .= $viewports[$viewport].$this->fields[12 - $columns].' ';
94
-				$fieldOffsetClass .= $viewports[$viewport].'offset-by-'.$this->fields[$columns].' ';
95
-			}
96
-		}
97
-
98
-		$this->labelWidth  = $labelWidthClass.'columns';
99
-		$this->fieldWidth  = $fieldWidthClass.'columns';
100
-		$this->fieldOffset = $fieldOffsetClass.'columns';
101
-	}
102
-
103
-	////////////////////////////////////////////////////////////////////
104
-	///////////////////////////// ADD CLASSES //////////////////////////
105
-	////////////////////////////////////////////////////////////////////
106
-
107
-	public function getFieldClasses(Field $field, $classes = array())
108
-	{
109
-		$classes = $this->filterFieldClasses($classes);
110
-
111
-		return $this->addClassesToField($field, $classes);
112
-	}
113
-
114
-	public function getGroupClasses()
115
-	{
116
-		if ($this->app['former.form']->isOfType('horizontal')) {
117
-			return 'row';
118
-		} else {
119
-			return null;
120
-		}
121
-	}
122
-
123
-	/**
124
-	 * Add label classes
125
-	 *
126
-	 * @return string|null An array of attributes with the label class
127
-	 */
128
-	public function getLabelClasses()
129
-	{
130
-		if ($this->app['former.form']->isOfType('horizontal')) {
131
-			return $this->getFrameworkOption('wrappedLabelClasses');
132
-		} else {
133
-			return null;
134
-		}
135
-	}
136
-
137
-	public function getUneditableClasses()
138
-	{
139
-		return null;
140
-	}
141
-
142
-	public function getPlainTextClasses()
143
-	{
144
-		return null;
145
-	}
146
-
147
-	public function getFormClasses($type)
148
-	{
149
-		return null;
150
-	}
151
-
152
-	public function getActionClasses()
153
-	{
154
-		return null;
155
-	}
156
-
157
-	////////////////////////////////////////////////////////////////////
158
-	//////////////////////////// RENDER BLOCKS /////////////////////////
159
-	////////////////////////////////////////////////////////////////////
160
-
161
-	public function createHelp($text, $attributes = null)
162
-	{
163
-		if (is_null($attributes) or empty($attributes)) {
164
-			$attributes = $this->getFrameworkOption('error_classes');
165
-		}
166
-
167
-		return Element::create('span', $text, $attributes);
168
-	}
169
-
170
-	/**
171
-	 * Render a disabled field
172
-	 *
173
-	 * @param Field $field
174
-	 *
175
-	 * @return Input
176
-	 */
177
-	public function createDisabledField(Field $field)
178
-	{
179
-		$field->disabled();
180
-
181
-		return Input::create('text', $field->getName(), $field->getValue(), $field->getAttributes());
182
-	}
183
-
184
-	/**
185
-	 * Render a plain text field
186
-	 * Which fallback to a disabled field
187
-	 *
188
-	 * @param Field $field
189
-	 *
190
-	 * @return Element
191
-	 */
192
-	public function createPlainTextField(Field $field)
193
-	{
194
-		return $this->createDisabledField($field);
195
-	}
196
-
197
-	////////////////////////////////////////////////////////////////////
198
-	//////////////////////////// WRAP BLOCKS ///////////////////////////
199
-	////////////////////////////////////////////////////////////////////
200
-
201
-	/**
202
-	 * Wrap an item to be prepended or appended to the current field.
203
-	 * For Zurb we return the item and handle the wrapping in prependAppend
204
-	 * as wrapping is dependent on whether we're prepending or appending.
205
-	 *
206
-	 * @return string A wrapped item
207
-	 */
208
-	public function placeAround($item)
209
-	{
210
-		return $item;
211
-	}
212
-
213
-	/**
214
-	 * Wrap a field with prepended and appended items
215
-	 *
216
-	 * @param  Field $field
217
-	 * @param  array $prepend
218
-	 * @param  array $append
219
-	 *
220
-	 * @return string A field concatented with prepended and/or appended items
221
-	 */
222
-	public function prependAppend($field, $prepend, $append)
223
-	{
224
-		$return = '';
225
-
226
-		foreach ($prepend as $item) {
227
-			$return .= '<div class="two mobile-one columns"><span class="prefix">'.$item.'</span></div>';
228
-		}
229
-
230
-		$return .= '<div class="ten mobile-three columns">'.$field->render().'</div>';
231
-
232
-		foreach ($append as $item) {
233
-			$return .= '<div class="two mobile-one columns"><span class="postfix">'.$item.'</span></div>';
234
-		}
235
-
236
-		return $return;
237
-	}
238
-
239
-	/**
240
-	 * Wraps all label contents with potential additional tags.
241
-	 *
242
-	 * @param  string $label
243
-	 *
244
-	 * @return string A wrapped label
245
-	 */
246
-	public function wrapLabel($label)
247
-	{
248
-		if ($this->app['former.form']->isOfType('horizontal')) {
249
-			return Element::create('div', $label)->addClass($this->labelWidth);
250
-		} else {
251
-			return $label;
252
-		}
253
-	}
254
-
255
-	/**
256
-	 * Wraps all field contents with potential additional tags.
257
-	 *
258
-	 * @param  Field $field
259
-	 *
260
-	 * @return Element A wrapped field
261
-	 */
262
-	public function wrapField($field)
263
-	{
264
-		if ($this->app['former.form']->isOfType('horizontal')) {
265
-			return Element::create('div', $field)->addClass($this->fieldWidth);
266
-		} else {
267
-			return $field;
268
-		}
269
-	}
270
-
271
-	/**
272
-	 * Wrap actions block with potential additional tags
273
-	 *
274
-	 * @param  Actions $actions
275
-	 *
276
-	 * @return string A wrapped actions block
277
-	 */
278
-	public function wrapActions($actions)
279
-	{
280
-		if ($this->app['former.form']->isOfType('horizontal')) {
281
-			return Element::create('div', $actions)->addClass(array($this->fieldOffset, $this->fieldWidth));
282
-		} else {
283
-			return $actions;
284
-		}
285
-	}
16
+    /**
17
+     * Form types that trigger special styling for this Framework
18
+     *
19
+     * @var array
20
+     */
21
+    protected $availableTypes = array('horizontal', 'vertical');
22
+
23
+    /**
24
+     * The field sizes available
25
+     *
26
+     * @var array
27
+     */
28
+    private $fields = array(
29
+        1  => 'one',
30
+        2  => 'two',
31
+        3  => 'three',
32
+        4  => 'four',
33
+        5  => 'five',
34
+        6  => 'six',
35
+        7  => 'seven',
36
+        8  => 'eight',
37
+        9  => 'nine',
38
+        10 => 'ten',
39
+        11 => 'eleven',
40
+        12 => 'twelve',
41
+    );
42
+
43
+    /**
44
+     * The field states available
45
+     *
46
+     * @var array
47
+     */
48
+    protected $states = array(
49
+        'error',
50
+    );
51
+
52
+    /**
53
+     * Create a new ZurbFoundation instance
54
+     *
55
+     * @param Container $app
56
+     */
57
+    public function __construct(Container $app)
58
+    {
59
+        $this->app = $app;
60
+        $this->setFrameworkDefaults();
61
+    }
62
+
63
+    ////////////////////////////////////////////////////////////////////
64
+    /////////////////////////// FILTER ARRAYS //////////////////////////
65
+    ////////////////////////////////////////////////////////////////////
66
+
67
+    public function filterButtonClasses($classes)
68
+    {
69
+        return $classes;
70
+    }
71
+
72
+    public function filterFieldClasses($classes)
73
+    {
74
+        // Filter classes
75
+        $classes = array_intersect($classes, $this->fields);
76
+
77
+        return $classes;
78
+    }
79
+
80
+    ////////////////////////////////////////////////////////////////////
81
+    ///////////////////// EXPOSE FRAMEWORK SPECIFICS ///////////////////
82
+    ////////////////////////////////////////////////////////////////////
83
+
84
+    protected function setFieldWidths($labelWidths)
85
+    {
86
+        $labelWidthClass = $fieldWidthClass = $fieldOffsetClass = '';
87
+
88
+        $viewports = $this->getFrameworkOption('viewports');
89
+
90
+        foreach ($labelWidths as $viewport => $columns) {
91
+            if ($viewport) {
92
+                $labelWidthClass .= $viewports[$viewport].$this->fields[$columns].' ';
93
+                $fieldWidthClass .= $viewports[$viewport].$this->fields[12 - $columns].' ';
94
+                $fieldOffsetClass .= $viewports[$viewport].'offset-by-'.$this->fields[$columns].' ';
95
+            }
96
+        }
97
+
98
+        $this->labelWidth  = $labelWidthClass.'columns';
99
+        $this->fieldWidth  = $fieldWidthClass.'columns';
100
+        $this->fieldOffset = $fieldOffsetClass.'columns';
101
+    }
102
+
103
+    ////////////////////////////////////////////////////////////////////
104
+    ///////////////////////////// ADD CLASSES //////////////////////////
105
+    ////////////////////////////////////////////////////////////////////
106
+
107
+    public function getFieldClasses(Field $field, $classes = array())
108
+    {
109
+        $classes = $this->filterFieldClasses($classes);
110
+
111
+        return $this->addClassesToField($field, $classes);
112
+    }
113
+
114
+    public function getGroupClasses()
115
+    {
116
+        if ($this->app['former.form']->isOfType('horizontal')) {
117
+            return 'row';
118
+        } else {
119
+            return null;
120
+        }
121
+    }
122
+
123
+    /**
124
+     * Add label classes
125
+     *
126
+     * @return string|null An array of attributes with the label class
127
+     */
128
+    public function getLabelClasses()
129
+    {
130
+        if ($this->app['former.form']->isOfType('horizontal')) {
131
+            return $this->getFrameworkOption('wrappedLabelClasses');
132
+        } else {
133
+            return null;
134
+        }
135
+    }
136
+
137
+    public function getUneditableClasses()
138
+    {
139
+        return null;
140
+    }
141
+
142
+    public function getPlainTextClasses()
143
+    {
144
+        return null;
145
+    }
146
+
147
+    public function getFormClasses($type)
148
+    {
149
+        return null;
150
+    }
151
+
152
+    public function getActionClasses()
153
+    {
154
+        return null;
155
+    }
156
+
157
+    ////////////////////////////////////////////////////////////////////
158
+    //////////////////////////// RENDER BLOCKS /////////////////////////
159
+    ////////////////////////////////////////////////////////////////////
160
+
161
+    public function createHelp($text, $attributes = null)
162
+    {
163
+        if (is_null($attributes) or empty($attributes)) {
164
+            $attributes = $this->getFrameworkOption('error_classes');
165
+        }
166
+
167
+        return Element::create('span', $text, $attributes);
168
+    }
169
+
170
+    /**
171
+     * Render a disabled field
172
+     *
173
+     * @param Field $field
174
+     *
175
+     * @return Input
176
+     */
177
+    public function createDisabledField(Field $field)
178
+    {
179
+        $field->disabled();
180
+
181
+        return Input::create('text', $field->getName(), $field->getValue(), $field->getAttributes());
182
+    }
183
+
184
+    /**
185
+     * Render a plain text field
186
+     * Which fallback to a disabled field
187
+     *
188
+     * @param Field $field
189
+     *
190
+     * @return Element
191
+     */
192
+    public function createPlainTextField(Field $field)
193
+    {
194
+        return $this->createDisabledField($field);
195
+    }
196
+
197
+    ////////////////////////////////////////////////////////////////////
198
+    //////////////////////////// WRAP BLOCKS ///////////////////////////
199
+    ////////////////////////////////////////////////////////////////////
200
+
201
+    /**
202
+     * Wrap an item to be prepended or appended to the current field.
203
+     * For Zurb we return the item and handle the wrapping in prependAppend
204
+     * as wrapping is dependent on whether we're prepending or appending.
205
+     *
206
+     * @return string A wrapped item
207
+     */
208
+    public function placeAround($item)
209
+    {
210
+        return $item;
211
+    }
212
+
213
+    /**
214
+     * Wrap a field with prepended and appended items
215
+     *
216
+     * @param  Field $field
217
+     * @param  array $prepend
218
+     * @param  array $append
219
+     *
220
+     * @return string A field concatented with prepended and/or appended items
221
+     */
222
+    public function prependAppend($field, $prepend, $append)
223
+    {
224
+        $return = '';
225
+
226
+        foreach ($prepend as $item) {
227
+            $return .= '<div class="two mobile-one columns"><span class="prefix">'.$item.'</span></div>';
228
+        }
229
+
230
+        $return .= '<div class="ten mobile-three columns">'.$field->render().'</div>';
231
+
232
+        foreach ($append as $item) {
233
+            $return .= '<div class="two mobile-one columns"><span class="postfix">'.$item.'</span></div>';
234
+        }
235
+
236
+        return $return;
237
+    }
238
+
239
+    /**
240
+     * Wraps all label contents with potential additional tags.
241
+     *
242
+     * @param  string $label
243
+     *
244
+     * @return string A wrapped label
245
+     */
246
+    public function wrapLabel($label)
247
+    {
248
+        if ($this->app['former.form']->isOfType('horizontal')) {
249
+            return Element::create('div', $label)->addClass($this->labelWidth);
250
+        } else {
251
+            return $label;
252
+        }
253
+    }
254
+
255
+    /**
256
+     * Wraps all field contents with potential additional tags.
257
+     *
258
+     * @param  Field $field
259
+     *
260
+     * @return Element A wrapped field
261
+     */
262
+    public function wrapField($field)
263
+    {
264
+        if ($this->app['former.form']->isOfType('horizontal')) {
265
+            return Element::create('div', $field)->addClass($this->fieldWidth);
266
+        } else {
267
+            return $field;
268
+        }
269
+    }
270
+
271
+    /**
272
+     * Wrap actions block with potential additional tags
273
+     *
274
+     * @param  Actions $actions
275
+     *
276
+     * @return string A wrapped actions block
277
+     */
278
+    public function wrapActions($actions)
279
+    {
280
+        if ($this->app['former.form']->isOfType('horizontal')) {
281
+            return Element::create('div', $actions)->addClass(array($this->fieldOffset, $this->fieldWidth));
282
+        } else {
283
+            return $actions;
284
+        }
285
+    }
286 286
 }
Please login to merge, or discard this patch.
src/Former/Framework/ZurbFoundation4.php 1 patch
Indentation   +277 added lines, -277 removed lines patch added patch discarded remove patch
@@ -13,281 +13,281 @@
 block discarded – undo
13 13
  */
14 14
 class ZurbFoundation4 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');
22
-
23
-	/**
24
-	 * The button types available
25
-	 *
26
-	 * @var array
27
-	 */
28
-	private $buttons = array(
29
-		'tiny',
30
-		'small',
31
-		'medium',
32
-		'large',
33
-		'success',
34
-		'radius',
35
-		'round',
36
-		'disabled',
37
-		'prefix',
38
-		'postfix',
39
-	);
40
-
41
-	/**
42
-	 * The field sizes available
43
-	 * Zurb Foundation 4 does not apply sizes to the form element, but to the wrapper div
44
-	 *
45
-	 * @var array
46
-	 */
47
-	private $fields = array();
48
-
49
-	/**
50
-	 * The field states available
51
-	 *
52
-	 * @var array
53
-	 */
54
-	protected $states = array(
55
-		'error',
56
-	);
57
-
58
-	/**
59
-	 * Create a new ZurbFoundation instance
60
-	 *
61
-	 * @param \Illuminate\Container\Container $app
62
-	 */
63
-	public function __construct(Container $app)
64
-	{
65
-		$this->app = $app;
66
-		$this->setFrameworkDefaults();
67
-	}
68
-
69
-	////////////////////////////////////////////////////////////////////
70
-	/////////////////////////// FILTER ARRAYS //////////////////////////
71
-	////////////////////////////////////////////////////////////////////
72
-
73
-	public function filterButtonClasses($classes)
74
-	{
75
-		// Filter classes
76
-		$classes   = array_intersect($classes, $this->buttons);
77
-		$classes[] = 'button';
78
-
79
-		return $classes;
80
-	}
81
-
82
-	public function filterFieldClasses($classes)
83
-	{
84
-		return null;
85
-	}
86
-
87
-	////////////////////////////////////////////////////////////////////
88
-	///////////////////// EXPOSE FRAMEWORK SPECIFICS ///////////////////
89
-	////////////////////////////////////////////////////////////////////
90
-
91
-	protected function setFieldWidths($labelWidths)
92
-	{
93
-		$labelWidthClass = $fieldWidthClass = $fieldOffsetClass = '';
94
-
95
-		$viewports = $this->getFrameworkOption('viewports');
96
-
97
-		foreach ($labelWidths as $viewport => $columns) {
98
-			if ($viewport) {
99
-				$labelWidthClass .= $viewports[$viewport].'-'.$columns.' ';
100
-				$fieldWidthClass .= $viewports[$viewport].'-'.(12 - $columns).' ';
101
-				$fieldOffsetClass .= $viewports[$viewport].'-offset-'.$columns.' ';
102
-			}
103
-		}
104
-
105
-		$this->labelWidth  = $labelWidthClass.'columns';
106
-		$this->fieldWidth  = $fieldWidthClass.'columns';
107
-		$this->fieldOffset = $fieldOffsetClass.'columns';
108
-	}
109
-
110
-	////////////////////////////////////////////////////////////////////
111
-	///////////////////////////// ADD CLASSES //////////////////////////
112
-	////////////////////////////////////////////////////////////////////
113
-
114
-	public function getFieldClasses(Field $field, $classes = array())
115
-	{
116
-		if ($field->isButton()) {
117
-			$classes = $this->filterButtonClasses($classes);
118
-		} else {
119
-			$classes = $this->filterFieldClasses($classes);
120
-		}
121
-
122
-		return $this->addClassesToField($field, $classes);
123
-	}
124
-
125
-	public function getGroupClasses()
126
-	{
127
-		if ($this->app['former.form']->isOfType('horizontal')) {
128
-			return 'row';
129
-		} else {
130
-			return null;
131
-		}
132
-	}
133
-
134
-	/**
135
-	 * Add label classes
136
-	 *
137
-	 * @return string|null An array of attributes with the label class
138
-	 */
139
-	public function getLabelClasses()
140
-	{
141
-		if ($this->app['former.form']->isOfType('horizontal')) {
142
-			return $this->getFrameworkOption('wrappedLabelClasses');
143
-		} else {
144
-			return null;
145
-		}
146
-	}
147
-
148
-	public function getUneditableClasses()
149
-	{
150
-		return null;
151
-	}
152
-
153
-	public function getPlainTextClasses()
154
-	{
155
-		return null;
156
-	}
157
-
158
-	public function getFormClasses($type)
159
-	{
160
-		return null;
161
-	}
162
-
163
-	public function getActionClasses()
164
-	{
165
-		return null;
166
-	}
167
-
168
-	////////////////////////////////////////////////////////////////////
169
-	//////////////////////////// RENDER BLOCKS /////////////////////////
170
-	////////////////////////////////////////////////////////////////////
171
-
172
-	public function createHelp($text, $attributes = null)
173
-	{
174
-		if (is_null($attributes) or empty($attributes)) {
175
-			$attributes = $this->getFrameworkOption('error_classes');
176
-		}
177
-
178
-		return Element::create('span', $text, $attributes);
179
-	}
180
-
181
-	/**
182
-	 * Render a disabled field
183
-	 *
184
-	 * @param Field $field
185
-	 *
186
-	 * @return Input
187
-	 */
188
-	public function createDisabledField(Field $field)
189
-	{
190
-		$field->disabled();
191
-
192
-		return Input::create('text', $field->getName(), $field->getValue(), $field->getAttributes());
193
-	}
194
-
195
-	/**
196
-	 * Render a plain text field
197
-	 * Which fallback to a disabled field
198
-	 *
199
-	 * @param Field $field
200
-	 *
201
-	 * @return Element
202
-	 */
203
-	public function createPlainTextField(Field $field)
204
-	{
205
-		return $this->createDisabledField($field);
206
-	}
207
-
208
-	////////////////////////////////////////////////////////////////////
209
-	//////////////////////////// WRAP BLOCKS ///////////////////////////
210
-	////////////////////////////////////////////////////////////////////
211
-
212
-	/**
213
-	 * Wrap an item to be prepended or appended to the current field.
214
-	 * For Zurb we return the item and handle the wrapping in prependAppend
215
-	 * as wrapping is dependent on whether we're prepending or appending.
216
-	 *
217
-	 * @return string A wrapped item
218
-	 */
219
-	public function placeAround($item)
220
-	{
221
-		return $item;
222
-	}
223
-
224
-	/**
225
-	 * Wrap a field with prepended and appended items
226
-	 *
227
-	 * @param  Field $field
228
-	 * @param  array $prepend
229
-	 * @param  array $append
230
-	 *
231
-	 * @return string A field concatented with prepended and/or appended items
232
-	 */
233
-	public function prependAppend($field, $prepend, $append)
234
-	{
235
-		$return = '';
236
-
237
-		foreach ($prepend as $item) {
238
-			$return .= '<div class="large-2 small-3 columns"><span class="prefix">'.$item.'</span></div>';
239
-		}
240
-
241
-		$return .= '<div class="large-10 small-9 columns">'.$field->render().'</div>';
242
-
243
-		foreach ($append as $item) {
244
-			$return .= '<div class="large-2 small-3 columns"><span class="postfix">'.$item.'</span></div>';
245
-		}
246
-
247
-		return $return;
248
-	}
249
-
250
-	/**
251
-	 * Wraps all label contents with potential additional tags.
252
-	 *
253
-	 * @param  string $label
254
-	 *
255
-	 * @return string A wrapped label
256
-	 */
257
-	public function wrapLabel($label)
258
-	{
259
-		if ($this->app['former.form']->isOfType('horizontal')) {
260
-			return Element::create('div', $label)->addClass($this->labelWidth);
261
-		} else {
262
-			return $label;
263
-		}
264
-	}
265
-
266
-	/**
267
-	 * Wraps all field contents with potential additional tags.
268
-	 *
269
-	 * @param  Field $field
270
-	 *
271
-	 * @return Element A wrapped field
272
-	 */
273
-	public function wrapField($field)
274
-	{
275
-		if ($this->app['former.form']->isOfType('horizontal')) {
276
-			return Element::create('div', $field)->addClass($this->fieldWidth);
277
-		} else {
278
-			return $field;
279
-		}
280
-	}
281
-
282
-	/**
283
-	 * Wrap actions block with potential additional tags
284
-	 *
285
-	 * @param  Actions $actions
286
-	 *
287
-	 * @return string A wrapped actions block
288
-	 */
289
-	public function wrapActions($actions)
290
-	{
291
-		return $actions;
292
-	}
16
+    /**
17
+     * Form types that trigger special styling for this Framework
18
+     *
19
+     * @var array
20
+     */
21
+    protected $availableTypes = array('horizontal', 'vertical');
22
+
23
+    /**
24
+     * The button types available
25
+     *
26
+     * @var array
27
+     */
28
+    private $buttons = array(
29
+        'tiny',
30
+        'small',
31
+        'medium',
32
+        'large',
33
+        'success',
34
+        'radius',
35
+        'round',
36
+        'disabled',
37
+        'prefix',
38
+        'postfix',
39
+    );
40
+
41
+    /**
42
+     * The field sizes available
43
+     * Zurb Foundation 4 does not apply sizes to the form element, but to the wrapper div
44
+     *
45
+     * @var array
46
+     */
47
+    private $fields = array();
48
+
49
+    /**
50
+     * The field states available
51
+     *
52
+     * @var array
53
+     */
54
+    protected $states = array(
55
+        'error',
56
+    );
57
+
58
+    /**
59
+     * Create a new ZurbFoundation instance
60
+     *
61
+     * @param \Illuminate\Container\Container $app
62
+     */
63
+    public function __construct(Container $app)
64
+    {
65
+        $this->app = $app;
66
+        $this->setFrameworkDefaults();
67
+    }
68
+
69
+    ////////////////////////////////////////////////////////////////////
70
+    /////////////////////////// FILTER ARRAYS //////////////////////////
71
+    ////////////////////////////////////////////////////////////////////
72
+
73
+    public function filterButtonClasses($classes)
74
+    {
75
+        // Filter classes
76
+        $classes   = array_intersect($classes, $this->buttons);
77
+        $classes[] = 'button';
78
+
79
+        return $classes;
80
+    }
81
+
82
+    public function filterFieldClasses($classes)
83
+    {
84
+        return null;
85
+    }
86
+
87
+    ////////////////////////////////////////////////////////////////////
88
+    ///////////////////// EXPOSE FRAMEWORK SPECIFICS ///////////////////
89
+    ////////////////////////////////////////////////////////////////////
90
+
91
+    protected function setFieldWidths($labelWidths)
92
+    {
93
+        $labelWidthClass = $fieldWidthClass = $fieldOffsetClass = '';
94
+
95
+        $viewports = $this->getFrameworkOption('viewports');
96
+
97
+        foreach ($labelWidths as $viewport => $columns) {
98
+            if ($viewport) {
99
+                $labelWidthClass .= $viewports[$viewport].'-'.$columns.' ';
100
+                $fieldWidthClass .= $viewports[$viewport].'-'.(12 - $columns).' ';
101
+                $fieldOffsetClass .= $viewports[$viewport].'-offset-'.$columns.' ';
102
+            }
103
+        }
104
+
105
+        $this->labelWidth  = $labelWidthClass.'columns';
106
+        $this->fieldWidth  = $fieldWidthClass.'columns';
107
+        $this->fieldOffset = $fieldOffsetClass.'columns';
108
+    }
109
+
110
+    ////////////////////////////////////////////////////////////////////
111
+    ///////////////////////////// ADD CLASSES //////////////////////////
112
+    ////////////////////////////////////////////////////////////////////
113
+
114
+    public function getFieldClasses(Field $field, $classes = array())
115
+    {
116
+        if ($field->isButton()) {
117
+            $classes = $this->filterButtonClasses($classes);
118
+        } else {
119
+            $classes = $this->filterFieldClasses($classes);
120
+        }
121
+
122
+        return $this->addClassesToField($field, $classes);
123
+    }
124
+
125
+    public function getGroupClasses()
126
+    {
127
+        if ($this->app['former.form']->isOfType('horizontal')) {
128
+            return 'row';
129
+        } else {
130
+            return null;
131
+        }
132
+    }
133
+
134
+    /**
135
+     * Add label classes
136
+     *
137
+     * @return string|null An array of attributes with the label class
138
+     */
139
+    public function getLabelClasses()
140
+    {
141
+        if ($this->app['former.form']->isOfType('horizontal')) {
142
+            return $this->getFrameworkOption('wrappedLabelClasses');
143
+        } else {
144
+            return null;
145
+        }
146
+    }
147
+
148
+    public function getUneditableClasses()
149
+    {
150
+        return null;
151
+    }
152
+
153
+    public function getPlainTextClasses()
154
+    {
155
+        return null;
156
+    }
157
+
158
+    public function getFormClasses($type)
159
+    {
160
+        return null;
161
+    }
162
+
163
+    public function getActionClasses()
164
+    {
165
+        return null;
166
+    }
167
+
168
+    ////////////////////////////////////////////////////////////////////
169
+    //////////////////////////// RENDER BLOCKS /////////////////////////
170
+    ////////////////////////////////////////////////////////////////////
171
+
172
+    public function createHelp($text, $attributes = null)
173
+    {
174
+        if (is_null($attributes) or empty($attributes)) {
175
+            $attributes = $this->getFrameworkOption('error_classes');
176
+        }
177
+
178
+        return Element::create('span', $text, $attributes);
179
+    }
180
+
181
+    /**
182
+     * Render a disabled field
183
+     *
184
+     * @param Field $field
185
+     *
186
+     * @return Input
187
+     */
188
+    public function createDisabledField(Field $field)
189
+    {
190
+        $field->disabled();
191
+
192
+        return Input::create('text', $field->getName(), $field->getValue(), $field->getAttributes());
193
+    }
194
+
195
+    /**
196
+     * Render a plain text field
197
+     * Which fallback to a disabled field
198
+     *
199
+     * @param Field $field
200
+     *
201
+     * @return Element
202
+     */
203
+    public function createPlainTextField(Field $field)
204
+    {
205
+        return $this->createDisabledField($field);
206
+    }
207
+
208
+    ////////////////////////////////////////////////////////////////////
209
+    //////////////////////////// WRAP BLOCKS ///////////////////////////
210
+    ////////////////////////////////////////////////////////////////////
211
+
212
+    /**
213
+     * Wrap an item to be prepended or appended to the current field.
214
+     * For Zurb we return the item and handle the wrapping in prependAppend
215
+     * as wrapping is dependent on whether we're prepending or appending.
216
+     *
217
+     * @return string A wrapped item
218
+     */
219
+    public function placeAround($item)
220
+    {
221
+        return $item;
222
+    }
223
+
224
+    /**
225
+     * Wrap a field with prepended and appended items
226
+     *
227
+     * @param  Field $field
228
+     * @param  array $prepend
229
+     * @param  array $append
230
+     *
231
+     * @return string A field concatented with prepended and/or appended items
232
+     */
233
+    public function prependAppend($field, $prepend, $append)
234
+    {
235
+        $return = '';
236
+
237
+        foreach ($prepend as $item) {
238
+            $return .= '<div class="large-2 small-3 columns"><span class="prefix">'.$item.'</span></div>';
239
+        }
240
+
241
+        $return .= '<div class="large-10 small-9 columns">'.$field->render().'</div>';
242
+
243
+        foreach ($append as $item) {
244
+            $return .= '<div class="large-2 small-3 columns"><span class="postfix">'.$item.'</span></div>';
245
+        }
246
+
247
+        return $return;
248
+    }
249
+
250
+    /**
251
+     * Wraps all label contents with potential additional tags.
252
+     *
253
+     * @param  string $label
254
+     *
255
+     * @return string A wrapped label
256
+     */
257
+    public function wrapLabel($label)
258
+    {
259
+        if ($this->app['former.form']->isOfType('horizontal')) {
260
+            return Element::create('div', $label)->addClass($this->labelWidth);
261
+        } else {
262
+            return $label;
263
+        }
264
+    }
265
+
266
+    /**
267
+     * Wraps all field contents with potential additional tags.
268
+     *
269
+     * @param  Field $field
270
+     *
271
+     * @return Element A wrapped field
272
+     */
273
+    public function wrapField($field)
274
+    {
275
+        if ($this->app['former.form']->isOfType('horizontal')) {
276
+            return Element::create('div', $field)->addClass($this->fieldWidth);
277
+        } else {
278
+            return $field;
279
+        }
280
+    }
281
+
282
+    /**
283
+     * Wrap actions block with potential additional tags
284
+     *
285
+     * @param  Actions $actions
286
+     *
287
+     * @return string A wrapped actions block
288
+     */
289
+    public function wrapActions($actions)
290
+    {
291
+        return $actions;
292
+    }
293 293
 }
Please login to merge, or discard this patch.
src/Former/Form/Fields/File.php 1 patch
Indentation   +123 added lines, -124 removed lines patch added patch discarded remove patch
@@ -12,128 +12,127 @@
 block discarded – undo
12 12
 class File extends Field
13 13
 {
14 14
 
15
-	/**
16
-	 * The maximum file size
17
-	 *
18
-	 * @var integer
19
-	 */
20
-	private $maxSize;
21
-
22
-	/**
23
-	 * An array of mime groups to use as shortcuts
24
-	 *
25
-	 * @var array
26
-	 */
27
-	private $mimeGroups = array('audio', 'video', 'image');
28
-
29
-	/**
30
-	 * A list of properties to be injected in the attributes
31
-	 *
32
-	 * @var array
33
-	 */
34
-	protected $injectedProperties = array('type', 'name');
35
-
36
-	////////////////////////////////////////////////////////////////////
37
-	/////////////////////////// CORE METHODS ///////////////////////////
38
-	////////////////////////////////////////////////////////////////////
39
-
40
-	/**
41
-	 * Easier arguments order for hidden fields
42
-	 *
43
-	 * @param Container $app        The Illuminate Container
44
-	 * @param string    $type       file
45
-	 * @param string    $name       Field name
46
-	 * @param string    $label      Its label
47
-	 * @param string    $value      Its value
48
-	 * @param array     $attributes Attributes
49
-	 */
50
-	public function __construct(Container $app, $type, $name, $label, $value, $attributes)
51
-	{
52
-		// Multiple files field
53
-		if ($type == 'files') {
54
-			$attributes['multiple'] = 'true';
55
-			$type                   = 'file';
56
-			$name                   = $name.'[]';
57
-		}
58
-
59
-		parent::__construct($app, $type, $name, $label, $value, $attributes);
60
-	}
61
-
62
-	/**
63
-	 * Prints out the current tag
64
-	 *
65
-	 * @return string An input file tag
66
-	 */
67
-	public function render()
68
-	{
69
-		// Maximum file size
70
-		$hidden = $this->maxSize
71
-			? HtmlInput::hidden('MAX_FILE_SIZE', $this->maxSize)
72
-			: null;
73
-
74
-		return $hidden.parent::render();
75
-	}
76
-
77
-	////////////////////////////////////////////////////////////////////
78
-	////////////////////////// FIELD METHODS ///////////////////////////
79
-	////////////////////////////////////////////////////////////////////
80
-
81
-	/**
82
-	 * Set which types of files are accepted by the file input
83
-
84
-	 */
85
-	public function accept()
86
-	{
87
-		$mimes = array();
88
-
89
-		// Transform all extensions/groups to mime types
90
-		foreach (func_get_args() as $mime) {
91
-
92
-			// Shortcuts and extensions
93
-			if (in_array($mime, $this->mimeGroups)) {
94
-				$mime .= '/*';
95
-			}
96
-			$mime = LaravelFile::mime($mime, $mime);
97
-
98
-			$mimes[] = $mime;
99
-		}
100
-
101
-		// Add accept attribute by concatenating the mimes
102
-		$this->attributes['accept'] = implode(',', $mimes);
103
-
104
-		return $this;
105
-	}
106
-
107
-	/**
108
-	 * Set a maximum size for files
109
-	 *
110
-	 * @param integer $size  A maximum size
111
-	 * @param string  $units The size's unit
112
-	 */
113
-	public function max($size, $units = 'KB')
114
-	{
115
-		// Bytes or bits ?
116
-		$unit = substr($units, -1);
117
-		$base = 1024;
118
-		if ($unit == 'b') {
119
-			$size = $size / 8;
120
-		}
121
-
122
-		// Convert
123
-		switch ($units[0]) {
124
-			case 'K':
125
-				$size = $size * $base;
126
-				break;
127
-			case 'M':
128
-				$size = $size * pow($base, 2);
129
-				break;
130
-			case 'G':
131
-				$size = $size * pow($base, 3);
132
-				break;
133
-		}
134
-
135
-		$this->maxSize = (int) $size;
136
-
137
-		return $this;
138
-	}
15
+    /**
16
+     * The maximum file size
17
+     *
18
+     * @var integer
19
+     */
20
+    private $maxSize;
21
+
22
+    /**
23
+     * An array of mime groups to use as shortcuts
24
+     *
25
+     * @var array
26
+     */
27
+    private $mimeGroups = array('audio', 'video', 'image');
28
+
29
+    /**
30
+     * A list of properties to be injected in the attributes
31
+     *
32
+     * @var array
33
+     */
34
+    protected $injectedProperties = array('type', 'name');
35
+
36
+    ////////////////////////////////////////////////////////////////////
37
+    /////////////////////////// CORE METHODS ///////////////////////////
38
+    ////////////////////////////////////////////////////////////////////
39
+
40
+    /**
41
+     * Easier arguments order for hidden fields
42
+     *
43
+     * @param Container $app        The Illuminate Container
44
+     * @param string    $type       file
45
+     * @param string    $name       Field name
46
+     * @param string    $label      Its label
47
+     * @param string    $value      Its value
48
+     * @param array     $attributes Attributes
49
+     */
50
+    public function __construct(Container $app, $type, $name, $label, $value, $attributes)
51
+    {
52
+        // Multiple files field
53
+        if ($type == 'files') {
54
+            $attributes['multiple'] = 'true';
55
+            $type                   = 'file';
56
+            $name                   = $name.'[]';
57
+        }
58
+
59
+        parent::__construct($app, $type, $name, $label, $value, $attributes);
60
+    }
61
+
62
+    /**
63
+     * Prints out the current tag
64
+     *
65
+     * @return string An input file tag
66
+     */
67
+    public function render()
68
+    {
69
+        // Maximum file size
70
+        $hidden = $this->maxSize
71
+            ? HtmlInput::hidden('MAX_FILE_SIZE', $this->maxSize)
72
+            : null;
73
+
74
+        return $hidden.parent::render();
75
+    }
76
+
77
+    ////////////////////////////////////////////////////////////////////
78
+    ////////////////////////// FIELD METHODS ///////////////////////////
79
+    ////////////////////////////////////////////////////////////////////
80
+
81
+    /**
82
+     * Set which types of files are accepted by the file input
83
+     */
84
+    public function accept()
85
+    {
86
+        $mimes = array();
87
+
88
+        // Transform all extensions/groups to mime types
89
+        foreach (func_get_args() as $mime) {
90
+
91
+            // Shortcuts and extensions
92
+            if (in_array($mime, $this->mimeGroups)) {
93
+                $mime .= '/*';
94
+            }
95
+            $mime = LaravelFile::mime($mime, $mime);
96
+
97
+            $mimes[] = $mime;
98
+        }
99
+
100
+        // Add accept attribute by concatenating the mimes
101
+        $this->attributes['accept'] = implode(',', $mimes);
102
+
103
+        return $this;
104
+    }
105
+
106
+    /**
107
+     * Set a maximum size for files
108
+     *
109
+     * @param integer $size  A maximum size
110
+     * @param string  $units The size's unit
111
+     */
112
+    public function max($size, $units = 'KB')
113
+    {
114
+        // Bytes or bits ?
115
+        $unit = substr($units, -1);
116
+        $base = 1024;
117
+        if ($unit == 'b') {
118
+            $size = $size / 8;
119
+        }
120
+
121
+        // Convert
122
+        switch ($units[0]) {
123
+            case 'K':
124
+                $size = $size * $base;
125
+                break;
126
+            case 'M':
127
+                $size = $size * pow($base, 2);
128
+                break;
129
+            case 'G':
130
+                $size = $size * pow($base, 3);
131
+                break;
132
+        }
133
+
134
+        $this->maxSize = (int) $size;
135
+
136
+        return $this;
137
+    }
139 138
 }
Please login to merge, or discard this patch.
src/Former/Traits/Field.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 	 * @param boolean $isRequired
197 197
 	 * @return $this
198 198
 	 */
199
-	public function required($isRequired=true)
199
+	public function required($isRequired = true)
200 200
 	{
201 201
 		if ($isRequired) {
202 202
 			$this->attributes['required'] = true;
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 
293 293
             // If we have a rule with a value
294 294
             if (($colon = strpos($rule, ':')) !== false) {
295
-                $rulename = substr($rule, 0, $colon) ;
295
+                $rulename = substr($rule, 0, $colon);
296 296
 
297 297
                 /**
298 298
                 * Regular expressions may contain commas and should not be divided by str_getcsv.
Please login to merge, or discard this patch.
Indentation   +433 added lines, -433 removed lines patch added patch discarded remove patch
@@ -16,281 +16,281 @@  discard block
 block discarded – undo
16 16
  */
17 17
 abstract class Field extends FormerObject implements FieldInterface
18 18
 {
19
-	/**
20
-	 * The IoC Container
21
-	 *
22
-	 * @var Container
23
-	 */
24
-	protected $app;
25
-
26
-	/**
27
-	 * The Form instance
28
-	 *
29
-	 * @var Former\Form
30
-	 */
31
-	protected $form;
32
-
33
-	/**
34
-	 * A label for the field (if not using Bootstrap)
35
-	 *
36
-	 * @var string
37
-	 */
38
-	protected $label;
39
-
40
-	/**
41
-	 * The field's group
42
-	 *
43
-	 * @var Group
44
-	 */
45
-	protected $group;
46
-
47
-	/**
48
-	 * The field's default element
49
-	 *
50
-	 * @var string
51
-	 */
52
-	protected $element = 'input';
53
-
54
-	/**
55
-	 * Whether the Field is self-closing or not
56
-	 *
57
-	 * @var boolean
58
-	 */
59
-	protected $isSelfClosing = true;
60
-
61
-	/**
62
-	 * The field's bind destination
63
-	 *
64
-	 * @var string
65
-	 */
66
-	protected $bind;
67
-
68
-	/**
69
-	 * Renders with floating label
70
-	 *
71
-	 * @var boolean
72
-	 */
73
-	protected $floatingLabel = false;
74
-
75
-	/**
76
-	 * Get the current framework instance
77
-	 *
78
-	 * @return Framework
79
-	 */
80
-	protected function currentFramework()
81
-	{
82
-		if ($this->app->bound('former.form.framework')) {
83
-			return $this->app['former.form.framework'];
84
-		}
85
-
86
-		return $this->app['former.framework'];
87
-	}
88
-
89
-	////////////////////////////////////////////////////////////////////
90
-	///////////////////////////// INTERFACE ////////////////////////////
91
-	////////////////////////////////////////////////////////////////////
92
-
93
-	/**
94
-	 * Set up a Field instance
95
-	 *
96
-	 * @param string $type A field type
97
-	 */
98
-	public function __construct(Container $app, $type, $name, $label, $value, $attributes)
99
-	{
100
-		// Set base parameters
101
-		$this->app   = $app;
102
-		$this->type  = $type;
103
-		$this->value = $value;
104
-		$this->setAttributes($attributes);
105
-		$this->form = $this->app->bound('former.form') ? $this->app['former.form'] : null;
106
-
107
-		// Compute and translate label
108
-		$this->automaticLabels($name, $label);
109
-
110
-		// Repopulate field
111
-		if ($type != 'password' && $name !== '_token') {
112
-			$this->value = $this->repopulate();
113
-		}
114
-
115
-		// Apply Live validation rules
116
-		if ($this->app['former']->getOption('live_validation')) {
117
-			$rules = new LiveValidation($this);
118
-			$rules->apply($this->getRules());
119
-		}
120
-
121
-		// Bind the Group class
122
-		$groupClass = $this->isCheckable() ? 'CheckableGroup' : 'Group';
123
-		$groupClass = Former::FORMSPACE.$groupClass;
124
-
125
-		$this->group = new $groupClass($this->app, $this->label);
126
-	}
127
-
128
-	/**
129
-	 * Redirect calls to the group if necessary
130
-	 *
131
-	 * @param string $method
132
-	 */
133
-	public function __call($method, $parameters)
134
-	{
135
-		// Translate attributes
136
-		$translatable = $this->app['former']->getOption('translatable', array());
137
-		if (in_array($method, $translatable) and isset($parameters[0])) {
138
-			$parameters[0] = Helpers::translate($parameters[0]);
139
-		}
140
-
141
-		// Redirect calls to the Control Group
142
-		if ((!empty($this->group) && method_exists($this->group, $method)) or Str::startsWith($method, 'onGroup')) {
143
-			$method = str_replace('onGroup', '', $method);
144
-			$method = lcfirst($method);
145
-
146
-			call_user_func_array(array($this->group, $method), $parameters);
147
-
148
-			return $this;
149
-		}
150
-
151
-		return parent::__call($method, $parameters);
152
-	}
153
-
154
-	/**
155
-	 * Prints out the field, wrapped in its group
156
-	 *
157
-	 * @return string
158
-	 */
159
-	public function wrapAndRender()
160
-	{
161
-		// Dry syntax (hidden fields, plain fields)
162
-		if ($this->isUnwrappable()) {
163
-			$html = $this->render();
164
-			// Control group syntax
165
-		} elseif (Form::hasInstanceOpened()) {
166
-			$html = $this->group->wrapField($this);
167
-			// Classic syntax
168
-		} else {
169
-			$html = $this->currentFramework()->createLabelOf($this);
170
-			$html .= $this->render();
171
-		}
172
-
173
-		return $html;
174
-	}
175
-
176
-	/**
177
-	 * Prints out the field
178
-	 *
179
-	 * @return string
180
-	 */
181
-	public function __toString()
182
-	{
183
-		return $this->wrapAndRender();
184
-	}
185
-
186
-	////////////////////////////////////////////////////////////////////
187
-	////////////////////////// PUBLIC INTERFACE ////////////////////////
188
-	////////////////////////////////////////////////////////////////////
189
-
190
-	/**
191
-	 * Whether the current field is required or not
192
-	 *
193
-	 * @return boolean
194
-	 */
195
-	public function isRequired()
196
-	{
197
-		return isset($this->attributes['required']);
198
-	}
199
-
200
-	/**
201
-	 * Set required live validation attribute
202
-	 *
203
-	 * @param boolean $isRequired
204
-	 * @return $this
205
-	 */
206
-	public function required($isRequired=true)
207
-	{
208
-		if ($isRequired) {
209
-			$this->attributes['required'] = true;
210
-		} else {
211
-			unset($this->attributes['required']);
212
-		}
213
-
214
-		return $this;
215
-	}
216
-
217
-	/**
218
-	 * Check if a field is unwrappable (no label)
219
-	 *
220
-	 * @return boolean
221
-	 */
222
-	public function isUnwrappable()
223
-	{
224
-		return
225
-			($this->form and $this->currentFramework()->is('Nude')) or
226
-			($this->form and $this->isOfType('inline')) or
227
-			$this->isButton() or
228
-			$this->isOfType('hidden') or
229
-			\Former\Form\Group::$opened or
230
-			$this->group and $this->group->isRaw();
231
-	}
232
-
233
-	/**
234
-	 * Check if field is a checkbox or a radio
235
-	 *
236
-	 * @return boolean
237
-	 */
238
-	public function isCheckable()
239
-	{
240
-		return $this->isOfType('checkbox', 'checkboxes', 'radio', 'radios', 'switch', 'switches');
241
-	}
242
-
243
-	/**
244
-	 * Check if the field is a button
245
-	 *
246
-	 * @return boolean
247
-	 */
248
-	public function isButton()
249
-	{
250
-		return false;
251
-	}
252
-
253
-	/**
254
-	 * Check if the field get a floating label
255
-	 *
256
-	 * @return boolean
257
-	 */
258
-	public function withFloatingLabel()
259
-	{
260
-		return $this->floatingLabel;
261
-	}
262
-
263
-	/**
264
-	 * Get the rules applied to the current field
265
-	 *
266
-	 * @return array An array of rules
267
-	 */
268
-	public function getRules()
269
-	{
270
-		return $this->app['former']->getRules($this->name);
271
-	}
272
-
273
-	////////////////////////////////////////////////////////////////////
274
-	//////////////////////// SETTERS AND GETTERS ///////////////////////
275
-	////////////////////////////////////////////////////////////////////
276
-
277
-	/**
278
-	 * Apply a Live Validation rule by chaining
279
-	 *
280
-	 * @param string $rule The rule
281
-	 */
282
-	public function rule($rule)
283
-	{
284
-		$parameters = func_get_args();
285
-		array_shift($parameters);
286
-
287
-		$live = new LiveValidation($this);
288
-		$live->apply(array(
289
-			$rule => $parameters,
290
-		));
291
-
292
-		return $this;
293
-	}
19
+    /**
20
+     * The IoC Container
21
+     *
22
+     * @var Container
23
+     */
24
+    protected $app;
25
+
26
+    /**
27
+     * The Form instance
28
+     *
29
+     * @var Former\Form
30
+     */
31
+    protected $form;
32
+
33
+    /**
34
+     * A label for the field (if not using Bootstrap)
35
+     *
36
+     * @var string
37
+     */
38
+    protected $label;
39
+
40
+    /**
41
+     * The field's group
42
+     *
43
+     * @var Group
44
+     */
45
+    protected $group;
46
+
47
+    /**
48
+     * The field's default element
49
+     *
50
+     * @var string
51
+     */
52
+    protected $element = 'input';
53
+
54
+    /**
55
+     * Whether the Field is self-closing or not
56
+     *
57
+     * @var boolean
58
+     */
59
+    protected $isSelfClosing = true;
60
+
61
+    /**
62
+     * The field's bind destination
63
+     *
64
+     * @var string
65
+     */
66
+    protected $bind;
67
+
68
+    /**
69
+     * Renders with floating label
70
+     *
71
+     * @var boolean
72
+     */
73
+    protected $floatingLabel = false;
74
+
75
+    /**
76
+     * Get the current framework instance
77
+     *
78
+     * @return Framework
79
+     */
80
+    protected function currentFramework()
81
+    {
82
+        if ($this->app->bound('former.form.framework')) {
83
+            return $this->app['former.form.framework'];
84
+        }
85
+
86
+        return $this->app['former.framework'];
87
+    }
88
+
89
+    ////////////////////////////////////////////////////////////////////
90
+    ///////////////////////////// INTERFACE ////////////////////////////
91
+    ////////////////////////////////////////////////////////////////////
92
+
93
+    /**
94
+     * Set up a Field instance
95
+     *
96
+     * @param string $type A field type
97
+     */
98
+    public function __construct(Container $app, $type, $name, $label, $value, $attributes)
99
+    {
100
+        // Set base parameters
101
+        $this->app   = $app;
102
+        $this->type  = $type;
103
+        $this->value = $value;
104
+        $this->setAttributes($attributes);
105
+        $this->form = $this->app->bound('former.form') ? $this->app['former.form'] : null;
106
+
107
+        // Compute and translate label
108
+        $this->automaticLabels($name, $label);
109
+
110
+        // Repopulate field
111
+        if ($type != 'password' && $name !== '_token') {
112
+            $this->value = $this->repopulate();
113
+        }
114
+
115
+        // Apply Live validation rules
116
+        if ($this->app['former']->getOption('live_validation')) {
117
+            $rules = new LiveValidation($this);
118
+            $rules->apply($this->getRules());
119
+        }
120
+
121
+        // Bind the Group class
122
+        $groupClass = $this->isCheckable() ? 'CheckableGroup' : 'Group';
123
+        $groupClass = Former::FORMSPACE.$groupClass;
124
+
125
+        $this->group = new $groupClass($this->app, $this->label);
126
+    }
127
+
128
+    /**
129
+     * Redirect calls to the group if necessary
130
+     *
131
+     * @param string $method
132
+     */
133
+    public function __call($method, $parameters)
134
+    {
135
+        // Translate attributes
136
+        $translatable = $this->app['former']->getOption('translatable', array());
137
+        if (in_array($method, $translatable) and isset($parameters[0])) {
138
+            $parameters[0] = Helpers::translate($parameters[0]);
139
+        }
140
+
141
+        // Redirect calls to the Control Group
142
+        if ((!empty($this->group) && method_exists($this->group, $method)) or Str::startsWith($method, 'onGroup')) {
143
+            $method = str_replace('onGroup', '', $method);
144
+            $method = lcfirst($method);
145
+
146
+            call_user_func_array(array($this->group, $method), $parameters);
147
+
148
+            return $this;
149
+        }
150
+
151
+        return parent::__call($method, $parameters);
152
+    }
153
+
154
+    /**
155
+     * Prints out the field, wrapped in its group
156
+     *
157
+     * @return string
158
+     */
159
+    public function wrapAndRender()
160
+    {
161
+        // Dry syntax (hidden fields, plain fields)
162
+        if ($this->isUnwrappable()) {
163
+            $html = $this->render();
164
+            // Control group syntax
165
+        } elseif (Form::hasInstanceOpened()) {
166
+            $html = $this->group->wrapField($this);
167
+            // Classic syntax
168
+        } else {
169
+            $html = $this->currentFramework()->createLabelOf($this);
170
+            $html .= $this->render();
171
+        }
172
+
173
+        return $html;
174
+    }
175
+
176
+    /**
177
+     * Prints out the field
178
+     *
179
+     * @return string
180
+     */
181
+    public function __toString()
182
+    {
183
+        return $this->wrapAndRender();
184
+    }
185
+
186
+    ////////////////////////////////////////////////////////////////////
187
+    ////////////////////////// PUBLIC INTERFACE ////////////////////////
188
+    ////////////////////////////////////////////////////////////////////
189
+
190
+    /**
191
+     * Whether the current field is required or not
192
+     *
193
+     * @return boolean
194
+     */
195
+    public function isRequired()
196
+    {
197
+        return isset($this->attributes['required']);
198
+    }
199
+
200
+    /**
201
+     * Set required live validation attribute
202
+     *
203
+     * @param boolean $isRequired
204
+     * @return $this
205
+     */
206
+    public function required($isRequired=true)
207
+    {
208
+        if ($isRequired) {
209
+            $this->attributes['required'] = true;
210
+        } else {
211
+            unset($this->attributes['required']);
212
+        }
213
+
214
+        return $this;
215
+    }
216
+
217
+    /**
218
+     * Check if a field is unwrappable (no label)
219
+     *
220
+     * @return boolean
221
+     */
222
+    public function isUnwrappable()
223
+    {
224
+        return
225
+            ($this->form and $this->currentFramework()->is('Nude')) or
226
+            ($this->form and $this->isOfType('inline')) or
227
+            $this->isButton() or
228
+            $this->isOfType('hidden') or
229
+            \Former\Form\Group::$opened or
230
+            $this->group and $this->group->isRaw();
231
+    }
232
+
233
+    /**
234
+     * Check if field is a checkbox or a radio
235
+     *
236
+     * @return boolean
237
+     */
238
+    public function isCheckable()
239
+    {
240
+        return $this->isOfType('checkbox', 'checkboxes', 'radio', 'radios', 'switch', 'switches');
241
+    }
242
+
243
+    /**
244
+     * Check if the field is a button
245
+     *
246
+     * @return boolean
247
+     */
248
+    public function isButton()
249
+    {
250
+        return false;
251
+    }
252
+
253
+    /**
254
+     * Check if the field get a floating label
255
+     *
256
+     * @return boolean
257
+     */
258
+    public function withFloatingLabel()
259
+    {
260
+        return $this->floatingLabel;
261
+    }
262
+
263
+    /**
264
+     * Get the rules applied to the current field
265
+     *
266
+     * @return array An array of rules
267
+     */
268
+    public function getRules()
269
+    {
270
+        return $this->app['former']->getRules($this->name);
271
+    }
272
+
273
+    ////////////////////////////////////////////////////////////////////
274
+    //////////////////////// SETTERS AND GETTERS ///////////////////////
275
+    ////////////////////////////////////////////////////////////////////
276
+
277
+    /**
278
+     * Apply a Live Validation rule by chaining
279
+     *
280
+     * @param string $rule The rule
281
+     */
282
+    public function rule($rule)
283
+    {
284
+        $parameters = func_get_args();
285
+        array_shift($parameters);
286
+
287
+        $live = new LiveValidation($this);
288
+        $live->apply(array(
289
+            $rule => $parameters,
290
+        ));
291
+
292
+        return $this;
293
+    }
294 294
 
295 295
     /**
296 296
      * Apply multiple rules passed as a string.
@@ -312,9 +312,9 @@  discard block
 block discarded – undo
312 312
                 $rulename = substr($rule, 0, $colon) ;
313 313
 
314 314
                 /**
315
-                * Regular expressions may contain commas and should not be divided by str_getcsv.
316
-                * For regular expressions we are just using the complete expression as a parameter.
317
-                */
315
+                 * Regular expressions may contain commas and should not be divided by str_getcsv.
316
+                 * For regular expressions we are just using the complete expression as a parameter.
317
+                 */
318 318
                 if ($rulename !== 'regex') {
319 319
                     $parameters = str_getcsv(substr($rule, $colon + 1), ',', '"', "\\");
320 320
                 } else {
@@ -336,159 +336,159 @@  discard block
 block discarded – undo
336 336
         return $this;
337 337
     }
338 338
 
339
-	/**
340
-	 * Adds a label to the group/field
341
-	 *
342
-	 * @param  string $text       A label
343
-	 * @param  array  $attributes The label's attributes
344
-	 *
345
-	 * @return Field              A field
346
-	 */
347
-	public function label($text, $attributes = array())
348
-	{
349
-		// Create the Label element
350
-		$for   = $this->id ?: $this->name;
351
-		$label = $this->app['former']->label($text, $for, $attributes);
352
-
353
-		// Set label
354
-		$this->label = $label;
355
-		if ($this->group) {
356
-			$this->group->setLabel($label);
357
-		}
358
-
359
-		return $this;
360
-	}
361
-
362
-	/**
363
-	 * Set the Field value no matter what
364
-	 *
365
-	 * @param string $value A new value
366
-	 */
367
-	public function forceValue($value)
368
-	{
369
-		$this->value = $value;
370
-
371
-		return $this;
372
-	}
373
-
374
-	/**
375
-	 * Classic setting of attribute, won't overwrite any populate() attempt
376
-	 *
377
-	 * @param  string $value A new value
378
-	 */
379
-	public function value($value)
380
-	{
381
-		// Check if we already have a value stored for this field or in POST data
382
-		$already = $this->repopulate();
383
-
384
-		if (!$already) {
385
-			$this->value = $value;
386
-		}
387
-
388
-		return $this;
389
-	}
390
-
391
-	/**
392
-	 * Change the field's name
393
-	 *
394
-	 * @param  string $name The new name
395
-	 */
396
-	public function name($name)
397
-	{
398
-		$this->name = $name;
399
-
400
-		// Also relink the label to the new name
401
-		$this->label($name);
402
-
403
-		return $this;
404
-	}
405
-
406
-	/**
407
-	 * Set the field as floating label
408
-	 */
409
-	public function floatingLabel($isFloatingLabel = true)
410
-	{
411
-		$this->floatingLabel = $isFloatingLabel;
412
-
413
-		return $this;
414
-	}
415
-
416
-	/**
417
-	 * Get the field's labels
418
-	 *
419
-	 * @return string
420
-	 */
421
-	public function getLabel()
422
-	{
423
-		return $this->label;
424
-	}
425
-
426
-	/**
427
-	 * Change the field's bind destination
428
-	 *
429
-	 * @param $destination
430
-	 */
431
-	public function bind($destination) {
432
-		$this->bind = $destination;
433
-		if ($this->type != 'password') {
434
-			$this->value = $this->repopulate();
435
-		}
436
-
437
-		return $this;
438
-	}
439
-
440
-	////////////////////////////////////////////////////////////////////
441
-	//////////////////////////////// HELPERS ///////////////////////////
442
-	////////////////////////////////////////////////////////////////////
443
-
444
-	/**
445
-	 * Use values stored in Former to populate the current field
446
-	 */
447
-	private function repopulate($fallback = null)
448
-	{
449
-		// Get values from POST, populated, and manually set value
450
-		$post      = $this->app['former']->getPost($this->name);
451
-		$populator = $this->form ? $this->form->getPopulator() : $this->app['former.populator'];
452
-		$populate  = $populator->get($this->bind ?: $this->name);
453
-
454
-		// Assign a priority to each
455
-		if (!is_null($post)) {
456
-			return $post;
457
-		}
458
-		if (!is_null($populate)) {
459
-			return $populate;
460
-		}
461
-
462
-		return $fallback ?: $this->value;
463
-	}
464
-
465
-	/**
466
-	 * Ponders a label and a field name, and tries to get the best out of it
467
-	 *
468
-	 * @param  string $label A label
469
-	 * @param  string $name  A field name
470
-	 *
471
-	 * @return false|null         A label and a field name
472
-	 */
473
-	private function automaticLabels($name, $label)
474
-	{
475
-		// Disabled automatic labels
476
-		if (!$this->app['former']->getOption('automatic_label')) {
477
-			$this->name = $name;
478
-			$this->label($label);
479
-
480
-			return false;
481
-		}
482
-
483
-		// Check for the two possibilities
484
-		if ($label and is_null($name)) {
485
-			$name = Str::slug($label);
486
-		} elseif (is_null($label) and $name) {
487
-			$label = preg_replace('/\[\]$/', '', $name);
488
-		}
489
-
490
-		// Save values
491
-		$this->name = $name;
492
-		$this->label($label);
493
-	}
339
+    /**
340
+     * Adds a label to the group/field
341
+     *
342
+     * @param  string $text       A label
343
+     * @param  array  $attributes The label's attributes
344
+     *
345
+     * @return Field              A field
346
+     */
347
+    public function label($text, $attributes = array())
348
+    {
349
+        // Create the Label element
350
+        $for   = $this->id ?: $this->name;
351
+        $label = $this->app['former']->label($text, $for, $attributes);
352
+
353
+        // Set label
354
+        $this->label = $label;
355
+        if ($this->group) {
356
+            $this->group->setLabel($label);
357
+        }
358
+
359
+        return $this;
360
+    }
361
+
362
+    /**
363
+     * Set the Field value no matter what
364
+     *
365
+     * @param string $value A new value
366
+     */
367
+    public function forceValue($value)
368
+    {
369
+        $this->value = $value;
370
+
371
+        return $this;
372
+    }
373
+
374
+    /**
375
+     * Classic setting of attribute, won't overwrite any populate() attempt
376
+     *
377
+     * @param  string $value A new value
378
+     */
379
+    public function value($value)
380
+    {
381
+        // Check if we already have a value stored for this field or in POST data
382
+        $already = $this->repopulate();
383
+
384
+        if (!$already) {
385
+            $this->value = $value;
386
+        }
387
+
388
+        return $this;
389
+    }
390
+
391
+    /**
392
+     * Change the field's name
393
+     *
394
+     * @param  string $name The new name
395
+     */
396
+    public function name($name)
397
+    {
398
+        $this->name = $name;
399
+
400
+        // Also relink the label to the new name
401
+        $this->label($name);
402
+
403
+        return $this;
404
+    }
405
+
406
+    /**
407
+     * Set the field as floating label
408
+     */
409
+    public function floatingLabel($isFloatingLabel = true)
410
+    {
411
+        $this->floatingLabel = $isFloatingLabel;
412
+
413
+        return $this;
414
+    }
415
+
416
+    /**
417
+     * Get the field's labels
418
+     *
419
+     * @return string
420
+     */
421
+    public function getLabel()
422
+    {
423
+        return $this->label;
424
+    }
425
+
426
+    /**
427
+     * Change the field's bind destination
428
+     *
429
+     * @param $destination
430
+     */
431
+    public function bind($destination) {
432
+        $this->bind = $destination;
433
+        if ($this->type != 'password') {
434
+            $this->value = $this->repopulate();
435
+        }
436
+
437
+        return $this;
438
+    }
439
+
440
+    ////////////////////////////////////////////////////////////////////
441
+    //////////////////////////////// HELPERS ///////////////////////////
442
+    ////////////////////////////////////////////////////////////////////
443
+
444
+    /**
445
+     * Use values stored in Former to populate the current field
446
+     */
447
+    private function repopulate($fallback = null)
448
+    {
449
+        // Get values from POST, populated, and manually set value
450
+        $post      = $this->app['former']->getPost($this->name);
451
+        $populator = $this->form ? $this->form->getPopulator() : $this->app['former.populator'];
452
+        $populate  = $populator->get($this->bind ?: $this->name);
453
+
454
+        // Assign a priority to each
455
+        if (!is_null($post)) {
456
+            return $post;
457
+        }
458
+        if (!is_null($populate)) {
459
+            return $populate;
460
+        }
461
+
462
+        return $fallback ?: $this->value;
463
+    }
464
+
465
+    /**
466
+     * Ponders a label and a field name, and tries to get the best out of it
467
+     *
468
+     * @param  string $label A label
469
+     * @param  string $name  A field name
470
+     *
471
+     * @return false|null         A label and a field name
472
+     */
473
+    private function automaticLabels($name, $label)
474
+    {
475
+        // Disabled automatic labels
476
+        if (!$this->app['former']->getOption('automatic_label')) {
477
+            $this->name = $name;
478
+            $this->label($label);
479
+
480
+            return false;
481
+        }
482
+
483
+        // Check for the two possibilities
484
+        if ($label and is_null($name)) {
485
+            $name = Str::slug($label);
486
+        } elseif (is_null($label) and $name) {
487
+            $label = preg_replace('/\[\]$/', '', $name);
488
+        }
489
+
490
+        // Save values
491
+        $this->name = $name;
492
+        $this->label($label);
493
+    }
494 494
 }
Please login to merge, or discard this patch.
src/Former/Traits/FormerObject.php 2 patches
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/Form/Fields/Choice.php 2 patches
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 ($this->value !== null && !(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) : '';
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 ($this->value !== null && !(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) : '';
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/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   +486 added lines, -486 removed lines patch added patch discarded remove patch
@@ -14,490 +14,490 @@
 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
-				if (is_object($expFieldRules)) {
306
-					continue;
307
-				}
308
-
309
-				$expFieldRules = explode('|', $expFieldRules);
310
-				$expFieldRules = array_map('trim', $expFieldRules);
311
-			}
312
-
313
-			foreach ($expFieldRules as $rule) {
314
-				if (is_object($rule)) {
315
-					continue;
316
-				}
317
-
318
-				$parameters = null;
319
-
320
-				if (($colon = strpos($rule, ':')) !== false) {
321
-					$rulename = substr($rule, 0, $colon);
322
-
323
-					/**
324
-					 * Regular expressions may contain commas and should not be divided by str_getcsv.
325
-					 * For regular expressions we are just using the complete expression as a parameter.
326
-					 */
327
-					if ($rulename !== 'regex') {
328
-						$parameters = str_getcsv(substr($rule, $colon + 1), ',', '"', "\\");
329
-					} else {
330
-						$parameters = [substr($rule, $colon + 1)];
331
-					}
332
-				}
333
-
334
-				// Exclude unsupported rules
335
-				$rule = is_numeric($colon) ? substr($rule, 0, $colon) : $rule;
336
-
337
-				// Store processed rule in Former's array
338
-				if (!isset($parameters)) {
339
-					$parameters = array();
340
-				}
341
-
342
-				$this->rules[$name][$rule] = $parameters;
343
-			}
344
-		}
345
-	}
346
-
347
-	/**
348
-	 * Switch the framework used by Former
349
-	 *
350
-	 * @param string $framework The name of the framework to use
351
-	 */
352
-	public function framework($framework = null)
353
-	{
354
-		if (!$framework) {
355
-			return $this->app['former.framework']->current();
356
-		}
357
-
358
-		$this->setOption('framework', $framework);
359
-
360
-		$framework = $this->getFrameworkInstance($framework);
361
-		$this->app->bind('former.framework', function ($app) use ($framework) {
362
-			return $framework;
363
-		});
364
-	}
365
-
366
-	/**
367
-	 * Get a new framework instance
368
-	 *
369
-	 * @param string $framework
370
-	 *
371
-	 * @throws Exceptions\InvalidFrameworkException
372
-	 * @return \Former\Interfaces\FrameworkInterface
373
-	 */
374
-	public function getFrameworkInstance($framework)
375
-	{
376
-		$formerClass = __NAMESPACE__.'\Framework\\'.$framework;
377
-
378
-		//get interfaces of the given framework
379
-		$interfaces = class_exists($framework) ? class_implements($framework) : array();
380
-
381
-		if(class_exists($formerClass)) {
382
-			$returnClass = $formerClass;
383
-		} elseif(class_exists($framework) && isset($interfaces['Former\Interfaces\FrameworkInterface'])) {
384
-			// We have some outside class, lets return it.
385
-			$returnClass = $framework;
386
-		} else {
387
-			throw (new InvalidFrameworkException())->setFramework($framework);
388
-		}
389
-
390
-		return new $returnClass($this->app);
391
-	}
392
-
393
-	/**
394
-	 * Get an option from the config
395
-	 *
396
-	 * @param string $option  The option
397
-	 * @param mixed  $default Optional fallback
398
-	 *
399
-	 * @return mixed
400
-	 */
401
-	public function getOption($option, $default = null)
402
-	{
403
-		return $this->app['config']->get('former.'.$option, $default);
404
-	}
405
-
406
-	/**
407
-	 * Set an option on the config
408
-	 *
409
-	 * @param string $option
410
-	 * @param string $value
411
-	 */
412
-	public function setOption($option, $value)
413
-	{
414
-		return $this->app['config']->set('former.'.$option, $value);
415
-	}
416
-
417
-	////////////////////////////////////////////////////////////////////
418
-	////////////////////////////// BUILDERS ////////////////////////////
419
-	////////////////////////////////////////////////////////////////////
420
-
421
-	/**
422
-	 * Closes a form
423
-	 *
424
-	 * @return string A form closing tag
425
-	 */
426
-	public function close()
427
-	{
428
-		if ($this->app->bound('former.form')) {
429
-			$closing = $this->app['former.form']->close();
430
-		}
431
-
432
-		// Destroy instances
433
-		$instances = array('former.form', 'former.form.framework');
434
-		foreach ($instances as $instance) {
435
-			$this->app[$instance] = null;
436
-			unset($this->app[$instance]);
437
-		}
438
-
439
-		// Reset populator
440
-		$this->app['former.populator']->reset();
441
-
442
-		// Reset all values
443
-		$this->errors = null;
444
-		$this->rules  = array();
445
-
446
-		return isset($closing) ? $closing : null;
447
-	}
448
-
449
-	////////////////////////////////////////////////////////////////////
450
-	////////////////////////////// HELPERS /////////////////////////////
451
-	////////////////////////////////////////////////////////////////////
452
-
453
-	/**
454
-	 * Get the errors for the current field
455
-	 *
456
-	 * @param  string $name A field name
457
-	 *
458
-	 * @return string       An error message
459
-	 */
460
-	public function getErrors($name = null)
461
-	{
462
-		// Get name and translate array notation
463
-		if (!$name and $this->app['former.field']) {
464
-			$name = $this->app['former.field']->getName();
465
-
466
-			// Always return empty string for anonymous fields (i.e. fields with no name/id)
467
-			if (!$name) {
468
-				return '';
469
-			}
470
-		}
471
-
472
-		if ($this->errors and $name) {
473
-			$name = str_replace(array('[', ']'), array('.', ''), $name);
474
-			$name = trim($name, '.');
475
-
476
-			return $this->errors->first($name);
477
-		}
478
-
479
-		return $this->errors;
480
-	}
481
-
482
-	/**
483
-	 * Get a rule from the Rules array
484
-	 *
485
-	 * @param  string $name The field to fetch
486
-	 *
487
-	 * @return array        An array of rules
488
-	 */
489
-	public function getRules($name)
490
-	{
491
-		// Check the rules for the name as given
492
-		$ruleset = Arr::get($this->rules, $name);
493
-
494
-		// If no rules found, convert to dot notation and try again
495
-		if (is_null($ruleset)) {
496
-			$name = str_replace(array('[', ']'), array('.', ''), $name);
497
-			$name = trim($name, '.');
498
-			$ruleset = Arr::get($this->rules, $name);
499
-		}
500
-
501
-		return $ruleset;
502
-	}
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
+                if (is_object($expFieldRules)) {
306
+                    continue;
307
+                }
308
+
309
+                $expFieldRules = explode('|', $expFieldRules);
310
+                $expFieldRules = array_map('trim', $expFieldRules);
311
+            }
312
+
313
+            foreach ($expFieldRules as $rule) {
314
+                if (is_object($rule)) {
315
+                    continue;
316
+                }
317
+
318
+                $parameters = null;
319
+
320
+                if (($colon = strpos($rule, ':')) !== false) {
321
+                    $rulename = substr($rule, 0, $colon);
322
+
323
+                    /**
324
+                     * Regular expressions may contain commas and should not be divided by str_getcsv.
325
+                     * For regular expressions we are just using the complete expression as a parameter.
326
+                     */
327
+                    if ($rulename !== 'regex') {
328
+                        $parameters = str_getcsv(substr($rule, $colon + 1), ',', '"', "\\");
329
+                    } else {
330
+                        $parameters = [substr($rule, $colon + 1)];
331
+                    }
332
+                }
333
+
334
+                // Exclude unsupported rules
335
+                $rule = is_numeric($colon) ? substr($rule, 0, $colon) : $rule;
336
+
337
+                // Store processed rule in Former's array
338
+                if (!isset($parameters)) {
339
+                    $parameters = array();
340
+                }
341
+
342
+                $this->rules[$name][$rule] = $parameters;
343
+            }
344
+        }
345
+    }
346
+
347
+    /**
348
+     * Switch the framework used by Former
349
+     *
350
+     * @param string $framework The name of the framework to use
351
+     */
352
+    public function framework($framework = null)
353
+    {
354
+        if (!$framework) {
355
+            return $this->app['former.framework']->current();
356
+        }
357
+
358
+        $this->setOption('framework', $framework);
359
+
360
+        $framework = $this->getFrameworkInstance($framework);
361
+        $this->app->bind('former.framework', function ($app) use ($framework) {
362
+            return $framework;
363
+        });
364
+    }
365
+
366
+    /**
367
+     * Get a new framework instance
368
+     *
369
+     * @param string $framework
370
+     *
371
+     * @throws Exceptions\InvalidFrameworkException
372
+     * @return \Former\Interfaces\FrameworkInterface
373
+     */
374
+    public function getFrameworkInstance($framework)
375
+    {
376
+        $formerClass = __NAMESPACE__.'\Framework\\'.$framework;
377
+
378
+        //get interfaces of the given framework
379
+        $interfaces = class_exists($framework) ? class_implements($framework) : array();
380
+
381
+        if(class_exists($formerClass)) {
382
+            $returnClass = $formerClass;
383
+        } elseif(class_exists($framework) && isset($interfaces['Former\Interfaces\FrameworkInterface'])) {
384
+            // We have some outside class, lets return it.
385
+            $returnClass = $framework;
386
+        } else {
387
+            throw (new InvalidFrameworkException())->setFramework($framework);
388
+        }
389
+
390
+        return new $returnClass($this->app);
391
+    }
392
+
393
+    /**
394
+     * Get an option from the config
395
+     *
396
+     * @param string $option  The option
397
+     * @param mixed  $default Optional fallback
398
+     *
399
+     * @return mixed
400
+     */
401
+    public function getOption($option, $default = null)
402
+    {
403
+        return $this->app['config']->get('former.'.$option, $default);
404
+    }
405
+
406
+    /**
407
+     * Set an option on the config
408
+     *
409
+     * @param string $option
410
+     * @param string $value
411
+     */
412
+    public function setOption($option, $value)
413
+    {
414
+        return $this->app['config']->set('former.'.$option, $value);
415
+    }
416
+
417
+    ////////////////////////////////////////////////////////////////////
418
+    ////////////////////////////// BUILDERS ////////////////////////////
419
+    ////////////////////////////////////////////////////////////////////
420
+
421
+    /**
422
+     * Closes a form
423
+     *
424
+     * @return string A form closing tag
425
+     */
426
+    public function close()
427
+    {
428
+        if ($this->app->bound('former.form')) {
429
+            $closing = $this->app['former.form']->close();
430
+        }
431
+
432
+        // Destroy instances
433
+        $instances = array('former.form', 'former.form.framework');
434
+        foreach ($instances as $instance) {
435
+            $this->app[$instance] = null;
436
+            unset($this->app[$instance]);
437
+        }
438
+
439
+        // Reset populator
440
+        $this->app['former.populator']->reset();
441
+
442
+        // Reset all values
443
+        $this->errors = null;
444
+        $this->rules  = array();
445
+
446
+        return isset($closing) ? $closing : null;
447
+    }
448
+
449
+    ////////////////////////////////////////////////////////////////////
450
+    ////////////////////////////// HELPERS /////////////////////////////
451
+    ////////////////////////////////////////////////////////////////////
452
+
453
+    /**
454
+     * Get the errors for the current field
455
+     *
456
+     * @param  string $name A field name
457
+     *
458
+     * @return string       An error message
459
+     */
460
+    public function getErrors($name = null)
461
+    {
462
+        // Get name and translate array notation
463
+        if (!$name and $this->app['former.field']) {
464
+            $name = $this->app['former.field']->getName();
465
+
466
+            // Always return empty string for anonymous fields (i.e. fields with no name/id)
467
+            if (!$name) {
468
+                return '';
469
+            }
470
+        }
471
+
472
+        if ($this->errors and $name) {
473
+            $name = str_replace(array('[', ']'), array('.', ''), $name);
474
+            $name = trim($name, '.');
475
+
476
+            return $this->errors->first($name);
477
+        }
478
+
479
+        return $this->errors;
480
+    }
481
+
482
+    /**
483
+     * Get a rule from the Rules array
484
+     *
485
+     * @param  string $name The field to fetch
486
+     *
487
+     * @return array        An array of rules
488
+     */
489
+    public function getRules($name)
490
+    {
491
+        // Check the rules for the name as given
492
+        $ruleset = Arr::get($this->rules, $name);
493
+
494
+        // If no rules found, convert to dot notation and try again
495
+        if (is_null($ruleset)) {
496
+            $name = str_replace(array('[', ']'), array('.', ''), $name);
497
+            $name = trim($name, '.');
498
+            $ruleset = Arr::get($this->rules, $name);
499
+        }
500
+
501
+        return $ruleset;
502
+    }
503 503
 }
Please login to merge, or discard this patch.
src/Former/Framework/TwitterBootstrap4.php 2 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.
Indentation   +465 added lines, -465 removed lines patch added patch discarded remove patch
@@ -13,469 +13,469 @@
 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('col-form-label', $this->labelWidth);
274
-		} elseif ($this->app['former.form']->isOfType('inline')) {
275
-			return array('sr-only');
276
-		} else {
277
-			return array('col-form-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-plaintext';
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, $place = null)
409
-	{
410
-		// Render object
411
-		if (is_object($item) and method_exists($item, '__toString')) {
412
-			$item = $item->__toString();
413
-		}
414
-
415
-		$items = (array) $item;
416
-		$element = '';
417
-		foreach ($items as $item) {
418
-			$hasButtonTag = strpos(ltrim($item), '<button') === 0;
419
-
420
-			// Get class to use
421
-			$class = $hasButtonTag ? '' : 'input-group-text';
422
-
423
-			$element .= $hasButtonTag ? $item : Element::create('span', $item)->addClass($class);
424
-		}
425
-
426
-		return Element::create('div', $element)->addClass('input-group-'.$place);
427
-	}
428
-
429
-	/**
430
-	 * Wrap a field with prepended and appended items
431
-	 *
432
-	 * @param  Field $field
433
-	 * @param  array $prepend
434
-	 * @param  array $append
435
-	 *
436
-	 * @return string A field concatented with prepended and/or appended items
437
-	 */
438
-	public function prependAppend($field, $prepend, $append)
439
-	{
440
-		$return = '<div class="input-group">';
441
-		$return .= implode('', $prepend);
442
-		$return .= $field->render();
443
-		$return .= implode('', $append);
444
-		$return .= '</div>';
445
-
446
-		return $return;
447
-	}
448
-
449
-	/**
450
-	 * Wrap a field with potential additional tags
451
-	 *
452
-	 * @param  Field $field
453
-	 *
454
-	 * @return Element A wrapped field
455
-	 */
456
-	public function wrapField($field)
457
-	{
458
-		if ($this->app['former.form']->isOfType('horizontal')) {
459
-			return Element::create('div', $field)->addClass($this->fieldWidth);
460
-		}
461
-
462
-		return $field;
463
-	}
464
-
465
-	/**
466
-	 * Wrap actions block with potential additional tags
467
-	 *
468
-	 * @param  Actions $actions
469
-	 *
470
-	 * @return string A wrapped actions block
471
-	 */
472
-	public function wrapActions($actions)
473
-	{
474
-		// For horizontal forms, we wrap the actions in a div
475
-		if ($this->app['former.form']->isOfType('horizontal')) {
476
-			return Element::create('div', $actions)->addClass(array($this->fieldOffset, $this->fieldWidth));
477
-		}
478
-
479
-		return $actions;
480
-	}
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('col-form-label', $this->labelWidth);
274
+        } elseif ($this->app['former.form']->isOfType('inline')) {
275
+            return array('sr-only');
276
+        } else {
277
+            return array('col-form-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-plaintext';
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, $place = null)
409
+    {
410
+        // Render object
411
+        if (is_object($item) and method_exists($item, '__toString')) {
412
+            $item = $item->__toString();
413
+        }
414
+
415
+        $items = (array) $item;
416
+        $element = '';
417
+        foreach ($items as $item) {
418
+            $hasButtonTag = strpos(ltrim($item), '<button') === 0;
419
+
420
+            // Get class to use
421
+            $class = $hasButtonTag ? '' : 'input-group-text';
422
+
423
+            $element .= $hasButtonTag ? $item : Element::create('span', $item)->addClass($class);
424
+        }
425
+
426
+        return Element::create('div', $element)->addClass('input-group-'.$place);
427
+    }
428
+
429
+    /**
430
+     * Wrap a field with prepended and appended items
431
+     *
432
+     * @param  Field $field
433
+     * @param  array $prepend
434
+     * @param  array $append
435
+     *
436
+     * @return string A field concatented with prepended and/or appended items
437
+     */
438
+    public function prependAppend($field, $prepend, $append)
439
+    {
440
+        $return = '<div class="input-group">';
441
+        $return .= implode('', $prepend);
442
+        $return .= $field->render();
443
+        $return .= implode('', $append);
444
+        $return .= '</div>';
445
+
446
+        return $return;
447
+    }
448
+
449
+    /**
450
+     * Wrap a field with potential additional tags
451
+     *
452
+     * @param  Field $field
453
+     *
454
+     * @return Element A wrapped field
455
+     */
456
+    public function wrapField($field)
457
+    {
458
+        if ($this->app['former.form']->isOfType('horizontal')) {
459
+            return Element::create('div', $field)->addClass($this->fieldWidth);
460
+        }
461
+
462
+        return $field;
463
+    }
464
+
465
+    /**
466
+     * Wrap actions block with potential additional tags
467
+     *
468
+     * @param  Actions $actions
469
+     *
470
+     * @return string A wrapped actions block
471
+     */
472
+    public function wrapActions($actions)
473
+    {
474
+        // For horizontal forms, we wrap the actions in a div
475
+        if ($this->app['former.form']->isOfType('horizontal')) {
476
+            return Element::create('div', $actions)->addClass(array($this->fieldOffset, $this->fieldWidth));
477
+        }
478
+
479
+        return $actions;
480
+    }
481 481
 }
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.