• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / forms / 20561735615

29 Dec 2025 12:27AM UTC coverage: 93.481% (+0.2%) from 93.237%
20561735615

push

github

dg
Container::setValues() and setDefaults() accepts array|Traversable|stdClass (BC break)

3 of 4 new or added lines in 1 file covered. (75.0%)

21 existing lines in 2 files now uncovered.

2065 of 2209 relevant lines covered (93.48%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.78
/src/Forms/Container.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\Forms;
11

12
use Nette;
13
use Nette\Utils\ArrayHash;
14
use Stringable;
15
use function array_combine, array_key_exists, array_map, array_merge, array_unique, explode, func_get_args, in_array, is_object, iterator_to_array, str_contains;
16

17

18
/**
19
 * Container for form controls.
20
 *
21
 * @property   ArrayHash $values
22
 * @property-read \Iterator $controls
23
 * @property-read Form|null $form
24
 */
25
class Container extends Nette\ComponentModel\Container implements \ArrayAccess
26
{
27
        use Nette\ComponentModel\ArrayAccess;
28

29
        public const Array = 'array';
30

31
        /**
32
         * Occurs when the form was validated
33
         * @var array<callable(self, array|object): void|callable(array|object): void>
34
         */
35
        public array $onValidate = [];
36
        protected ?ControlGroup $currentGroup = null;
37

38
        /** @var callable[]  extension methods */
39
        private static array $extMethods = [];
40
        private ?bool $validated = false;
41
        private ?string $mappedType = null;
42

43

44
        /********************* data exchange ****************d*g**/
45

46

47
        /**
48
         * Fill-in with default values.
49
         * @param  array|\Traversable|\stdClass  $values
50
         */
51
        public function setDefaults(array|object $values, bool $erase = false): static
1✔
52
        {
53
                $form = $this->getForm(throw: false);
1✔
54
                $this->setValues($values, $erase, $form?->isAnchored() && $form->isSubmitted());
1✔
55
                return $this;
1✔
56
        }
57

58

59
        /**
60
         * Fill-in with values.
61
         * @param  array|\Traversable|\stdClass  $values
62
         * @internal
63
         */
64
        public function setValues(array|object $values, bool $erase = false, bool $onlyDisabled = false): static
1✔
65
        {
66
                if (is_object($values) && !($values instanceof \Traversable || $values instanceof \stdClass)) {
1✔
NEW
67
                        trigger_error(__METHOD__ . ': argument should be array|Traversable|stdClass, ' . get_debug_type($values) . ' given.');
×
68
                }
69

70
                $values = $values instanceof \Traversable
1✔
71
                        ? iterator_to_array($values)
1✔
72
                        : (array) $values;
1✔
73

74
                foreach ($this->getComponents() as $name => $control) {
1✔
75
                        if ($control instanceof Control) {
1✔
76
                                if ((array_key_exists($name, $values) && (!$onlyDisabled || $control->isDisabled())) || $erase) {
1✔
77
                                        $control->setValue($values[$name] ?? null);
1✔
78
                                }
79
                        } elseif ($control instanceof self) {
1✔
80
                                if (isset($values[$name]) || $erase) {
1✔
81
                                        $control->setValues($values[$name] ?? [], $erase, $onlyDisabled);
1✔
82
                                }
83
                        }
84
                }
85

86
                return $this;
1✔
87
        }
88

89

90
        /**
91
         * Returns the values submitted by the form.
92
         * @param  Control[]|null  $controls
93
         */
94
        public function getValues(string|object|null $returnType = null, ?array $controls = null): object|array
1✔
95
        {
96
                $form = $this->getForm(throw: false);
1✔
97
                if ($form && ($submitter = $form->isSubmitted())) {
1✔
98
                        if ($this->validated === null) {
1✔
UNCOV
99
                                throw new Nette\InvalidStateException('You cannot call getValues() during the validation process. Use getUntrustedValues() instead.');
×
100

101
                        } elseif (!$this->isValid()) {
1✔
UNCOV
102
                                trigger_error(__METHOD__ . "() invoked but the form is not valid (form '{$this->getName()}').", E_USER_WARNING);
×
103
                        }
104

105
                        if ($controls === null && $submitter instanceof SubmitterControl) {
1✔
106
                                $controls = $submitter->getValidationScope();
1✔
107
                                if ($controls !== null && !in_array($this, $controls, strict: true)) {
1✔
108
                                        $scope = $this;
1✔
109
                                        while (($scope = $scope->getParent()) instanceof self) {
1✔
UNCOV
110
                                                if (in_array($scope, $controls, strict: true)) {
×
UNCOV
111
                                                        $controls[] = $this;
×
UNCOV
112
                                                        break;
×
113
                                                }
114
                                        }
115
                                }
116
                        }
117
                }
118

119
                return $this->getUntrustedValues($returnType, $controls);
1✔
120
        }
121

122

123
        /**
124
         * Returns the potentially unvalidated values submitted by the form.
125
         * @param  Control[]|null  $controls
126
         */
127
        public function getUntrustedValues(string|object|null $returnType = null, ?array $controls = null): object|array
1✔
128
        {
129
                if (is_object($returnType)) {
1✔
130
                        $resultObj = $returnType;
1✔
131
                        $properties = (new \ReflectionClass($resultObj))->getProperties();
1✔
132

133
                } else {
134
                        $returnType ??= $this->mappedType ?? ArrayHash::class;
1✔
135
                        $rc = new \ReflectionClass($returnType === self::Array ? \stdClass::class : $returnType);
1✔
136
                        $constructor = $rc->hasMethod('__construct') ? $rc->getMethod('__construct') : null;
1✔
137
                        if ($constructor?->getNumberOfRequiredParameters()) {
1✔
138
                                $resultObj = new \stdClass;
1✔
139
                                $properties = $constructor->getParameters();
1✔
140
                        } else {
141
                                $constructor = null;
1✔
142
                                $resultObj = $rc->newInstance();
1✔
143
                                $properties = $rc->getProperties();
1✔
144
                        }
145
                }
146

147
                $properties = array_combine(array_map(fn($p) => $p->getName(), $properties), $properties);
1✔
148

149
                foreach ($this->getComponents() as $name => $control) {
1✔
150
                        $allowed = $controls === null || in_array($this, $controls, strict: true) || in_array($control, $controls, strict: true);
1✔
151
                        $name = (string) $name;
1✔
152
                        $property = $properties[$name] ?? null;
1✔
153
                        if (
154
                                $control instanceof Control
1✔
155
                                && $allowed
1✔
156
                                && !$control->isOmitted()
1✔
157
                        ) {
158
                                $resultObj->$name = Helpers::tryEnumConversion($control->getValue(), $property);
1✔
159

160
                        } elseif ($control instanceof self) {
1✔
161
                                $type = $returnType === self::Array && !$control->mappedType
1✔
162
                                        ? self::Array
1✔
163
                                        : ($property ? Helpers::getSingleType($property) : null);
1✔
164
                                $resultObj->$name = $control->getUntrustedValues($type, $allowed ? null : $controls);
1✔
165
                        }
166
                }
167

168
                return match (true) {
169
                        isset($constructor) => new $returnType(...(array) $resultObj),
1✔
170
                        $returnType === self::Array => (array) $resultObj,
1✔
171
                        default => $resultObj,
1✔
172
                };
173
        }
174

175

176
        /** @deprecated use getUntrustedValues() */
177
        public function getUnsafeValues($returnType, ?array $controls = null)
178
        {
UNCOV
179
                return $this->getUntrustedValues($returnType, $controls);
×
180
        }
181

182

183
        public function setMappedType(string $type): static
1✔
184
        {
185
                $this->mappedType = $type;
1✔
186
                return $this;
1✔
187
        }
188

189

190
        /********************* validation ****************d*g**/
191

192

193
        /**
194
         * Is form valid?
195
         */
196
        public function isValid(): bool
197
        {
198
                if ($this->validated === null) {
1✔
UNCOV
199
                        throw new Nette\InvalidStateException('You cannot call isValid() during the validation process.');
×
200

201
                } elseif (!$this->validated) {
1✔
202
                        if ($this->getErrors()) {
1✔
203
                                return false;
1✔
204
                        }
205

206
                        $this->validate();
1✔
207
                }
208

209
                return !$this->getErrors();
1✔
210
        }
211

212

213
        /**
214
         * Performs the server side validation.
215
         * @param  (Control|self)[]|null  $controls
216
         */
217
        public function validate(?array $controls = null): void
1✔
218
        {
219
                $this->validated = null;
1✔
220
                foreach ($controls ?? $this->getComponents() as $control) {
1✔
221
                        if ($control instanceof Control || $control instanceof self) {
1✔
222
                                $control->validate();
1✔
223
                        }
224
                }
225

226
                $this->validated = true;
1✔
227

228
                foreach ($this->onValidate as $handler) {
1✔
229
                        $params = Nette\Utils\Callback::toReflection($handler)->getParameters();
1✔
230
                        $types = array_map(Helpers::getSingleType(...), $params);
1✔
231
                        $args = isset($types[0]) && !$this instanceof $types[0]
1✔
232
                                ? [$this->getUntrustedValues($types[0])]
1✔
233
                                : [$this, isset($params[1]) ? $this->getUntrustedValues($types[1]) : null];
1✔
234
                        $handler(...$args);
1✔
235
                }
236
        }
1✔
237

238

239
        /**
240
         * Returns all validation errors.
241
         */
242
        public function getErrors(): array
243
        {
244
                $errors = [];
1✔
245
                foreach ($this->getControls() as $control) {
1✔
246
                        $errors = array_merge($errors, $control->getErrors());
1✔
247
                }
248

249
                return array_unique($errors);
1✔
250
        }
251

252

253
        /********************* form building ****************d*g**/
254

255

256
        public function setCurrentGroup(?ControlGroup $group = null): static
1✔
257
        {
258
                $this->currentGroup = $group;
1✔
259
                return $this;
1✔
260
        }
261

262

263
        /**
264
         * Returns current group.
265
         */
266
        public function getCurrentGroup(): ?ControlGroup
267
        {
UNCOV
268
                return $this->currentGroup;
×
269
        }
270

271

272
        /**
273
         * Adds the specified component to the IContainer.
274
         * @throws Nette\InvalidStateException
275
         */
276
        public function addComponent(
1✔
277
                Nette\ComponentModel\IComponent $component,
278
                ?string $name,
279
                ?string $insertBefore = null,
280
        ): static
281
        {
282
                parent::addComponent($component, $name, $insertBefore);
1✔
283
                $this->currentGroup?->add($component);
1✔
284
                return $this;
1✔
285
        }
286

287

288
        /**
289
         * Iterates over all form controls.
290
         */
291
        public function getControls(): iterable
292
        {
293
                return Nette\Utils\Iterables::repeatable(function () {
1✔
294
                        foreach ($this->getComponentTree() as $component) {
1✔
295
                                if ($component instanceof Control) {
1✔
296
                                        yield $component->getName() => $component;
1✔
297
                                }
298
                        }
299
                });
1✔
300
        }
301

302

303
        /**
304
         * Returns form.
305
         * @return ($throw is true ? Form : ?Form)
306
         */
307
        public function getForm(bool $throw = true): ?Form
1✔
308
        {
309
                return $this->lookup(Form::class, $throw);
1✔
310
        }
311

312

313
        /********************* control factories ****************d*g**/
314

315

316
        /**
317
         * Adds single-line text input control to the form.
318
         */
319
        public function addText(
1✔
320
                string $name,
321
                string|Stringable|null $label = null,
322
                ?int $cols = null,
323
                ?int $maxLength = null,
324
        ): Controls\TextInput
325
        {
326
                return $this[$name] = (new Controls\TextInput($label, $maxLength))
1✔
327
                        ->setHtmlAttribute('size', $cols);
1✔
328
        }
329

330

331
        /**
332
         * Adds single-line text input control used for sensitive input such as passwords.
333
         */
334
        public function addPassword(
1✔
335
                string $name,
336
                string|Stringable|null $label = null,
337
                ?int $cols = null,
338
                ?int $maxLength = null,
339
        ): Controls\TextInput
340
        {
341
                return $this[$name] = (new Controls\TextInput($label, $maxLength))
1✔
342
                        ->setHtmlAttribute('size', $cols)
1✔
343
                        ->setHtmlType('password');
1✔
344
        }
345

346

347
        /**
348
         * Adds multi-line text input control to the form.
349
         */
350
        public function addTextArea(
1✔
351
                string $name,
352
                string|Stringable|null $label = null,
353
                ?int $cols = null,
354
                ?int $rows = null,
355
        ): Controls\TextArea
356
        {
357
                return $this[$name] = (new Controls\TextArea($label))
1✔
358
                        ->setHtmlAttribute('cols', $cols)->setHtmlAttribute('rows', $rows);
1✔
359
        }
360

361

362
        /**
363
         * Adds input for email.
364
         */
365
        public function addEmail(
1✔
366
                string $name,
367
                string|Stringable|null $label = null,
368
                int $maxLength = 255,
369
        ): Controls\TextInput
370
        {
371
                return $this[$name] = (new Controls\TextInput($label, $maxLength))
1✔
372
                        ->addRule(Form::Email);
1✔
373
        }
374

375

376
        /**
377
         * Adds input for integer.
378
         */
379
        public function addInteger(string $name, string|Stringable|null $label = null): Controls\TextInput
1✔
380
        {
381
                return $this[$name] = (new Controls\TextInput($label))
1✔
382
                        ->setNullable()
1✔
383
                        ->addRule(Form::Integer);
1✔
384
        }
385

386

387
        /**
388
         * Adds input for float.
389
         */
390
        public function addFloat(string $name, string|Stringable|null $label = null): Controls\TextInput
1✔
391
        {
392
                return $this[$name] = (new Controls\TextInput($label))
1✔
393
                        ->setNullable()
1✔
394
                        ->setHtmlType('number')
1✔
395
                        ->setHtmlAttribute('step', 'any')
1✔
396
                        ->addRule(Form::Float);
1✔
397
        }
398

399

400
        /**
401
         * Adds input for date selection.
402
         */
403
        public function addDate(string $name, string|object|null $label = null): Controls\DateTimeControl
1✔
404
        {
405
                return $this[$name] = new Controls\DateTimeControl($label, Controls\DateTimeControl::TypeDate);
1✔
406
        }
407

408

409
        /**
410
         * Adds input for time selection.
411
         */
412
        public function addTime(
1✔
413
                string $name,
414
                string|object|null $label = null,
415
                bool $withSeconds = false,
416
        ): Controls\DateTimeControl
417
        {
418
                return $this[$name] = new Controls\DateTimeControl($label, Controls\DateTimeControl::TypeTime, $withSeconds);
1✔
419
        }
420

421

422
        /**
423
         * Adds input for date and time selection.
424
         */
425
        public function addDateTime(
1✔
426
                string $name,
427
                string|object|null $label = null,
428
                bool $withSeconds = false,
429
        ): Controls\DateTimeControl
430
        {
431
                return $this[$name] = new Controls\DateTimeControl($label, Controls\DateTimeControl::TypeDateTime, $withSeconds);
1✔
432
        }
433

434

435
        /**
436
         * Adds control that allows the user to upload files.
437
         */
438
        public function addUpload(string $name, string|Stringable|null $label = null): Controls\UploadControl
1✔
439
        {
440
                return $this[$name] = new Controls\UploadControl($label, multiple: false);
1✔
441
        }
442

443

444
        /**
445
         * Adds control that allows the user to upload multiple files.
446
         */
447
        public function addMultiUpload(string $name, string|Stringable|null $label = null): Controls\UploadControl
1✔
448
        {
449
                return $this[$name] = new Controls\UploadControl($label, multiple: true);
1✔
450
        }
451

452

453
        /**
454
         * Adds hidden form control used to store a non-displayed value.
455
         */
456
        public function addHidden(string $name, $default = null): Controls\HiddenField
1✔
457
        {
458
                return $this[$name] = (new Controls\HiddenField)
1✔
459
                        ->setDefaultValue($default);
1✔
460
        }
461

462

463
        /**
464
         * Adds check box control to the form.
465
         */
466
        public function addCheckbox(string $name, string|Stringable|null $caption = null): Controls\Checkbox
1✔
467
        {
468
                return $this[$name] = new Controls\Checkbox($caption);
1✔
469
        }
470

471

472
        /**
473
         * Adds set of radio button controls to the form.
474
         */
475
        public function addRadioList(
1✔
476
                string $name,
477
                string|Stringable|null $label = null,
478
                ?array $items = null,
479
        ): Controls\RadioList
480
        {
481
                return $this[$name] = new Controls\RadioList($label, $items);
1✔
482
        }
483

484

485
        /**
486
         * Adds set of checkbox controls to the form.
487
         */
488
        public function addCheckboxList(
1✔
489
                string $name,
490
                string|Stringable|null $label = null,
491
                ?array $items = null,
492
        ): Controls\CheckboxList
493
        {
494
                return $this[$name] = new Controls\CheckboxList($label, $items);
1✔
495
        }
496

497

498
        /**
499
         * Adds select box control that allows single item selection.
500
         */
501
        public function addSelect(
1✔
502
                string $name,
503
                string|Stringable|null $label = null,
504
                ?array $items = null,
505
                ?int $size = null,
506
        ): Controls\SelectBox
507
        {
508
                return $this[$name] = (new Controls\SelectBox($label, $items))
1✔
509
                        ->setHtmlAttribute('size', $size > 1 ? $size : null);
1✔
510
        }
511

512

513
        /**
514
         * Adds select box control that allows multiple item selection.
515
         */
516
        public function addMultiSelect(
1✔
517
                string $name,
518
                string|Stringable|null $label = null,
519
                ?array $items = null,
520
                ?int $size = null,
521
        ): Controls\MultiSelectBox
522
        {
523
                return $this[$name] = (new Controls\MultiSelectBox($label, $items))
1✔
524
                        ->setHtmlAttribute('size', $size > 1 ? $size : null);
1✔
525
        }
526

527

528
        /**
529
         * Adds color picker.
530
         */
531
        public function addColor(string $name, string|Stringable|null $label = null): Controls\ColorPicker
1✔
532
        {
533
                return $this[$name] = new Controls\ColorPicker($label);
1✔
534
        }
535

536

537
        /**
538
         * Adds button used to submit form.
539
         */
540
        public function addSubmit(string $name, string|Stringable|null $caption = null): Controls\SubmitButton
1✔
541
        {
542
                return $this[$name] = new Controls\SubmitButton($caption);
1✔
543
        }
544

545

546
        /**
547
         * Adds push buttons with no default behavior.
548
         */
549
        public function addButton(string $name, string|Stringable|null $caption = null): Controls\Button
1✔
550
        {
551
                return $this[$name] = new Controls\Button($caption);
1✔
552
        }
553

554

555
        /**
556
         * Adds graphical button used to submit form.
557
         * @param  string|null  $src  URI of the image
558
         * @param  string|null  $alt  alternate text for the image
559
         */
560
        public function addImageButton(string $name, ?string $src = null, ?string $alt = null): Controls\ImageButton
1✔
561
        {
562
                return $this[$name] = new Controls\ImageButton($src, $alt);
1✔
563
        }
564

565

566
        /** @deprecated  use addImageButton() */
567
        public function addImage(): Controls\ImageButton
568
        {
UNCOV
569
                return $this->addImageButton(...func_get_args());
×
570
        }
571

572

573
        /**
574
         * Adds naming container to the form.
575
         */
576
        public function addContainer(string|int $name): self
1✔
577
        {
578
                $control = new self;
1✔
579
                $control->currentGroup = $this->currentGroup;
1✔
580
                $this->currentGroup?->add($control);
1✔
581
                return $this[$name] = $control;
1✔
582
        }
583

584

585
        /********************* extension methods ****************d*g**/
586

587

588
        public function __call(string $name, array $args)
1✔
589
        {
590
                if (isset(self::$extMethods[$name])) {
1✔
591
                        return (self::$extMethods[$name])($this, ...$args);
1✔
592
                }
593

UNCOV
594
                return parent::__call($name, $args);
×
595
        }
596

597

598
        public static function extensionMethod(string $name, /*callable*/ $callback): void
1✔
599
        {
600
                if (str_contains($name, '::')) { // back compatibility
1✔
UNCOV
601
                        [, $name] = explode('::', $name);
×
602
                }
603

604
                self::$extMethods[$name] = $callback;
1✔
605
        }
1✔
606

607

608
        /**
609
         * Prevents cloning.
610
         */
611
        public function __clone()
612
        {
UNCOV
613
                throw new Nette\NotImplementedException('Form cloning is not supported yet.');
×
614
        }
615
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc