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

nette / forms / 40630207392

28 Oct 2026 04:03AM UTC coverage: 92.13% (-1.2%) from 93.369%
40630207392

push

github

dg
Helpers::tryEnumConversion() no longer throws on incompatible input

When mapping a text/hidden control onto a backed-enum property, the raw
submitted value was passed straight to BackedEnum::from(). Under strict_types
that rejects any mismatch: an int-backed enum given a non-numeric string (e.g.
an empty field) raised TypeError, an out-of-range value raised ValueError.

The method is now total: it converts only when a matching case exists - coercing
numeric strings to the int backing type so int-backed enums map from form input
at all - and returns the value unchanged otherwise.

This only makes the helper itself safe; it does not add enum-membership
validation. A required enum property fed an invalid value still fails later at
the typed assignment in the target object's constructor, which is generic
typed-mapping behaviour, not specific to enums.

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

79 existing lines in 16 files now uncovered.

1955 of 2122 relevant lines covered (92.13%)

0.92 hits per line

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

93.13
/src/Forms/Controls/BaseControl.php
1
<?php declare(strict_types=1);
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
namespace Nette\Forms\Controls;
9

10
use Nette;
11
use Nette\Forms\{Control, Form, Rules};
12
use Nette\Utils\Html;
13
use Stringable;
14
use function func_num_args, is_array;
15

16

17
/**
18
 * Base implementation for form controls with HTML rendering, validation, translation, and option support.
19
 *
20
 * @property-read string $name
21
 * @property-read Form $form
22
 * @property-read string $htmlName
23
 * @property   string|bool|null $htmlId
24
 * @property   mixed $value
25
 * @property   string|Stringable $caption
26
 * @property   bool $disabled
27
 * @property   bool $omitted
28
 * @property-read Html $control
29
 * @property-read Html $label
30
 * @property-read Html $controlPrototype
31
 * @property-read Html $labelPrototype
32
 * @property   bool $required
33
 * @property-read bool $filled
34
 * @property-read string[] $errors
35
 * @property-read array<string,mixed> $options
36
 * @property-read string $error
37
 */
