Apply PSR-12 code style (#3886)
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / system / form / builder / field / validation / FormFieldValidator.class.php
CommitLineData
ee553688 1<?php
a9229942 2
ee553688 3namespace wcf\system\form\builder\field\validation;
a9229942 4
ee553688
MS
5use wcf\system\form\builder\field\IFormField;
6
7/**
8 * Validates the value of a form field.
a9229942
TD
9 *
10 * @author Matthias Schmidt
11 * @copyright 2001-2019 WoltLab GmbH
12 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
13 * @package WoltLabSuite\Core\System\Form\Builder\Field\Validation
14 * @since 5.2
ee553688 15 */
a9229942
TD
16class FormFieldValidator implements IFormFieldValidator
17{
18 /**
19 * id of the validator that has to be unique for each field
20 * @var
21 */
22 protected $id;
23
24 /**
25 * validation function
26 * @var callable
27 */
28 protected $validator;
29
30 /**
31 * @inheritDoc
32 */
33 public function __construct($id, callable $validator)
34 {
35 static::validateId($id);
36
37 $this->id = $id;
38
39 // validate validation function
40 $parameters = (new \ReflectionFunction($validator))->getParameters();
41 if (\count($parameters) !== 1) {
42 throw new \InvalidArgumentException("The validation function must expect one parameter, instead " . \count($parameters) . " parameters are expected.");
43 }
44 /** @var \ReflectionType $parameterType */
45 $parameterType = $parameters[0]->getType();
46 if (
47 !(
48 $parameterType instanceof \ReflectionNamedType
49 && (
50 $parameterType->getName() === IFormField::class
51 || \is_subclass_of($parameterType->getName(), IFormField::class)
52 )
53 )
54 ) {
55 throw new \InvalidArgumentException(
56 "The validation function's parameter must be an instance of '" . IFormField::class . "', instead "
57 . @($parameterType === null ? 'any' : "'" . $parameterType . "'") . " parameter is expected."
58 );
59 }
60
61 $this->validator = $validator;
62 }
63
64 /**
65 * @inheritDoc
66 */
67 public function __invoke(IFormField $field)
68 {
69 \call_user_func($this->validator, $field);
70 }
71
72 /**
73 * @inheritDoc
74 */
75 public function getId()
76 {
77 return $this->id;
78 }
79
80 /**
81 * @inheritDoc
82 */
83 public static function validateId($id)
84 {
85 if (\preg_match('~^[a-z][A-z0-9-]*$~', $id) !== 1) {
86 throw new \InvalidArgumentException("Invalid id '{$id}' given.");
87 }
88 }
ee553688 89}