1
|
|
|
<?php |
2
|
|
|
namespace DERHANSEN\SfEventMgt\ViewHelpers\Validation; |
3
|
|
|
|
4
|
|
|
/* |
5
|
|
|
* This file is part of the Extension "sf_event_mgt" for TYPO3 CMS. |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please read the |
8
|
|
|
* LICENSE.txt file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
use DERHANSEN\SfEventMgt\Domain\Model\Registration\Field; |
12
|
|
|
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* ViewHelper to render a given class when a field has validation errors |
16
|
|
|
*/ |
17
|
|
|
class ErrorClassViewHelper extends AbstractViewHelper |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Initialize arguments |
21
|
|
|
*/ |
22
|
|
|
public function initializeArguments() |
23
|
|
|
{ |
24
|
|
|
$this->registerArgument('fieldname', 'string', 'A fieldname to be checked', false); |
25
|
|
|
$this->registerArgument('registrationField', 'object', 'A registration field record', false); |
26
|
|
|
$this->registerArgument('class', 'string', 'Classname if the field has an error', false, 'error-class'); |
27
|
|
|
parent::initializeArguments(); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @return string |
32
|
|
|
*/ |
33
|
|
|
public function render() |
34
|
|
|
{ |
35
|
|
|
$result = ''; |
36
|
|
|
$validationErrors = $this->getValidationErrors(); |
37
|
|
|
|
38
|
|
|
if (isset($this->arguments['fieldname'])) { |
39
|
|
|
$fieldname = 'registration.' . $this->arguments['fieldname']; |
40
|
|
|
} elseif (isset($this->arguments['registrationField']) && |
41
|
|
|
$this->arguments['registrationField'] instanceof Field) { |
42
|
|
|
$fieldname = 'registration.fields.' . $this->arguments['registrationField']->getUid(); |
43
|
|
|
} else { |
44
|
|
|
return ''; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
foreach ($validationErrors as $validationFieldName => $fieldValidationErrors) { |
48
|
|
|
if ($validationFieldName === $fieldname) { |
49
|
|
|
$result = $this->arguments['class']; |
50
|
|
|
break; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
return $result; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
|
|
protected function getValidationErrors() |
60
|
|
|
{ |
61
|
|
|
$validationResults = $this->renderingContext->getControllerContext() |
|
|
|
|
62
|
|
|
->getRequest()->getOriginalRequestMappingResults(); |
63
|
|
|
return $validationResults->getFlattenedErrors(); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: