Completed
Push — master ( a7c9f5...0b7c41 )
by Lars
01:24
created

Validator   F

Complexity

Total Complexity 80

Size/Duplication

Total Lines 613
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 90.83%

Importance

Changes 0
Metric Value
wmc 80
lcom 1
cbo 12
dl 0
loc 613
ccs 198
cts 218
cp 0.9083
rs 3.9888
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A addCustomFilter() 0 4 1
A addCustomRule() 0 4 1
B applyFilter() 0 48 6
A autoSelectRuleByInputType() 0 18 1
A getAllFilters() 0 4 1
A getAllRules() 0 4 1
C getCurrentFieldValue() 0 54 11
A getHtml() 0 4 1
A getRequiredRules() 0 4 1
A getTranslator() 0 4 1
C parseHtmlDomForRules() 0 48 8
A parseInputForFilter() 0 15 3
F parseInputForRules() 0 105 20
A setTranslator() 0 6 1
D validate() 0 137 22

How to fix   Complexity   

Complex Class

Complex classes like Validator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Validator, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\HtmlFormValidator;
6
7
use Respect\Validation\Exceptions\ComponentException;
8
use Respect\Validation\Exceptions\NestedValidationException;
9
use Respect\Validation\Exceptions\ValidationException;
10
use Respect\Validation\Factory;
11
use Respect\Validation\Rules\AbstractRule;
12
use Respect\Validation\Rules\Date;
13
use Respect\Validation\Rules\Email;
14
use Respect\Validation\Rules\HexRgbColor;
15
use Respect\Validation\Rules\Numeric;
16
use Respect\Validation\Rules\Phone;
17
use Respect\Validation\Rules\Url;
18
use Symfony\Component\CssSelector\Exception\SyntaxErrorException;
19
use voku\helper\HtmlDomParser;
20
use voku\helper\SimpleHtmlDom;
21
use voku\helper\UTF8;
22
use voku\HtmlFormValidator\Exceptions\NoValidationRule;
23
use voku\HtmlFormValidator\Exceptions\UnknownFilter;
24
use voku\HtmlFormValidator\Exceptions\UnknownValidationRule;
25
26
class Validator
27
{
28
  /**
29
   * @var HtmlDomParser
30
   */
31
  private $formDocument;
32
33
  /**
34
   * @var string[][]
35
   */
36
  private $rules = [];
37
38
  /**
39
   * @var string[][]
40
   */
41
  private $required_rules = [];
42
43
  /**
44
   * @var string[][]
45
   */
46
  private $filters = [];
47
48
  /**
49
   * @var callable[]
50
   */
51
  private $filters_custom = [];
52
53
  /**
54
   * @var callable|null
55
   */
56
  private $translator;
57
58
  /**
59
   * @var ValidatorRulesManager
60
   */
61
  private $validatorRulesManager;
62
63
  /**
64
   * @var string
65
   */
66
  private $selector;
67
68
  /**
69
   * @param string $formHTML
70
   * @param string $selector
71
   */
72 22
  public function __construct($formHTML, $selector = '')
73
  {
74 22
    $this->validatorRulesManager = new ValidatorRulesManager();
75
76 22
    $this->formDocument = HtmlDomParser::str_get_html($formHTML);
0 ignored issues
show
Unused Code introduced by
The call to HtmlDomParser::str_get_html() has too many arguments starting with $formHTML.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
77 22
    $this->selector = $selector;
78
79 22
    $this->parseHtmlDomForRules();
80 22
  }
81
82
  /**
83
   * @param string   $name   <p>A name for the "data-filter"-attribute in the dom.</p>
84
   * @param callable $filter <p>A custom filter.</p>
85
   */
86 1
  public function addCustomFilter(string $name, callable $filter)
87
  {
88 1
    $this->filters_custom[$name] = $filter;
89 1
  }
90
91
  /**
92
   * @param string              $name      <p>A name for the "data-validator"-attribute in the dom.</p>
93
   * @param string|AbstractRule $validator <p>A custom validation class.</p>
94
   */
95 3
  public function addCustomRule(string $name, $validator)
96
  {
97 3
    $this->validatorRulesManager->addCustomRule($name, $validator);
98 3
  }
99
100
  /**
101
   * @param mixed  $currentFieldData
102
   * @param string $fieldFilter
103
   *
104
   * @throws UnknownFilter
105
   *
106
   * @return mixed|string|null
107
   */
108 5
  private function applyFilter($currentFieldData, string $fieldFilter)
109
  {
110 5
    if ($currentFieldData === null) {
111 1
      return null;
112
    }
113
114
    //
115
    // fixed filters
116
    //
117
118
    switch ($fieldFilter) {
119 5
      case 'escape':
120 4
        return \htmlentities($currentFieldData, ENT_QUOTES | ENT_HTML5, 'UTF-8');
121
    }
122
123
    //
124
    // get arguments
125
    //
126
127 5
    list($fieldFilter, $fieldFilterArgs) = ValidatorHelpers::getArgsFromString($fieldFilter);
128
129 5
    $currentFieldData = (array)$currentFieldData;
130 5
    foreach ($fieldFilterArgs as $arg) {
131 1
      $currentFieldData[] = $arg;
132
    }
133
134
    //
135
    // custom filters
136
    //
137
138 5
    if (isset($this->filters_custom[$fieldFilter])) {
139 1
      return \call_user_func_array($this->filters_custom[$fieldFilter], $currentFieldData);
140
    }
141
142
    //
143
    // dynamic filters
144
    //
145
146 4
    if (method_exists(UTF8::class, $fieldFilter)) {
147 4
      $currentFieldData = \call_user_func_array([UTF8::class, $fieldFilter], $currentFieldData);
148
    } else {
149
      throw new UnknownFilter(
150
          'No filter available for "' . $fieldFilter . '"'
151
      );
152
    }
153
154 4
    return $currentFieldData;
155
  }
156
157
  /**
158
   * @param string $type
159
   *
160
   * @return string|null
161
   */
162 3
  public function autoSelectRuleByInputType(string $type)
163
  {
164
    $matchingArray = [
165 3
        'email'  => Email::class,
166
        'url'    => Url::class,
167
        'color'  => HexRgbColor::class,
168
        'number' => Numeric::class,
169
        'date'   => Date::class,
170
        'range'  => Numeric::class,
171
        'tel'    => Phone::class,
172
        // -> this need localisation e.g. for german / us / etc.
173
        //'time'   => Time::class,
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
174
        //'month'  => Month::class,
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
175
        //'week'   => Week::class,
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
176
    ];
177
178 3
    return $matchingArray[$type] ?? null;
179
  }
180
181
  /**
182
   * Get the filters that will be applied.
183
   *
184
   * @return string[][]
185
   */
186 1
  public function getAllFilters(): array
187
  {
188 1
    return $this->filters;
189
  }
190
191
  /**
192
   * Get the rules that will be applied.
193
   *
194
   * @return string[][]
195
   */
196 15
  public function getAllRules(): array
197
  {
198 15
    return $this->rules;
199
  }
200
201
  /**
202
   * @param array  $formValues
203
   * @param string $field
204
   *
205
   * @return mixed|null
206
   */
207 18
  private function getCurrentFieldValue(array $formValues, string $field)
208
  {
209 18
    $fieldArrayPos = UTF8::strpos($field, '[');
210 18
    if ($fieldArrayPos !== false) {
211 3
      $fieldStart = UTF8::substr($field, 0, $fieldArrayPos);
212 3
      $fieldArray = UTF8::substr($field, $fieldArrayPos);
213 3
      $fieldHelperChar = '';
214 3
      $fieldArrayTmp = preg_replace_callback(
215 3
          '/\[([^\]]+)\]/',
216 3
          function ($match) use ($fieldHelperChar) {
217 3
            return $match[1] . $fieldHelperChar;
218 3
          },
219 3
          $fieldArray
220
      );
221 3
      $fieldArrayTmp = explode($fieldHelperChar, trim($fieldArrayTmp, $fieldHelperChar));
222
223 3
      $i = 0;
224 3
      $fieldHelper = [];
225 3
      foreach ($fieldArrayTmp as $fieldArrayTmpInner) {
226 3
        $fieldHelper[$i] = $fieldArrayTmpInner;
227
228 3
        $i++;
229
      }
230
231 3
      $currentFieldValue = null;
232
233
      switch ($i) {
234 3
        case 4:
235
          if (isset($formValues[$fieldStart][$fieldHelper[0]][$fieldHelper[1]][$fieldHelper[2]][$fieldHelper[3]])) {
236
            $currentFieldValue = $formValues[$fieldStart][$fieldHelper[0]][$fieldHelper[1]][$fieldHelper[2]][$fieldHelper[3]];
237
          }
238
          break;
239 3
        case 3:
240
          if (isset($formValues[$fieldStart][$fieldHelper[0]][$fieldHelper[1]][$fieldHelper[2]])) {
241
            $currentFieldValue = $formValues[$fieldStart][$fieldHelper[0]][$fieldHelper[1]][$fieldHelper[2]];
242
          }
243
          break;
244 3
        case 2:
245 1
          if (isset($formValues[$fieldStart][$fieldHelper[0]][$fieldHelper[1]])) {
246 1
            $currentFieldValue = $formValues[$fieldStart][$fieldHelper[0]][$fieldHelper[1]];
247
          }
248 1
          break;
249 2
        case 1:
250 2
          if (isset($formValues[$fieldStart][$fieldHelper[0]])) {
251 2
            $currentFieldValue = $formValues[$fieldStart][$fieldHelper[0]];
252
          }
253 3
          break;
254
      }
255
    } else {
256 15
      $currentFieldValue = $formValues[$field] ?? null;
257
    }
258
259 18
    return $currentFieldValue;
260
  }
261
262
  /**
263
   * @return string
264
   */
265 3
  public function getHtml(): string
266
  {
267 3
    return $this->formDocument->html();
268
  }
269
270
  /**
271
   * Get the required rules that will be applied.
272
   *
273
   * @return string[][]
274
   */
275
  public function getRequiredRules(): array
276
  {
277
    return $this->required_rules;
278
  }
279
280
  /**
281
   * @return callable|null
282
   */
283 17
  public function getTranslator()
284
  {
285 17
    return $this->translator;
286
  }
287
288
  /**
289
   * Find the first form on page or via css-selector, and parse <input>-elements.
290
   *
291
   * @return bool
292
   */
293 22
  public function parseHtmlDomForRules(): bool
294
  {
295
    // init
296 22
    $this->rules = [];
297 22
    $inputForm = [];
298
299 22
    if ($this->selector) {
300 2
      $forms = $this->formDocument->find($this->selector);
301
    } else {
302 20
      $forms = $this->formDocument->find('form');
303
    }
304
305 22
    if (\count($forms) === 0) {
306 1
      return false;
307
    }
308
309
    // get the first form
310 21
    $form = $forms[0];
311
312
    // get the from-id
313 21
    if ($form->id) {
314 14
      $formHelperId = $form->id;
315
    } else {
316 7
      $formHelperId = \uniqid('html-form-validator-tmp', true);
317
    }
318
319 21
    $formTagSelector = 'input, textarea, select';
320
321
    // get the <input>-elements from the form
322 21
    $inputFromFields = $form->find($formTagSelector);
323 21
    foreach ($inputFromFields as $inputFormField) {
324 21
      $this->parseInputForRules($inputFormField, $formHelperId, $form);
325 21
      $this->parseInputForFilter($inputFormField, $formHelperId);
326
    }
327
328
    // get the <input>-elements with a matching form="id"
329 21
    if (\strpos($formHelperId, 'html-form-validator-tmp') !== 0) {
330 14
      $inputFromFieldsTmpAll = $this->formDocument->find($formTagSelector);
331 14
      foreach ($inputFromFieldsTmpAll as $inputFromFieldTmp) {
0 ignored issues
show
Bug introduced by
The expression $inputFromFieldsTmpAll of type array<integer,object<vok...leHtmlDomNodeInterface> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
332 14
        if ($inputFromFieldTmp->form == $formHelperId) {
333 1
          $this->parseInputForRules($inputFromFieldTmp, $formHelperId);
334 14
          $this->parseInputForFilter($inputFromFieldTmp, $formHelperId);
335
        }
336
      }
337
    }
338
339 21
    return (\count($inputForm) >= 0);
340
  }
341
342
  /**
343
   * Determine if element has filter attributes, and save the given filter.
344
   *
345
   * @param SimpleHtmlDom $inputField
346
   * @param string        $formHelperId
347
   */
348 21
  private function parseInputForFilter(SimpleHtmlDom $inputField, string $formHelperId)
349
  {
350 21
    if (!$inputField->hasAttribute('data-filter')) {
351 21
      return;
352
    }
353
354 6
    $inputName = $inputField->getAttribute('name');
355 6
    $inputFilter = $inputField->getAttribute('data-filter');
356
357 6
    if (!$inputFilter) {
358 1
      $inputFilter = 'htmlentities';
359
    }
360
361 6
    $this->filters[$formHelperId][$inputName] = $inputFilter;
362 6
  }
363
364
365
  /**
366
   * Determine if element has validator attributes, and save the given rule.
367
   *
368
   * @param SimpleHtmlDom      $formField
369
   * @param string             $formHelperId
370
   * @param SimpleHtmlDom|null $form
371
   */
372 21
  private function parseInputForRules(SimpleHtmlDom $formField, string $formHelperId, SimpleHtmlDom $form = null)
373
  {
374 21
    if (!$formField->hasAttribute('data-validator')) {
375 14
      return;
376
    }
377
378 20
    $inputName = $formField->getAttribute('name');
379 20
    $inputType = $formField->getAttribute('type');
380 20
    $inputPattern = $formField->getAttribute('pattern');
381 20
    $inputRule = $formField->getAttribute('data-validator');
382
383 20
    $inputMinLength = $formField->getAttribute('minlength');
384 20
    $inputMaxLength = $formField->getAttribute('maxlength');
385
386 20
    $inputMin = $formField->getAttribute('min');
387 20
    $inputMax = $formField->getAttribute('max');
388
389 20
    if (strpos($inputRule, 'auto') !== false) {
390
391
      //
392
      // select default rule by input-type
393
      //
394
395 4
      if ($inputType) {
396 3
        $selectedRule = $this->autoSelectRuleByInputType($inputType);
397 3
        if ($selectedRule) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $selectedRule of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
398 3
          $inputRule .= '|' . $selectedRule;
399
        }
400
      }
401
402
      //
403
      // html5 pattern to regex
404
      //
405
406 4
      if ($inputPattern) {
407 1
        $inputRule .= '|regex(/' . $inputPattern . '/)';
408
      }
409
410
      //
411
      // min- / max values
412
      //
413
414 4
      if ($inputMinLength) {
415
        $inputRule .= '|minLength(' . serialize($inputMinLength) . ')';
416
      }
417
418 4
      if ($inputMaxLength) {
419
        $inputRule .= '|maxLength(' . serialize($inputMaxLength) . ')';
420
      }
421
422 4
      if ($inputMin) {
423
        $inputRule .= '|min(' . serialize($inputMin) . ')';
424
      }
425
426 4
      if ($inputMax) {
427
        $inputRule .= '|max(' . serialize($inputMax) . ')';
428
      }
429
430
    }
431
432 20
    if (strpos($inputRule, 'strict') !== false) {
433
434 3
      if ($formField->tag === 'select') {
435
436 1
        $selectableValues = [];
437 1
        foreach ($formField->getElementsByTagName('option') as $option) {
438 1
          $selectableValues[] = $option->getNode()->nodeValue;
439
        }
440 1
        $inputRule .= '|in(' . serialize($selectableValues) . ')';
441
442
      } else if (
443
          (
444 2
              $inputType == 'checkbox'
445
              ||
446 2
              $inputType == 'radio'
447
          )
448
          &&
449 2
          $form) {
450
451 2
        $selectableValues = [];
452
453
        try {
454 2
          $formFieldNames = $form->find('[name=' . $formField->name . ']');
455
        } catch (SyntaxErrorException $syntaxErrorException) {
456
          $formFieldNames = null;
457
          // TODO@me -> can the symfony CssSelectorConverter use array-name-attributes?
458
        }
459
460 2
        if ($formFieldNames) {
461 2
          foreach ($formFieldNames as $formFieldName) {
0 ignored issues
show
Bug introduced by
The expression $formFieldNames of type array<integer,object<vok...leHtmlDomNodeInterface> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
462 2
            $selectableValues[] = $formFieldName->value;
463
          }
464
        }
465
466 2
        $inputRule .= '|in(' . serialize($selectableValues) . ')';
467
468
      }
469
    }
470
471 20
    if ($formField->hasAttribute('required')) {
472 18
      $this->required_rules[$formHelperId][$inputName] = $inputRule;
473
    }
474
475 20
    $this->rules[$formHelperId][$inputName] = $inputRule;
476 20
  }
