Completed
Push — develop ( 896e3e...cec796 )
by Torben
22s queued 14s
created

RegistrationValidator   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 139
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 61
c 3
b 0
f 0
dl 0
loc 139
rs 10
wmc 22

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getValidator() 0 16 3
A isSpamCheckFailed() 0 13 1
A getRequest() 0 3 1
A validateDefaultFields() 0 26 6
A __construct() 0 8 1
B isValid() 0 28 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
7
 *
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
namespace DERHANSEN\SfEventMgt\Validation\Validator;
13
14
use DERHANSEN\SfEventMgt\Domain\Model\Registration;
15
use DERHANSEN\SfEventMgt\Service\SpamCheckService;
16
use DERHANSEN\SfEventMgt\SpamChecks\Exceptions\SpamCheckNotFoundException;
17
use Psr\Http\Message\ServerRequestInterface;
18
use TYPO3\CMS\Core\Utility\ArrayUtility;
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\ArrayUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\GeneralUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
21
use TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator;
22
use TYPO3\CMS\Extbase\Validation\Validator\BooleanValidator;
23
use TYPO3\CMS\Extbase\Validation\Validator\EmailAddressValidator;
24
use TYPO3\CMS\Extbase\Validation\Validator\NotEmptyValidator;
25
26
/**
27
 * RegistrationValidator
28
 */
29
class RegistrationValidator extends AbstractValidator
30
{
31
    protected ConfigurationManagerInterface $configurationManager;
32
    protected array $settings;
33
34
    public function __construct()
35
    {
36
        $this->configurationManager = GeneralUtility::makeInstance(ConfigurationManagerInterface::class);
37
38
        $this->settings = $this->configurationManager->getConfiguration(
39
            ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS,
40
            'SfEventMgt',
41
            'Pieventregistration'
42
        );
43
    }
44
45
    /**
46
     * Validates the given registration according to required fields set in plugin
47
     * settings. For boolean fields, the booleanValidator is used and it is assumed,
48
     * that boolean fields must have the value "TRUE" (for checkboxes)
49
     *
50
     * @param Registration $value Registration
51
     */
52
    protected function isValid(mixed $value): void
53
    {
54
        $spamSettings = $this->settings['registration']['spamCheck'] ?? [];
55
        if ((bool)($spamSettings['enabled'] ?? false) && $this->isSpamCheckFailed($value, $spamSettings)) {
56
            $message = $this->translateErrorMessage('registration.spamCheckFailed', 'SfEventMgt');
57
            $this->addErrorForProperty('spamCheck', $message, 1578855253);
58
59
            return;
60
        }
61
62
        $this->validateDefaultFields($value);
63
64
        // If no required fields are set, then the registration is valid
65
        if (!isset($this->settings['registration']['requiredFields']) ||
66
            $this->settings['registration']['requiredFields'] === ''
67
        ) {
68
            return;
69
        }
70
71
        $requiredFields = array_map('trim', explode(',', $this->settings['registration']['requiredFields']));
72
73
        foreach ($requiredFields as $requiredField) {
74
            if ($requiredField !== '' && $value->_hasProperty($requiredField)) {
75
                $validator = $this->getValidator(gettype($value->_getProperty($requiredField)), $requiredField);
76
                $validationResult = $validator->validate($value->_getProperty($requiredField));
77
                if ($validationResult->hasErrors()) {
78
                    foreach ($validationResult->getErrors() as $error) {
79
                        $this->result->forProperty($requiredField)->addError($error);
80
                    }
81
                }
82
            }
83
        }
84
    }
85
86
    /**
87
     * Validates the default fields of a registration, that must be filled out. Since domain object validation
88
     * did not work as expected with registration fields (domain object validation results completely ignored)
89
     * this own validation is done
90
     *
91
     * Checks:
92
     * - firstname: NotEmpty
93
     * - lastname: NotEmpty
94
     * - email: NotEmpty, EmailAddress
95
     */
96
    protected function validateDefaultFields(Registration $value): bool
97
    {
98
        $result = true;
99
100
        $defaultFields = ['firstname', 'lastname', 'email'];
101
        foreach ($defaultFields as $defaultField) {
102
            $validator = new NotEmptyValidator();
103
            $validationResult = $validator->validate($value->_getProperty($defaultField));
104
            if ($validationResult->hasErrors()) {
105
                $result = false;
106
                foreach ($validationResult->getErrors() as $error) {
107
                    $this->result->forProperty($defaultField)->addError($error);
108
                }
109
            }
110
        }
111
112
        $validator = new EmailAddressValidator();
113
        $validationResult = $validator->validate($value->_getProperty('email'));
114
        if ($validationResult->hasErrors()) {
115
            $result = false;
116
            foreach ($validationResult->getErrors() as $error) {
117
                $this->result->forProperty('email')->addError($error);
118
            }
119
        }
120
121
        return $result;
122
    }
123
124
    /**
125
     * Processes the spam check and returns, if it failed or not
126
     *
127
     * @throws SpamCheckNotFoundException
128
     */
129
    protected function isSpamCheckFailed(Registration $registration, array $settings): bool
130
    {
131
        $pluginKey = 'tx_sfeventmgt_pieventregistration';
132
        $getMergedWithPost = $this->getRequest()->getQueryParams()[$pluginKey];
133
        ArrayUtility::mergeRecursiveWithOverrule($getMergedWithPost, $this->getRequest()->getParsedBody()[$pluginKey] ?? []);
134
135
        $spamCheckService = new SpamCheckService(
136
            $registration,
137
            $settings,
138
            $getMergedWithPost
139
        );
140
141
        return $spamCheckService->isSpamCheckFailed();
142
    }
143
144
    /**
145
     * Returns a validator object depending on the given type of the property
146
     */
147
    protected function getValidator(string $type, string $field): AbstractValidator
148
    {
149
        switch ($type) {
150
            case 'boolean':
151
                $validator = new BooleanValidator();
152
                $validator->setOptions(['is' => true]);
153
                break;
154
            default:
155
                if ($field === 'captcha') {
156
                    $validator = new CaptchaValidator();
157
                } else {
158
                    $validator = new NotEmptyValidator();
159
                }
160
        }
161
162
        return $validator;
163
    }
164
165
    protected function getRequest(): ServerRequestInterface
166
    {
167
        return $GLOBALS['TYPO3_REQUEST'];
168
    }
169
}
170