Test Setup Failed
Push — master ( c2e48f...d84003 )
by Fabio
08:11
created

TValidationSummary::getValidationFailed()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 0
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * TValidationSummary class file
4
 *
5
 * @author Qiang Xue <[email protected]>
6
 * @link https://github.com/pradosoft/prado
7
 * @copyright Copyright &copy; 2005-2016 The PRADO Group
8
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
9
 * @package Prado\Web\UI\WebControls
10
 */
11
12
namespace Prado\Web\UI\WebControls;
13
14
use Prado\TPropertyValue;
15
use Prado\Web\Javascripts\TJavaScript;
16
17
/**
18
 * TValidationSummary class
19
 *
20
 * TValidationSummary displays a summary of validation errors inline on a Web page,
21
 * in a message box, or both. By default, a validation summary will collect
22
 * {@link TBaseValidator::getErrorMessage ErrorMessage} of all failed validators
23
 * on the page. If {@link getValidationGroup ValidationGroup} is not
24
 * empty, only those validators who belong to the group will show their error messages
25
 * in the summary.
26
 *
27
 * The summary can be displayed as a list, as a bulleted list, or as a single
28
 * paragraph based on the {@link setDisplayMode DisplayMode} property.
29
 * The messages shown can be prefixed with {@link setHeaderText HeaderText}.
30
 *
31
 * The summary can be displayed on the Web page and in a message box by setting
32
 * the {@link setShowSummary ShowSummary} and {@link setShowMessageBox ShowMessageBox}
33
 * properties, respectively. Note, the latter is only effective when
34
 * {@link setEnableClientScript EnableClientScript} is true.
35
 *
36
 * @author Qiang Xue <[email protected]>
37
 * @package Prado\Web\UI\WebControls
38
 * @since 3.0
39
 */
40
class TValidationSummary extends \Prado\Web\UI\WebControls\TWebControl
41
{
42
	/**
43
	 * @var TClientSideValidationSummaryOptions validation client side options.
44
	 */
45
	private $_clientSide;
46
47
	/**
48
	 * Constructor.
49
	 * This method sets the foreground color to red.
50
	 */
51
	public function __construct()
52
	{
53
		parent::__construct();
54
		$this->setForeColor('red');
55
	}
56
57
	/**
58
	 * @return TValidationSummaryDisplayStyle the style of displaying the error messages. Defaults to TValidationSummaryDisplayStyle::Fixed.
59
	 */
60
	public function getDisplay()
61
	{
62
		return $this->getViewState('Display', TValidationSummaryDisplayStyle::Fixed);
63
	}
64
65
	/**
66
	 * @param TValidationSummaryDisplayStyle $value the style of displaying the error messages
67
	 */
68
	public function setDisplay($value)
69
	{
70
		$this->setViewState('Display', TPropertyValue::ensureEnum($value, 'Prado\\Web\\UI\\WebControls\\TValidationSummaryDisplayStyle'), TValidationSummaryDisplayStyle::Fixed);
71
	}
72
73
	/**
74
	 * @return string the header text displayed at the top of the summary
75
	 */
76
	public function getHeaderText()
77
	{
78
		return $this->getViewState('HeaderText', '');
79
	}
80
81
	/**
82
	 * Sets the header text to be displayed at the top of the summary
83
	 * @param string $value the header text
84
	 */
85
	public function setHeaderText($value)
86
	{
87
		$this->setViewState('HeaderText', $value, '');
88
	}
89
90
	/**
91
	 * @return TValidationSummaryDisplayMode the mode of displaying error messages. Defaults to TValidationSummaryDisplayMode::BulletList.
92
	 */
93
	public function getDisplayMode()
94
	{
95
		return $this->getViewState('DisplayMode', TValidationSummaryDisplayMode::BulletList);
96
	}
97
98
	/**
99
	 * @param TValidationSummaryDisplayMode $value the mode of displaying error messages
100
	 */
101
	public function setDisplayMode($value)
102
	{
103
		$this->setViewState('DisplayMode', TPropertyValue::ensureEnum($value, 'Prado\\Web\\UI\\WebControls\\TValidationSummaryDisplayMode'), TValidationSummaryDisplayMode::BulletList);
104
	}
105
106
	/**
107
	 * @return bool whether the TValidationSummary component updates itself using client-side script. Defaults to true.
108
	 */
109
	public function getEnableClientScript()
110
	{
111
		return $this->getViewState('EnableClientScript', true);
112
	}
113
114
	/**
115
	 * @param bool $value whether the TValidationSummary component updates itself using client-side script.
116
	 */
117
	public function setEnableClientScript($value)
118
	{
119
		$this->setViewState('EnableClientScript', TPropertyValue::ensureBoolean($value), true);
120
	}
121
122
	/**
123
	 * @return bool whether the validation summary is displayed in a message box. Defaults to false.
124
	 */
125
	public function getShowMessageBox()
126
	{
127
		return $this->getViewState('ShowMessageBox', false);
128
	}
129
130
	/**
131
	 * @param bool $value whether the validation summary is displayed in a message box.
132
	 */
133
	public function setShowMessageBox($value)
134
	{
135
		$this->setViewState('ShowMessageBox', TPropertyValue::ensureBoolean($value), false);
136
	}
137
138
	/**
139
	 * @return bool whether the validation summary is displayed inline. Defaults to true.
140
	 */
141
	public function getShowSummary()
142
	{
143
		return $this->getViewState('ShowSummary', true);
144
	}
145
146
	/**
147
	 * @param bool $value whether the validation summary is displayed inline.
148
	 */
149
	public function setShowSummary($value)
150
	{
151
		$this->setViewState('ShowSummary', TPropertyValue::ensureBoolean($value), true);
152
	}
153
154
	/**
155
	 * @return bool whether scroll summary into viewport or not. Defaults to true.
156
	 */
157
	public function getScrollToSummary()
158
	{
159
		return $this->getViewState('ScrollToSummary', true);
160
	}
161
162
	/**
163
	 * @param bool $value whether scroll summary into viewport or not.
164
	 */
165
	public function setScrollToSummary($value)
166
	{
167
		$this->setViewState('ScrollToSummary', TPropertyValue::ensureBoolean($value), true);
168
	}
169
170
	/**
171
	 * @return bool whether the validation summary should be anchored. Defaults to false.
172
	 */
173
	public function getShowAnchor()
174
	{
175
		return $this->getViewState('ShowAnchor', false);
176
	}
177
178
	/**
179
	 * @param bool $value whether the validation summary should be anchored.
180
	 */
181
	public function setShowAnchor($value)
182
	{
183
		$this->setViewState('ShowAnchor', TPropertyValue::ensureBoolean($value), false);
184
	}
185
186
	/**
187
	 * Gets the auto-update for this summary.
188
	 * @return bool automatic client-side summary updates. Defaults to true.
189
	 */
190
	public function getAutoUpdate()
191
	{
192
		return $this->getViewState('AutoUpdate', true);
193
	}
194
195
	/**
196
	 * Sets the summary to auto-update on the client-side
197
	 * @param bool $value true for automatic summary updates.
198
	 */
199
	public function setAutoUpdate($value)
200
	{
201
		$this->setViewState('AutoUpdate', TPropertyValue::ensureBoolean($value), true);
202
	}
203
204
	/**
205
	 * @return string the group which this validator belongs to
206
	 */
207
	public function getValidationGroup()
208
	{
209
		return $this->getViewState('ValidationGroup', '');
210
	}
211
212
	/**
213
	 * @param string $value the group which this validator belongs to
214
	 */
215
	public function setValidationGroup($value)
216
	{
217
		$this->setViewState('ValidationGroup', $value, '');
218
	}
219
220
	protected function addAttributesToRender($writer)
221
	{
222
		$display = $this->getDisplay();
223
		$visible = $this->getEnabled(true) && $this->getValidationFailed();
224 View Code Duplication
		if (!$visible) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
225
			if ($display === TValidationSummaryDisplayStyle::None || $display === TValidationSummaryDisplayStyle::Dynamic) {
226
				$writer->addStyleAttribute('display', 'none');
227
			} else {
228
				$writer->addStyleAttribute('visibility', 'hidden');
229
			}
230
		}
231
		$writer->addAttribute('id', $this->getClientID());
232
		parent::addAttributesToRender($writer);
233
	}
