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

nette / forms / 8860576145

27 Apr 2024 02:35PM UTC coverage: 93.067% (-0.05%) from 93.113%
8860576145

push

github

dg
added HTML attribute data-nette-error

1 of 1 new or added line in 1 file covered. (100.0%)

33 existing lines in 5 files now uncovered.

2094 of 2250 relevant lines covered (93.07%)

0.93 hits per line

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

90.0
/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

16

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

28
        public const Array = 'array';
29

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

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

42

43
        /********************* data exchange ****************d*g**/
44

45

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

57

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

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

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

85
                return $this;
1✔
86
        }
87

88

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

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

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

118
                if ($returnType === true) {
1✔
UNCOV
119
                        trigger_error(static::class . '::' . __FUNCTION__ . "(true) is deprecated, use getValues('array').", E_USER_DEPRECATED);
×
UNCOV
120
                        $returnType = self::Array;
×
121
                }
122

123
                return $this->getUntrustedValues($returnType, $controls);
1✔
124
        }
125

126

127
        /**
128
         * Returns the potentially unvalidated values submitted by the form.
129
         * @param  Control[]|null  $controls
130
         */
131
        public function getUntrustedValues(string|object|null $returnType = null, ?array $controls = null): object|array
1✔
132
        {
133
                if (is_object($returnType)) {
1✔
134
                        $obj = $returnType;
1✔
135
                        $rc = new \ReflectionClass($obj);
1✔
136

137
                } else {
138
                        $returnType = ($returnType ?? $this->mappedType ?? ArrayHash::class);
1✔
139
                        $rc = new \ReflectionClass($returnType === self::Array ? \stdClass::class : $returnType);
1✔
140
                        if ($rc->hasMethod('__construct') && $rc->getMethod('__construct')->getNumberOfRequiredParameters()) {
1✔
141
                                $obj = new \stdClass;
1✔
142
                                $useConstructor = true;
1✔
143
                        } else {
144
                                $obj = $rc->newInstance();
1✔
145
                        }
146
                }
147

148
                foreach ($this->getComponents() as $name => $control) {
1✔
149
                        $allowed = $controls === null || in_array($this, $controls, true) || in_array($control, $controls, true);
1✔
150
                        $name = (string) $name;
1✔
151
                        if (
152
                                $control instanceof Control
1✔
153
                                && $allowed
1✔
154
                                && !$control->isOmitted()
1✔
155
                        ) {
156
                                $obj->$name = $control->getValue();
1✔
157

158
                        } elseif ($control instanceof self) {
1✔
159
                                $type = $returnType === self::Array && !$control->mappedType
1✔
160
                                        ? self::Array
1✔
161
                                        : ($rc->hasProperty($name) ? Helpers::getSingleType($rc->getProperty($name)) : null);
1✔
162
                                $obj->$name = $control->getUntrustedValues($type, $allowed ? null : $controls);
1✔
163
                        }
164
                }
165

166
                if (isset($useConstructor)) {
1✔
167
                        return new $returnType(...(array) $obj);
1✔
168
                }
169

170
                return $returnType === self::Array
1✔
171
                        ? (array) $obj
1✔
172
                        : $obj;
1✔
173
        }
174

175

176
        /** @deprecated use getUntrustedValues() */
177
        public function getUnsafeValues($returnType, ?array $controls = null)
178
        {
UNCOV
179
                trigger_error(__METHOD__ . '() was renamed to getUntrustedValues()', E_USER_DEPRECATED);
×
UNCOV
180
                return $this->getUntrustedValues($returnType, $controls);
×
181
        }
182

183

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

190

191
        /********************* validation ****************d*g**/
192

193

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

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

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

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

213

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

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

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

239

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

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

253

254
        /********************* form building ****************d*g**/
255

256

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

263

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

272

273
        /**
274
         * Adds the specified component to the IContainer.
275
         * @throws Nette\InvalidStateException
276
         */
277
        public function addComponent(
1✔
278
                Nette\ComponentModel\IComponent $component,
279
                ?string $name,
280
                ?string $insertBefore = null,
281
        ): static
282
        {
283
                if (!$component instanceof Control && !$component instanceof self) {
1✔
UNCOV
284
                        throw new Nette\InvalidStateException("Component '$name' of type " . get_debug_type($component) . ' is not intended to be used in the form.');
×
285
                }
286

287
                parent::addComponent($component, $name, $insertBefore);
1✔
288
                $this->currentGroup?->add($component);
1✔
289
                return $this;
1✔
290
        }
291

292

293
        /**
294
         * Retrieves the entire hierarchy of form controls including nested.
295
         * @return list<Control>
296
         */
297
        public function getControls(): array
298
        {
299
                return array_values(array_filter($this->getComponentTree(), fn($c) => $c instanceof Control));
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(string $name, string|Stringable|null $label = null): Controls\TextInput
1✔
366
        {
367
                return $this[$name] = (new Controls\TextInput($label))
1✔
368
                        ->addRule(Form::Email);
1✔
369
        }
370

371

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

382

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

395

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

404

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

417

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

430

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

439

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

448

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

458

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

467

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

480

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

493

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

508

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

523

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

532

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

541

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

550

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

561

562
        /** @deprecated  use addImageButton() */
563
        public function addImage(): Controls\ImageButton
564
        {
UNCOV
565
                trigger_error(__METHOD__ . '() was renamed to addImageButton()', E_USER_DEPRECATED);
×
UNCOV
566
                return $this->addImageButton(...func_get_args());
×
567
        }
568

569

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

581

582
        /********************* extension methods ****************d*g**/
583

584

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

UNCOV
591
                return parent::__call($name, $args);
×
592
        }
593

594

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

601
                self::$extMethods[$name] = $callback;
1✔
602
        }
1✔
603

604

605
        /**
606
         * Prevents cloning.
607
         */
608
        public function __clone()
609
        {
UNCOV
610
                throw new Nette\NotImplementedException('Form cloning is not supported yet.');
×
611
        }
612
}
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

© 2026 Coveralls, Inc