477
478
  /**
479
   * @param callable $translator
480
   *
481
   * @return Validator
482
   */
483 1
  public function setTranslator(callable $translator): Validator
484
  {
485 1
    $this->translator = $translator;
486
487 1
    return $this;
488
  }
489
490
  /**
491
   * Loop the form data through form rules.
492
   *
493
   * @param array $formValues
494
   * @param bool  $useNoValidationRuleException
495
   *
496
   * @throws UnknownValidationRule
497
   *
498
   * @return ValidatorResult
499
   */
500 20
  public function validate(array $formValues, $useNoValidationRuleException = false): ValidatorResult
501
  {
502
    if (
503 20
        $useNoValidationRuleException === true
504
        &&
505 20
        \count($this->rules) === 0
506
    ) {
507 1
      throw new NoValidationRule(
508 1
          'No rules defined in the html.'
509
      );
510
    }
511
512
    // init
513 19
    $validatorResult = new ValidatorResult($this->formDocument);
514
515 19
    foreach ($this->rules as $formHelperId => $formFields) {
516 18
      foreach ($formFields as $field => $fieldRuleOuter) {
517
518 18
        $currentFieldValue = $this->getCurrentFieldValue($formValues, $field);
519
520
        //
521
        // use the filter
522
        //
523
524 18
        if (isset($this->filters[$formHelperId][$field])) {
525 5
          $filtersOuter = $this->filters[$formHelperId][$field];
526 5
          $fieldFilters = preg_split("/\|+(?![^\(]*\))/", $filtersOuter);
527
528 5
          foreach ($fieldFilters as $fieldFilter) {
529
530 5
            if (!$fieldFilter) {
531
              continue;
532
            }
533
534 5
            $currentFieldValue = $this->applyFilter($currentFieldValue, $fieldFilter);
535
          }
536
        }
537
538
        //
539
        // save the new values into the result-object
540
        //
541
542 18
        $validatorResult->setValues($field, $currentFieldValue);
543
544
        //
545
        // skip validation, if there was no value and validation is not required
546
        //
547
548
        if (
549 18
            $currentFieldValue === null
550
            &&
551 18
            !isset($this->required_rules[$formHelperId][$field])
552
        ) {
553 3
          continue;
554
        }
555
556
        //
557
        // use the validation rules from the dom
558
        //
559
560 18
        $fieldRules = preg_split("/\|+(?![^\(?:]*\))/", $fieldRuleOuter);
561
562 18
        foreach ($fieldRules as $fieldRule) {
563
564 18
          if (!$fieldRule) {
565
            continue;
566
          }
567
568 18
          $validationClassArray = $this->validatorRulesManager->getClassViaAlias($fieldRule);
569
570 18
          if ($validationClassArray['object']) {
571 1
            $validationClass = $validationClassArray['object'];
572 18
          } else if ($validationClassArray['class']) {
573 18
            $validationClass = $validationClassArray['class'];
574
          } else {
575
            $validationClass = null;
576
          }
577
578 18
          $validationClassArgs = $validationClassArray['classArgs'] ?? null;
579
580 18
          if ($validationClass instanceof AbstractRule) {
581
582 1
            $respectValidator = $validationClass;
583
584
          } else {
585
586
            try {
587 18
              $respectValidatorFactory = new Factory();
588 18
              $respectValidatorFactory->prependRulePrefix('voku\\HtmlFormValidator\\Rules');
589
590 18
              if ($validationClassArgs !== null) {
591 9
                $respectValidator = $respectValidatorFactory->rule($validationClass, $validationClassArgs);
592
              } else {
593 18
                $respectValidator = $respectValidatorFactory->rule($validationClass);
594
              }
595
596 1
            } catch (ComponentException $componentException) {
597 1
              throw new UnknownValidationRule(
598 1
                  'No rule defined for: ' . $field . ' (rule: ' . $fieldRule . ' | class: ' . $validationClass . ')',
599 1
                  500,
600 1
                  $componentException
601
              );
602
            }
603
604
          }
605
606 17
          $hasPassed = false;
607 17
          $translator = $this->getTranslator();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $translator is correct as $this->getTranslator() (which targets voku\HtmlFormValidator\Validator::getTranslator()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
608
609
          try {
610 17
            $hasPassed = $respectValidator->assert($currentFieldValue);
611 12
          } catch (NestedValidationException $nestedValidationException) {
612
613 1
            if ($translator) {
614
              $nestedValidationException->setParam('translator', $translator);
615
            }
616
617 1
            $validatorResult->setError($field, $nestedValidationException->getFullMessage());
618 11
          } catch (ValidationException $validationException) {
619
620 11
            if ($translator) {
621 1
              $validationException->setParam('translator', $translator);
622
            }
623
624 11
            $validatorResult->setError($field, $validationException->getMainMessage());
625
          }
626
627 17
          if ($hasPassed === true) {
628 17
            continue;
629
          }
630
631
        }
632
      }
633
    }
634
635 18
    return $validatorResult;
636
  }
637
638
}
639