234
235
	/**
236
	 * Render the javascript for validation summary.
237
	 */
238
	protected function renderJsSummary()
239
	{
240
		if (!$this->getEnabled(true) || !$this->getEnableClientScript()) {
241
			return;
242
		}
243
		$cs = $this->getPage()->getClientScript();
244
		$cs->registerPradoScript('validator');
245
246
		//need to register the validation manager is validation summary is alone.
247
		$formID = $this->getPage()->getForm()->getClientID();
248
		$scriptKey = "TBaseValidator:$formID";
249 View Code Duplication
		if ($this->getEnableClientScript() && !$cs->isEndScriptRegistered($scriptKey)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
250
			$manager['FormID'] = $formID;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$manager was never initialized. Although not strictly required by PHP, it is generally a good practice to add $manager = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
251
			$options = TJavaScript::encode($manager);
252
			$cs->registerPradoScript('validator');
253
			$cs->registerEndScript($scriptKey, "new Prado.ValidationManager({$options});");
254
		}
255
256
257
		$options = TJavaScript::encode($this->getClientScriptOptions());
258
		$script = "new Prado.WebUI.TValidationSummary({$options});";
259
		$cs->registerEndScript($this->getClientID(), $script);
260
	}
261
262
	/**
263
	 * Get a list of options for the client-side javascript validation summary.
264
	 * @return array list of options for the summary
265
	 */
266
	protected function getClientScriptOptions()
267
	{
268
		$options['ID'] = $this->getClientID();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
269
		$options['FormID'] = $this->getPage()->getForm()->getClientID();
270
		if ($this->getShowMessageBox()) {
271
			$options['ShowMessageBox'] = true;
272
		}
273
		if (!$this->getShowSummary()) {
274
			$options['ShowSummary'] = false;
275
		}
276
277
		$options['ScrollToSummary'] = $this->getScrollToSummary();
278
		$options['HeaderText'] = $this->getHeaderText();
279
		$options['DisplayMode'] = $this->getDisplayMode();
280
281
		$options['Refresh'] = $this->getAutoUpdate();
282
		$options['ValidationGroup'] = $this->getValidationGroup();
283
		$options['Display'] = $this->getDisplay();
284
285
		if ($this->_clientSide !== null) {
286
			$options = array_merge($options, $this->_clientSide->getOptions()->toArray());
287
		}
288
289
		return $options;
290
	}
291
292
	/**
293
	 * @return TClientSideValidationSummaryOptions client-side validation summary
294
	 * event options.
295
	 */
296
	public function getClientSide()
297
	{
298
		if ($this->_clientSide === null) {
299
			$this->_clientSide = $this->createClientScript();
300
		}
301
		return $this->_clientSide;
302
	}
303
304
	/**
305
	 * @return TClientSideValidationSummaryOptions javascript validation summary
306
	 * event options.
307
	 */
308
	protected function createClientScript()
309
	{
310
		return new TClientSideValidationSummaryOptions;
311
	}
312
313
	/**
314
	 * Get the list of validation error messages.
315
	 * @return array list of validator error messages.
316
	 */
317
	protected function getErrorMessages()