38
abstract class BaseControl extends Nette\ComponentModel\Component implements Control
39
{
40
        public static string $idMask = 'frm-%s';
41

42
        protected mixed $value = null;
43
        protected Html $control;
44
        protected Html $label;
45

46
        /** @var bool|bool[] */
47
        protected bool|array $disabled = false;
48

49
        /** @var array<string, array<class-string, callable(static): mixed>> */
50
        private static array $extMethods = [];
51

52
        /** @var list<string|Stringable> */
53
        private array $errors = [];
54
        private ?bool $omitted = null;
55
        private Rules $rules;
56

57
        /** true means autodetect */
58
        private Nette\Localization\Translator|bool|null $translator = true;
59

60
        /** @var array<string, mixed> */
61
        private array $options = [];
62

63

64
        public function __construct(
1 ✔
65
                private string|Stringable|null $caption = null,
66
        ) {
67
                $this->control = Html::el('input', ['type' => null, 'name' => null]);
1 ✔
68
                $this->label = Html::el('label');
1 ✔
69
                $this->rules = new Rules($this);
1 ✔
70
                $this->setValue(null);
1 ✔
71
                $this->monitor(Form::class, function (Form $form): void {
1 ✔
72
                        if (!$this->isDisabled() && $form->isAnchored() && $form->isSubmitted()) {
1 ✔
73
                                $this->loadHttpData();
1 ✔
74
                        }
75
                });
1 ✔
76
        }
1 ✔
77

78

79
        public function setCaption(string|Stringable|null $caption): static
80
        {
UNCOV
81
                $this->caption = $caption;
×
UNCOV
82
                return $this;
×
83
        }
84

85

86
        public function getCaption(): string|Stringable|null
87
        {
88
                return $this->caption;
1 ✔
89
        }
90

91

92
        /**
93
         * Returns form.
94
         * @return ($throw is true ? Form : ?Form)
95
         */
96
        public function getForm(bool $throw = true): ?Form
97
        {
98
                return $this->lookup(Form::class, $throw);
1 ✔
99
        }
100

101

102
        /**
103
         * Loads HTTP data.
104
         */
105
        public function loadHttpData(): void
106
        {
107
                $this->setValue($this->getHttpData(Form::DataText));
1 ✔
108
        }
1 ✔
109

110

111
        /**
112
         * Returns submitted HTTP value for this control.
113
         */
114
        protected function getHttpData(int $type, ?string $htmlTail = null): mixed
115
        {
116
                return $this->getForm()->getHttpData($type, $this->getHtmlName() . $htmlTail);
1 ✔
117
        }
118

119

120
        /**
121
         * Returns HTML name of control.
122
         */
123
        public function getHtmlName(): string
124
        {
125
                return $this->control->name ?? Nette\Forms\Helpers::generateHtmlName($this->lookupPath(Form::class));
1 ✔
126
        }
127

128

129
        /********************* interface Control ****************d*g**/
130

131

132
        /**
133
         * @return static
134
         * @internal
135
         */
136
        public function setValue(mixed $value)
137
        {
138
                $this->value = $value;
1 ✔
139
                return $this;
1 ✔
140
        }
141

142

143
        /** @return mixed */
144
        public function getValue()
145
        {
146
                return $this->value;
1 ✔
147
        }
148

149

150
        /**
151
         * Is control filled?
152
         */
153
        public function isFilled(): bool
154
        {
155
                $value = $this->getValue();
1 ✔
156
                return $value !== null && $value !== [] && $value !== '';
1 ✔
157
        }
158

159

160
        /**
161
         * Sets the default value. Has no effect on submitted or disabled controls.
162
         * @return static
163
         */
164
        public function setDefaultValue(mixed $value)
165
        {
166
                $form = $this->getForm(throw: false);
1 ✔
167
                if ($this->isDisabled() || !$form || !$form->isAnchored() || !$form->isSubmitted()) {
1 ✔
168
                        $this->setValue($value);
1 ✔
169
                }
170

171
                return $this;
1 ✔
172
        }
173

174

175
        /**
176
         * Disables or enables control.
177
         * @return static
178
         */
179
        public function setDisabled(bool $state = true)
180
        {
181
                $this->disabled = $state;
1 ✔
182
                if ($state) {
1 ✔
183
                        $this->setValue(null);
1 ✔
184
                } elseif (($form = $this->getForm(throw: false)) && $form->isAnchored() && $form->isSubmitted()) {
1 ✔
185
                        $this->loadHttpData();
1 ✔
186
                }
187

188
                return $this;
1 ✔
189
        }
190

191

192
        /**
193
         * Is control disabled?
194
         */
195
        public function isDisabled(): bool
196
        {
197
                return $this->disabled === true;
1 ✔
198
        }
199

200

201
        /**
202
         * Excludes or includes the control value from $form->getValues() result.
203
         */
204
        public function setOmitted(bool $state = true): static
205
        {
206
                $this->omitted = $state;
1 ✔
207
                return $this;
1 ✔
208
        }
209

210

211
        /**
212
         * Is control value excluded from $form->getValues() result?
213
         */
214
        public function isOmitted(): bool
215
        {
216
                return $this->omitted || ($this->isDisabled() && $this->omitted === null);
1 ✔
217
        }
218

219

220
        /********************* rendering ****************d*g**/
221

222

223
        /**
224
         * Generates control's HTML element.
225
         * @return Html|string
226
         */
227
        public function getControl()
228
        {
229
                $this->setOption('rendered', true);
1 ✔
230
                $el = clone $this->control;
1 ✔
231
                return $el->addAttributes([
1 ✔
232
                        'name' => $this->getHtmlName(),
1 ✔
233
                        'id' => $this->getHtmlId(),
1 ✔
234
                        'required' => $this->isRequired(),
1 ✔
235
                        'disabled' => $this->isDisabled(),
1 ✔
236
                        'data-nette-rules' => Nette\Forms\Helpers::exportRules($this->rules) ?: null,
1 ✔
237
                ]);
238
        }
239

240

241
        /**
242
         * Generates label's HTML element.
243
         * @return Html|string|null
244
         */
245
        public function getLabel(string|Stringable|null $caption = null)
246
        {
247
                $label = clone $this->label;
1 ✔
248
                $label->for = $this->getHtmlId();
1 ✔
249
                $caption ??= $this->caption;
1 ✔
250
                $translator = $this->getForm()->getTranslator();
1 ✔
251
                $label->setText(
1 ✔
252
                        $translator && $caption !== null && !$caption instanceof Nette\HtmlStringable ? $translator->translate($caption) : $caption,
1 ✔
253
                );
254
                return $label;
1 ✔
255
        }
256

257

258
        public function getControlPart(): ?Html
259
        {
260
                $control = $this->getControl();
1 ✔
261
                return $control instanceof Html ? $control : null;
1 ✔
262
        }
263

264

265
        public function getLabelPart(): ?Html
266
        {
267
                $label = $this->getLabel();
1 ✔
268
                return $label instanceof Html ? $label : null;
1 ✔
269
        }
270

271

272
        /**
273
         * Returns control's HTML element template.
274
         */
275
        public function getControlPrototype(): Html
276
        {
277
                return $this->control;
1 ✔
278
        }
279

280

281
        /**
282
         * Returns label's HTML element template.
283
         */
284
        public function getLabelPrototype(): Html
285
        {
UNCOV
286
                return $this->label;
×
287
        }
288

289

290
        /**
291
         * Changes control's HTML id.
292
         */
293
        public function setHtmlId(string|bool|null $id): static
294
        {
295
                $this->control->id = $id;
1 ✔
296
                return $this;
1 ✔
297
        }
298

299

300
        /**
301
         * Returns control's HTML id.
302
         */
303
        public function getHtmlId(): string|bool|null
304
        {
305
                if (!isset($this->control->id)) {
1 ✔
306
                        $form = $this->getForm();
1 ✔
307
                        $prefix = $form instanceof Nette\Application\UI\Form || $form->getName() === null
1 ✔
308
                                ? ''
1 ✔
309
                                : $form->getName() . '-';
1 ✔
310
                        $this->control->id = sprintf(self::$idMask, $prefix . $this->lookupPath());
1 ✔
311
                }
312

313
                return $this->control->id;
1 ✔
314
        }
315

316

317
        /**
318
         * Changes control's HTML attribute.
319
         */
320
        public function setHtmlAttribute(string $name, mixed $value = true): static
321
        {
322
                $this->control->$name = $value;
1 ✔
323
                if (
324
                        $name === 'name'
1 ✔
325
                        && ($form = $this->getForm(throw: false))
1 ✔
326
                        && !$this->isDisabled()
1 ✔
327
                        && $form->isAnchored()
1 ✔
328
                        && $form->isSubmitted()
1 ✔
329
                ) {
330
                        $this->loadHttpData();
1 ✔
331
                }
332

333
                return $this;
1 ✔
334
        }
335

336

337
        /**
338
         * @deprecated  use setHtmlAttribute()
339
         */
340
        public function setAttribute(string $name, mixed $value = true): static
341
        {
UNCOV
342
                return $this->setHtmlAttribute($name, $value);
×
343
        }
344

345

346
        /********************* translator ****************d*g**/
347

348

349
        public function setTranslator(?Nette\Localization\Translator $translator): static
350
        {
351
                $this->translator = $translator;
1 ✔
352
                return $this;
1 ✔
353
        }
354

355

356
        /**
357
         * Returns the translator, or inherits it from the form when not explicitly set.
358
         */
359
        public function getTranslator(): ?Nette\Localization\Translator
360
        {
361
                if ($this->translator === true) {
1 ✔
362
                        return $this->getForm(throw: false)
1 ✔
363
                                ? $this->getForm()->getTranslator()
1 ✔
364
                                : null;
1 ✔
365
                }
366

367
                return $this->translator ?: null;
1 ✔
368
        }
369

370

371
        /**
372
         * Translates a string or array of strings, or returns the value unchanged without a translator or when it is HtmlStringable.
373
         */
374
        public function translate(mixed $value, mixed ...$parameters): mixed
375
        {
376
                if ($translator = $this->getTranslator()) {
1 ✔
377
                        $tmp = is_array($value) ? [&$value] : [[&$value]];
1 ✔
378
                        foreach ($tmp[0] as &$v) {
1 ✔
379
                                if ($v != null && !$v instanceof Nette\HtmlStringable) { // intentionally ==
1 ✔
380
                                        $v = $translator->translate($v, ...$parameters);
1 ✔
381
                                }
382
                        }
383
                }
384

385
                return $value;
1 ✔
386
        }
387

388

389
        /********************* rules ****************d*g**/
390

391

392
        /**
393
         * Adds a validation rule.
394
         * @param  (callable(Control, mixed): bool)|string  $validator
395
         * @return static
396
         */
397
        public function addRule(
398
                callable|string $validator,
399
                string|Stringable|null $errorMessage = null,
400
                mixed $arg = null,
401
        ) {
402
                $this->rules->addRule($validator, $errorMessage, $arg);
1 ✔
403
                return $this;
1 ✔
404
        }
405

406

407
        /**
408
         * Adds a validation condition and returns a new branch.
409
         * @param  (callable(Control, mixed): bool)|string|bool  $validator
410
         */
411
        public function addCondition($validator, mixed $value = null): Rules
412
        {
413
                return $this->rules->addCondition($validator, $value);
1 ✔
414
        }
415

416

417
        /**
418
         * Adds a validation condition based on another control and returns a new branch.
419
         * @param  (callable(Control, mixed): bool)|string  $validator
420
         */
421
        public function addConditionOn(Control $control, $validator, mixed $value = null): Rules
422
        {
423
                return $this->rules->addConditionOn($control, $validator, $value);
1 ✔
424
        }
425

426

427
        /**
428
         * Adds an input filter callback.
429
         * @param callable(mixed): mixed  $filter
430
         */
431
        public function addFilter(callable $filter): static
432
        {
433
                $this->getRules()->addFilter($filter);
1 ✔
434
                return $this;
1 ✔
435
        }
436

437

438
        public function getRules(): Rules
439
        {
440
                return $this->rules;
1 ✔
441
        }
442

443

444
        /**
445
         * Makes control mandatory.
446
         */
447
        public function setRequired(string|Stringable|bool $value = true): static
448
        {
449
                $this->rules->setRequired($value);
1 ✔
450
                return $this;
1 ✔
451
        }
452

453

454
        /**
455
         * Is control mandatory?
456
         */
457
        public function isRequired(): bool
458
        {
459
                return $this->rules->isRequired();
1 ✔
460
        }
461

462

463
        /**
464
         * Performs server-side validation against all rules.
465
         */
466
        public function validate(): void
467
        {
468
                if ($this->isDisabled()) {
1 ✔
469
                        return;
1 ✔
470
                }
471

472
                $this->cleanErrors();
1 ✔
473
                $this->rules->validate();
1 ✔
474
        }
1 ✔
475

476

477
        /**
478
         * Adds error message to the list.
479
         */
480
        public function addError(string|Stringable $message, bool $translate = true): void
481
        {
482
                $this->errors[] = $translate ? $this->translate($message) : $message;
1 ✔
483
        }
1 ✔
484

485

486
        /**
487
         * Returns all control errors joined into one string, or null if there are no errors.
488
         */
489
        public function getError(): ?string
490
        {
491
                return $this->errors ? implode(' ', array_unique($this->errors)) : null;
1 ✔
492
        }
493

494

495
        /**
496
         * Returns all unique validation errors for this control.
497
         * @return list<string|Stringable>
498
         */
499
        public function getErrors(): array
500
        {
501
                return array_values(array_unique($this->errors));
1 ✔
502
        }
503

504

505
        public function hasErrors(): bool
506
        {
507
                return (bool) $this->errors;
1 ✔
508
        }
509

510

511
        public function cleanErrors(): void
512
        {
513
                $this->errors = [];
1 ✔
514
        }
1 ✔
515

516

517
        /********************* user data ****************d*g**/
518

519

520
        /**
521
         * Sets a rendering or user-specific option (e.g. 'description', 'class', 'id').
522
         */
523
        public function setOption(string $key, mixed $value): static
524
        {
525
                if ($value === null) {
1 ✔
UNCOV
526
                        unset($this->options[$key]);
×
527
                } else {
528
                        $this->options[$key] = $value;
1 ✔
529
                }
530

531
                return $this;
1 ✔
532
        }
533

534

535
        /**
536
         * Returns a rendering or user-specific option value.
537
         */
538
        public function getOption(string $key): mixed
539
        {
540
                if (func_num_args() > 1) {
1 ✔
UNCOV
541
                        trigger_error(__METHOD__ . '() parameter $default is deprecated, use operator ??', E_USER_DEPRECATED);
×
542
                        $default = func_get_arg(1);
×
543
                }
544
                return $this->options[$key] ?? $default ?? null;
1 ✔
545
        }
546

547

548
        /**
549
         * Returns all rendering and user-specific options.
550
         * @return array<string, mixed>
551
         */
552
        public function getOptions(): array
553
        {
UNCOV
554
                return $this->options;
×
555
        }
556

557

558
        /********************* extension methods ****************d*g**/
559

560

561
        /**
562
         * @param  mixed[]  $args
563
         * @return mixed
564
         */
565
        public function __call(string $name, array $args)
566
        {
567
                $class = static::class;
1 ✔
568
                do {
569
                        if (isset(self::$extMethods[$name][$class])) {
1 ✔
570
                                return (self::$extMethods[$name][$class])($this, ...$args);
1 ✔
571
                        }
572

573
                        $class = get_parent_class($class);
1 ✔
574
                } while ($class);
1 ✔
575

576
                return parent::__call($name, $args);
1 ✔
577
        }
578

579

580
        /** @param callable(static): mixed  $callback */
581
        public static function extensionMethod(string $name, callable $callback): void
582
        {
583
                if (str_contains($name, '::')) { // back compatibility
1 ✔
UNCOV
584
                        [, $name] = explode('::', $name);
×
585
                }
586

587
                self::$extMethods[$name][static::class] = $callback;
1 ✔
588
        }
1 ✔
589
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc