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

nette / forms / 15763260878

19 Jun 2025 05:19PM UTC coverage: 93.011%. Remained the same
15763260878

push

github

dg
netteForms: restructured package, includes UMD and ESM (BC break)

2076 of 2232 relevant lines covered (93.01%)

0.93 hits per line

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

93.88
/src/Forms/Controls/BaseControl.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\Controls;
11

12
use Nette;
13
use Nette\Forms\Control;
14
use Nette\Forms\Form;
15
use Nette\Forms\Rules;
16
use Nette\Utils\Html;
17
use Stringable;
18
use function array_unique, explode, func_get_arg, func_num_args, get_parent_class, implode, is_array, sprintf, str_contains;
19

20

21
/**
22
 * Base class that implements the basic functionality common to form controls.
23
 *
24
 * @property-read Form $form
25
 * @property-read string $htmlName
26
 * @property   string|bool|null $htmlId
27
 * @property   mixed $value
28
 * @property   string|Stringable $caption
29
 * @property   bool $disabled
30
 * @property   bool $omitted
31
 * @property-read Html $control
32
 * @property-read Html $label
33
 * @property-read Html $controlPrototype
34
 * @property-read Html $labelPrototype
35
 * @property   bool $required
36
 * @property-read bool $filled
37
 * @property-read array $errors
38
 * @property-read array $options
39
 * @property-read string $error
40
 */
41
abstract class BaseControl extends Nette\ComponentModel\Component implements Control
42
{
43
        public static string $idMask = 'frm-%s';
44

45
        protected mixed $value = null;
46
        protected Html $control;
47
        protected Html $label;
48
        protected bool $disabled = false;
49

50
        /** @var callable[][]  extension methods */
51
        private static array $extMethods = [];
52
        private string|Stringable|null $caption;
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
        private array $options = [];
60

61

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

76

77
        /**
78
         * Sets textual caption or label.
79
         */
80
        public function setCaption(string|Stringable|null $caption): static
81
        {
82
                $this->caption = $caption;
×
83
                return $this;
×
84
        }
85

86

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

92

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

102

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

111

112
        /**
113
         * Loads HTTP data.
114
         */
115
        protected function getHttpData($type, ?string $htmlTail = null): mixed
1✔
116
        {
117
                return $this->getForm()->getHttpData($type, $this->getHtmlName() . $htmlTail);
1✔
118
        }
119

120

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

129

130
        /********************* interface Control ****************d*g**/
131

132

133
        /**
134
         * Sets control's value.
135
         * @internal
136
         */
137
        public function setValue($value): static
138
        {
139
                $this->value = $value;
1✔
140
                return $this;
1✔
141
        }
142

143

144
        /**
145
         * Returns control's value.
146
         * @return mixed
147
         */
148
        public function getValue(): mixed
149
        {
150
                return $this->value;
1✔
151
        }
152

153

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

163

164
        /**
165
         * Sets control's default value.
166
         */
167
        public function setDefaultValue($value): static
168
        {
169
                $form = $this->getForm(throw: false);
1✔
170
                if ($this->isDisabled() || !$form || !$form->isAnchored() || !$form->isSubmitted()) {
1✔
171
                        $this->setValue($value);
1✔
172
                }
173

174
                return $this;
1✔
175
        }
176

177

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

190
                return $this;
1✔
191
        }
192

193

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

202

203
        /**
204
         * Sets whether control value is excluded from $form->getValues() result.
205
         */
206
        public function setOmitted(bool $state = true): static
1✔
207
        {
208
                $this->omitted = $state;
1✔
209
                return $this;
1✔
210
        }
211

212

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

221

222
        /********************* rendering ****************d*g**/
223

224

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

242

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

256

257
        public function getControlPart(): ?Html
258
        {
259
                return $this->getControl();
1✔
260
        }
261

262

263
        public function getLabelPart(): ?Html
264
        {
265
                return $this->getLabel();
1✔
266
        }
267

268

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

277

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

286

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

296

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

310
                return $this->control->id;
1✔
311
        }
312

313

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

330
                return $this;
1✔
331
        }
332

333

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

342

343
        /********************* translator ****************d*g**/
344

345

346
        /**
347
         * Sets translate adapter.
348
         */
349
        public function setTranslator(?Nette\Localization\Translator $translator): static
1✔
350
        {
351
                $this->translator = $translator;
1✔
352
                return $this;
1✔
353
        }
354

355

356
        /**
357
         * Returns translate adapter.
358
         */
359
        public function getTranslator(): ?Nette\Localization\Translator
360
        {
361
                if ($this->translator === true) {
1✔
362
                        return $this->getForm(false)
1✔
363
                                ? $this->getForm()->getTranslator()
1✔
364
                                : null;
1✔
365
                }
366

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

370

371
        /**
372
         * Returns translated string.
373
         */
374
        public function translate($value, ...$parameters): mixed
1✔
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
         */
395
        public function addRule(
1✔
396
                callable|string $validator,
397
                string|Stringable|null $errorMessage = null,
398
                mixed $arg = null,
399
        ): static
400
        {
401
                $this->rules->addRule($validator, $errorMessage, $arg);
1✔
402
                return $this;
1✔
403
        }
404

405

406
        /**
407
         * Adds a validation condition a returns new branch.
408
         */
409
        public function addCondition($validator, $value = null): Rules
1✔
410
        {
411
                return $this->rules->addCondition($validator, $value);
1✔
412
        }
413

414

415
        /**
416
         * Adds a validation condition based on another control a returns new branch.
417
         */
418
        public function addConditionOn(Control $control, $validator, $value = null): Rules
1✔
419
        {
420
                return $this->rules->addConditionOn($control, $validator, $value);
1✔
421
        }
422

423

424
        /**
425
         * Adds an input filter callback.
426
         */
427
        public function addFilter(callable $filter): static
1✔
428
        {
429
                $this->getRules()->addFilter($filter);
1✔
430
                return $this;
1✔
431
        }
432

433

434
        public function getRules(): Rules
435
        {
436
                return $this->rules;
1✔
437
        }
438

439

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

449

450
        /**
451
         * Is control mandatory?
452
         */
453
        public function isRequired(): bool
454
        {
455
                return $this->rules->isRequired();
1✔
456
        }
457

458

459
        /**
460
         * Performs the server side validation.
461
         */
462
        public function validate(): void
463
        {
464
                if ($this->isDisabled()) {
1✔
465
                        return;
1✔
466
                }
467

468
                $this->cleanErrors();
1✔
469
                $this->rules->validate();
1✔
470
        }
1✔
471

472

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

481

482
        /**
483
         * Returns errors corresponding to control.
484
         */
485
        public function getError(): ?string
486
        {
487
                return $this->errors ? implode(' ', array_unique($this->errors)) : null;
1✔
488
        }
489

490

491
        /**
492
         * Returns errors corresponding to control.
493
         */
494
        public function getErrors(): array
495
        {
496
                return array_unique($this->errors);
1✔
497
        }
498

499

500
        public function hasErrors(): bool
501
        {
502
                return (bool) $this->errors;
1✔
503
        }
504

505

506
        public function cleanErrors(): void
507
        {
508
                $this->errors = [];
1✔
509
        }
1✔
510

511

512
        /********************* user data ****************d*g**/
513

514

515
        /**
516
         * Sets user-specific option.
517
         */
518
        public function setOption($key, mixed $value): static
1✔
519
        {
520
                if ($value === null) {
1✔
521
                        unset($this->options[$key]);
×
522
                } else {
523
                        $this->options[$key] = $value;
1✔
524
                }
525

526
                return $this;
1✔
527
        }
528

529

530
        /**
531
         * Returns user-specific option.
532
         */
533
        public function getOption($key): mixed
534
        {
535
                if (func_num_args() > 1) {
1✔
536
                        trigger_error(__METHOD__ . '() parameter $default is deprecated, use operator ??', E_USER_DEPRECATED);
×
537
                        $default = func_get_arg(1);
×
538
                }
539
                return $this->options[$key] ?? $default ?? null;
1✔
540
        }
541

542

543
        /**
544
         * Returns user-specific options.
545
         */
546
        public function getOptions(): array
547
        {
548
                return $this->options;
×
549
        }
550

551

552
        /********************* extension methods ****************d*g**/
553

554

555
        public function __call(string $name, array $args)
1✔
556
        {
557
                $class = static::class;
1✔
558
                do {
559
                        if (isset(self::$extMethods[$name][$class])) {
1✔
560
                                return (self::$extMethods[$name][$class])($this, ...$args);
1✔
561
                        }
562

563
                        $class = get_parent_class($class);
1✔
564
                } while ($class);
1✔
565

566
                return parent::__call($name, $args);
1✔
567
        }
568

569

570
        public static function extensionMethod(string $name, /*callable*/ $callback): void
1✔
571
        {
572
                if (str_contains($name, '::')) { // back compatibility
1✔
573
                        [, $name] = explode('::', $name);
×
574
                }
575

576
                self::$extMethods[$name][static::class] = $callback;
1✔
577
        }
1✔
578
}
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