318
	{
319
		$validators = $this->getPage()->getValidators($this->getValidationGroup());
320
		$messages = [];
321
		foreach ($validators as $validator) {
322
			if (!$validator->getIsValid() && ($msg = $validator->getErrorMessage()) !== '') {
323
				//$messages[] = $validator->getAnchoredMessage($msg);
324
				$messages[] = $msg;
325
			}
326
		}
327
		return $messages;
328
	}
329
330
	/**
331
	 * Checked if at least one validator failed.
332
	 * @return bool wether validation failed
333
	 */
334
	protected function getValidationFailed()
335
	{
336
		$validators = $this->getPage()->getValidators($this->getValidationGroup());
337
		foreach ($validators as $validator) {
338
			if (!$validator->getIsValid()) {
339
				return true;
340
			}
341
		}
342
		return false;
343
	}
344
345
	/**
346
	 * Overrides parent implementation by rendering TValidationSummary-specific presentation.
347
	 * @param mixed $writer
348
	 * @return string the rendering result
349
	 */
350
	public function renderContents($writer)
351
	{
352
		$this->renderJsSummary();
353
		if ($this->getShowSummary()) {
354
//		    $this->setStyle('display:block');
355
			switch ($this->getDisplayMode()) {
356
				case TValidationSummaryDisplayMode::SimpleList:
357
					$this->renderList($writer);
358
					break;
359
				case TValidationSummaryDisplayMode::SingleParagraph:
360
					$this->renderSingleParagraph($writer);
361
					break;
362
				case TValidationSummaryDisplayMode::BulletList:
363
					$this->renderBulletList($writer);
364
					break;
365
				case TValidationSummaryDisplayMode::HeaderOnly:
366
					$this->renderHeaderOnly($writer);
367
					break;
368
			}
369
		}
370
	}
371
372
	/**
373
	 * Render the validation summary as a simple list.
374
	 * @param string $writer the header text
375
	 * @return string summary list
376
	 */
377 View Code Duplication
	protected function renderList($writer)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
378
	{
379
		$header = $this->getHeaderText();
380
		$messages = $this->getErrorMessages();
381
		$content = '';
382
		if (strlen($header)) {
383
			$content .= $header . "<br/>\n";
384
		}
385
		foreach ($messages as $message) {
386
			$content .= "$message<br/>\n";
387
		}
388
		$writer->write($content);
0 ignored issues
show
Bug introduced by
The method write cannot be called on $writer (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
389
	}
390
391
	/**
392
	 * Render the validation summary as a paragraph.
393
	 * @param string $writer the header text
394
	 * @return string summary paragraph
395
	 */
396
	protected function renderSingleParagraph($writer)
397
	{
398
		$header = $this->getHeaderText();
399
		$messages = $this->getErrorMessages();
400
		$content = $header;
401
		foreach ($messages as $message) {
402
			$content .= ' ' . $message;
403
		}
404
		$writer->write($content);
0 ignored issues
show
Bug introduced by
The method write cannot be called on $writer (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
405
	}
406
407
	/**
408
	 * Render the validation summary as a bullet list.
409
	 * @param string $writer the header text
410
	 * @return string summary bullet list
411
	 */
412 View Code Duplication
	protected function renderBulletList($writer)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
413
	{
414
		$header = $this->getHeaderText();
415
		$messages = $this->getErrorMessages();
416
		$content = $header;
417
		if (count($messages) > 0) {
418
			$content .= "<ul>\n";
419
			foreach ($messages as $message) {
420
				$content .= '<li>' . $message . "</li>\n";
421
			}
422
			$content .= "</ul>\n";
423
		}
424
		$writer->write($content);
0 ignored issues
show
Bug introduced by
The method write cannot be called on $writer (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
425
	}
426
427
	/**
428
	 * Render the validation summary header text only.
429
	 * @param THtmlWriter $writer the writer used for the rendering purpose
430
	 */
431
	protected function renderHeaderOnly($writer)
432
	{
433
		$writer->write($this->getHeaderText());
434
	}
435
}
436