2 namespace wcf\system\form\builder\field\data\processor;
3 use wcf\system\form\builder\IFormDocument;
6 * Field data processor implementation that supports a custom processor callable.
8 * @author Matthias Schmidt
9 * @copyright 2001-2019 WoltLab GmbH
10 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
11 * @package WoltLabSuite\Core\System\Form\Builder\Field\Data\Processor
14 class CustomFormFieldDataProcessor implements IFormFieldDataProcessor {
16 * processor id primarily used for error messages
22 * callable processing the data
28 * Initializes a new CustomFormFieldDataProcessor object.
30 * @param string $id processor id primarily used for error messages, does not have to be unique
31 * @param callable $processor processor callable
33 * @throws \InvalidArgumentException if either id or processor callable are invalid
35 public function __construct($id, callable $processor) {
36 if (preg_match('~^[a-z][A-z0-9-]*$~', $id) !== 1) {
37 throw new \InvalidArgumentException("Invalid id '{$id}' given.");
42 // validate processor function
43 $parameters = (new \ReflectionFunction($processor))->getParameters();
44 if (count($parameters) !== 2) {
45 throw new \InvalidArgumentException(
46 "The processor function must expect two parameters, instead " . count($parameters) .
47 " parameter" . (count($parameters) !== 1 ? 's' : '') . " are expected."
51 /** @var \ReflectionClass $parameterClass */
52 $parameterClass = $parameters[0]->getClass();
53 if ($parameterClass === null || ($parameterClass->getName() !== IFormDocument::class && !is_subclass_of($parameterClass->getName(), IFormDocument::class))) {
54 throw new \InvalidArgumentException(
55 "The processor function's first parameter must be an instance of '" . IFormDocument::class . "', instead " .
56 ($parameterClass === null ? 'any' : "'" . $parameterClass->getName() . "'") . " parameter is expected."
59 if (!$parameters[1]->isArray()) {
60 throw new \InvalidArgumentException("The processor function's second parameter must be an array.");
63 $this->processor = $processor;
69 public function __invoke(IFormDocument $document, array $parameters) {
70 $parameters = call_user_func($this->processor, $document, $parameters);
72 if (!is_array($parameters)) {
73 throw new \UnexpectedValueException("Field data processor '{$this->id}' does not return an array.");