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

nette / forms / 11466457354

22 Oct 2024 06:38PM UTC coverage: 92.998% (-0.006%) from 93.004%
11466457354

push

github

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

2072 of 2228 relevant lines covered (93.0%)

0.93 hits per line

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

89.95
/src/Forms/Form.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\Arrays;
14
use Nette\Utils\Html;
15
use Stringable;
16

17

18
/**
19
 * Creates, validates and renders HTML forms.
20
 *
21
 * @property-read array $errors
22
 * @property-read array $ownErrors
23
 * @property-read Html $elementPrototype
24
 * @property-read FormRenderer $renderer
25
 * @property string $action
26
 * @property string $method
27
 */
28
class Form extends Container implements Nette\HtmlStringable
29
{
30
        /** validator */
31
        public const
32
                Equal = ':equal',
33
                IsIn = self::Equal,
34
                NotEqual = ':notEqual',
35
                IsNotIn = self::NotEqual,
36
                Filled = ':filled',
37
                Blank = ':blank',
38
                Required = self::Filled,
39
                Valid = ':valid',
40

41
                // button
42
                Submitted = ':submitted',
43

44
                // text
45
                MinLength = ':minLength',
46
                MaxLength = ':maxLength',
47
                Length = ':length',
48
                Email = ':email',
49
                URL = ':url',
50
                Pattern = ':pattern',
51
                PatternInsensitive = ':patternCaseInsensitive',
52
                Integer = ':integer',
53
                Numeric = ':numeric',
54
                Float = ':float',
55
                Min = ':min',
56
                Max = ':max',
57
                Range = ':range',
58

59
                // multiselect
60
                Count = self::Length,
61

62
                // file upload
63
                MaxFileSize = ':fileSize',
64
                MimeType = ':mimeType',
65
                Image = ':image',
66
                MaxPostSize = ':maxPostSize';
67

68
        /** method */
69
        public const
70
                Get = 'get',
71
                Post = 'post';
72

73
        /** submitted data types */
74
        public const
75
                DataText = 1,
76
                DataLine = 2,
77
                DataFile = 3,
78
                DataKeys = 8;
79

80
        /** @internal tracker ID */
81
        public const TrackerId = '_form_';
82

83
        /** @internal protection token ID */
84
        public const ProtectorId = '_token_';
85

86
        /** @deprecated use Form::Equal */
87
        public const EQUAL = self::Equal;
88

89
        /** @deprecated use Form::IsIn */
90
        public const IS_IN = self::IsIn;
91

92
        /** @deprecated use Form::NotEqual */
93
        public const NOT_EQUAL = self::NotEqual;
94

95
        /** @deprecated use Form::IsNotIn */
96
        public const IS_NOT_IN = self::IsNotIn;
97

98
        /** @deprecated use Form::Filled */
99
        public const FILLED = self::Filled;
100

101
        /** @deprecated use Form::Blank */
102
        public const BLANK = self::Blank;
103

104
        /** @deprecated use Form::Required */
105
        public const REQUIRED = self::Required;
106

107
        /** @deprecated use Form::Valid */
108
        public const VALID = self::Valid;
109

110
        /** @deprecated use Form::Submitted */
111
        public const SUBMITTED = self::Submitted;
112

113
        /** @deprecated use Form::MinLength */
114
        public const MIN_LENGTH = self::MinLength;
115

116
        /** @deprecated use Form::MaxLength */
117
        public const MAX_LENGTH = self::MaxLength;
118

119
        /** @deprecated use Form::Length */
120
        public const LENGTH = self::Length;
121

122
        /** @deprecated use Form::Email */
123
        public const EMAIL = self::Email;
124

125
        /** @deprecated use Form::Pattern */
126
        public const PATTERN = self::Pattern;
127

128
        /** @deprecated use Form::PatternCI */
129
        public const PATTERN_ICASE = self::PatternInsensitive;
130

131
        /** @deprecated use Form::Integer */
132
        public const INTEGER = self::Integer;
133

134
        /** @deprecated use Form::Numeric */
135
        public const NUMERIC = self::Numeric;
136

137
        /** @deprecated use Form::Float */
138
        public const FLOAT = self::Float;
139

140
        /** @deprecated use Form::Min */
141
        public const MIN = self::Min;
142

143
        /** @deprecated use Form::Max */
144
        public const MAX = self::Max;
145

146
        /** @deprecated use Form::Range */
147
        public const RANGE = self::Range;
148

149
        /** @deprecated use Form::Count */
150
        public const COUNT = self::Count;
151

152
        /** @deprecated use Form::MaxFileSize */
153
        public const MAX_FILE_SIZE = self::MaxFileSize;
154

155
        /** @deprecated use Form::MimeType */
156
        public const MIME_TYPE = self::MimeType;
157

158
        /** @deprecated use Form::Image */
159
        public const IMAGE = self::Image;
160

161
        /** @deprecated use Form::MaxPostSize */
162
        public const MAX_POST_SIZE = self::MaxPostSize;
163

164
        /** @deprecated use Form::Get */
165
        public const GET = self::Get;
166

167
        /** @deprecated use Form::Post */
168
        public const POST = self::Post;
169

170
        /** @deprecated use Form::DataText */
171
        public const DATA_TEXT = self::DataText;
172

173
        /** @deprecated use Form::DataLine */
174
        public const DATA_LINE = self::DataLine;
175

176
        /** @deprecated use Form::DataFile */
177
        public const DATA_FILE = self::DataFile;
178

179
        /** @deprecated use Form::DataKeys */
180
        public const DATA_KEYS = self::DataKeys;
181

182
        /** @deprecated use Form::TrackerId */
183
        public const TRACKER_ID = self::TrackerId;
184

185
        /** @deprecated use Form::ProtectorId */
186
        public const PROTECTOR_ID = self::ProtectorId;
187

188
        /**
189
         * Occurs when the form is submitted and successfully validated
190
         * @var array<callable(self, array|object): void|callable(array|object): void>
191
         */
192
        public array $onSuccess = [];
193

194
        /** @var array<callable(self): void>  Occurs when the form is submitted and is not valid */
195
        public array $onError = [];
196

197
        /** @var array<callable(self): void>  Occurs when the form is submitted */
198
        public array $onSubmit = [];
199

200
        /** @var array<callable(self): void>  Occurs before the form is rendered */
201
        public array $onRender = [];
202

203
        /** @internal used only by standalone form */
204
        public Nette\Http\IRequest $httpRequest;
205
        protected bool $crossOrigin = false;
206
        private static ?Nette\Http\IRequest $defaultHttpRequest = null;
207
        private SubmitterControl|bool $submittedBy = false;
208
        private array $httpData;
209
        private Html $element;
210
        private FormRenderer $renderer;
211
        private ?Nette\Localization\Translator $translator = null;
212

213
        /** @var ControlGroup[] */
214
        private array $groups = [];
215
        private array $errors = [];
216
        private bool $beforeRenderCalled = false;
217

218

219
        public function __construct(?string $name = null)
1✔
220
        {
221
                if ($name !== null) {
1✔
222
                        $this->getElementPrototype()->id = 'frm-' . $name;
1✔
223
                        $tracker = new Controls\HiddenField($name);
1✔
224
                        $tracker->setOmitted();
1✔
225
                        $this[self::TrackerId] = $tracker;
1✔
226
                        $this->setParent(null, $name);
1✔
227
                }
228

229
                $this->monitor(self::class, function (): void {
1✔
230
                        throw new Nette\InvalidStateException('Nested forms are forbidden.');
231
                });
1✔
232
        }
1✔
233

234

235
        /**
236
         * Returns self.
237
         */
238
        public function getForm(bool $throw = true): static
1✔
239
        {
240
                return $this;
1✔
241
        }
242

243

244
        /**
245
         * Sets form's action.
246
         */
247
        public function setAction(string|Stringable $url): static
1✔
248
        {
249
                $this->getElementPrototype()->action = $url;
1✔
250
                return $this;
1✔
251
        }
252

253

254
        /**
255
         * Returns form's action.
256
         */
257
        public function getAction(): string|Stringable
258
        {
259
                return $this->getElementPrototype()->action;
1✔
260
        }
261

262

263
        /**
264
         * Sets form's method GET or POST.
265
         */
266
        public function setMethod(string $method): static
1✔
267
        {
268
                if (isset($this->httpData)) {
1✔
269
                        throw new Nette\InvalidStateException(__METHOD__ . '() must be called until the form is empty.');
×
270
                }
271

272
                $this->getElementPrototype()->method = strtolower($method);
1✔
273
                return $this;
1✔
274
        }
275

276

277
        /**
278
         * Returns form's method.
279
         */
280
        public function getMethod(): string
281
        {
282
                return $this->getElementPrototype()->method;
1✔
283
        }
284

285

286
        /**
287
         * Checks if the request method is the given one.
288
         */
289
        public function isMethod(string $method): bool
1✔
290
        {
291
                return strcasecmp($this->getElementPrototype()->method, $method) === 0;
1✔
292
        }
293

294

295
        /**
296
         * Changes forms's HTML attribute.
297
         */
298
        public function setHtmlAttribute(string $name, mixed $value = true): static
299
        {
300
                $this->getElementPrototype()->$name = $value;
×
301
                return $this;
×
302
        }
303

304

305
        /**
306
         * Disables CSRF protection using a SameSite cookie.
307
         */
308
        public function allowCrossOrigin(): void
309
        {
310
                $this->crossOrigin = true;
1✔
311
        }
1✔
312

313

314
        /**
315
         * Cross-Site Request Forgery (CSRF) form protection.
316
         */
317
        public function addProtection(?string $errorMessage = null): Controls\CsrfProtection
1✔
318
        {
319
                $control = new Controls\CsrfProtection($errorMessage);
1✔
320
                $children = $this->getComponents();
1✔
321
                $first = $children ? (string) array_key_first($children) : null;
1✔
322
                $this->addComponent($control, self::ProtectorId, $first);
1✔
323
                return $control;
1✔
324
        }
325

326

327
        /**
328
         * Adds fieldset group to the form.
329
         */
330
        public function addGroup(string|Stringable|null $caption = null, bool $setAsCurrent = true): ControlGroup
1✔
331
        {
332
                $group = new ControlGroup;
1✔
333
                $group->setOption('label', $caption);
1✔
334
                $group->setOption('visual', true);
1✔
335

336
                if ($setAsCurrent) {
1✔
337
                        $this->setCurrentGroup($group);
1✔
338
                }
339

340
                return !is_scalar($caption) || isset($this->groups[$caption])
1✔
341
                        ? $this->groups[] = $group
1✔
342
                        : $this->groups[$caption] = $group;
1✔
343
        }
344

345

346
        /**
347
         * Removes fieldset group from form.
348
         */
349
        public function removeGroup(string|ControlGroup $name): void
350
        {
351
                if (is_string($name) && isset($this->groups[$name])) {
×
352
                        $group = $this->groups[$name];
×
353

354
                } elseif ($name instanceof ControlGroup && in_array($name, $this->groups, strict: true)) {
×
355
                        $group = $name;
×
356
                        $name = array_search($group, $this->groups, strict: true);
×
357

358
                } else {
359
                        throw new Nette\InvalidArgumentException("Group not found in form '{$this->getName()}'");
×
360
                }
361

362
                foreach ($group->getControls() as $control) {
×
363
                        $control->getParent()->removeComponent($control);
×
364
                }
365

366
                unset($this->groups[$name]);
×
367
        }
368

369

370
        /**
371
         * Returns all defined groups.
372
         * @return ControlGroup[]
373
         */
374
        public function getGroups(): array
375
        {
376
                return $this->groups;
1✔
377
        }
378

379

380
        /**
381
         * Returns the specified group.
382
         */
383
        public function getGroup(string|int $name): ?ControlGroup
1✔
384
        {
385
                return $this->groups[$name] ?? null;
1✔
386
        }
387

388

389
        /********************* translator ****************d*g**/
390

391

392
        /**
393
         * Sets translate adapter.
394
         */
395
        public function setTranslator(?Nette\Localization\Translator $translator): static
1✔
396
        {
397
                $this->translator = $translator;
1✔
398
                return $this;
1✔
399
        }
400

401

402
        /**
403
         * Returns translate adapter.
404
         */
405
        public function getTranslator(): ?Nette\Localization\Translator
406
        {
407
                return $this->translator;
1✔
408
        }
409

410

411
        /********************* submission ****************d*g**/
412

413

414
        /**
415
         * Tells if the form is anchored.
416
         */
417
        public function isAnchored(): bool
418
        {
419
                return true;
1✔
420
        }
421

422

423
        /**
424
         * Tells if the form was submitted.
425
         */
426
        public function isSubmitted(): SubmitterControl|bool
427
        {
428
                if (!isset($this->httpData)) {
1✔
429
                        $this->getHttpData();
1✔
430
                }
431

432
                return $this->submittedBy;
1✔
433
        }
434

435

436
        /**
437
         * Tells if the form was submitted and successfully validated.
438
         */
439
        public function isSuccess(): bool
440
        {
441
                return $this->isSubmitted() && $this->isValid();
1✔
442
        }
443

444

445
        /**
446
         * Sets the submittor control.
447
         * @internal
448
         */
449
        public function setSubmittedBy(?SubmitterControl $by): static
1✔
450
        {
451
                $this->submittedBy = $by ?? false;
1✔
452
                return $this;
1✔
453
        }
454

455

456
        /**
457
         * Returns submitted HTTP data.
458
         */
459
        public function getHttpData(?int $type = null, ?string $htmlName = null): string|array|Nette\Http\FileUpload|null
1✔
460
        {
461
                if (!isset($this->httpData)) {
1✔
462
                        if (!$this->isAnchored()) {
1✔
463
                                throw new Nette\InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.');
×
464
                        }
465

466
                        $data = $this->receiveHttpData();
1✔
467
                        $this->httpData = (array) $data;
1✔
468
                        $this->submittedBy = is_array($data);
1✔
469
                }
470

471
                return $htmlName === null
1✔
472
                        ? $this->httpData
1✔
473
                        : Helpers::extractHttpData($this->httpData, $htmlName, $type);
1✔
474
        }
475

476

477
        /**
478
         * Fires submit/click events.
479
         */
480
        public function fireEvents(): void
481
        {
482
                if (!$this->isSubmitted()) {
1✔
483
                        return;
1✔
484

485
                } elseif (!$this->getErrors()) {
1✔
486
                        $this->validate();
1✔
487
                }
488

489
                $handled = count($this->onSuccess ?? []) || count($this->onSubmit ?? []) || $this->submittedBy === true;
1✔
490

491
                if ($this->submittedBy instanceof Controls\SubmitButton) {
1✔
492
                        $handled = $handled || count($this->submittedBy->onClick ?? []);
1✔
493
                        if ($this->isValid()) {
1✔
494
                                $this->invokeHandlers($this->submittedBy->onClick, $this->submittedBy);
1✔
495
                        } else {
496
                                Arrays::invoke($this->submittedBy->onInvalidClick, $this->submittedBy);
1✔
497
                        }
498
                }
499

500
                if ($this->isValid()) {
1✔
501
                        $this->invokeHandlers($this->onSuccess);
1✔
502
                }
503

504
                if (!$this->isValid()) {
1✔
505
                        Arrays::invoke($this->onError, $this);
1✔
506
                }
507

508
                Arrays::invoke($this->onSubmit, $this);
1✔
509

510
                if (!$handled) {
1✔
511
                        trigger_error("Form was submitted but there are no associated handlers (form '{$this->getName()}').", E_USER_WARNING);
1✔
512
                }
513
        }
1✔
514

515

516
        private function invokeHandlers(iterable $handlers, $button = null): void
1✔
517
        {
518
                foreach ($handlers as $handler) {
1✔
519
                        $params = Nette\Utils\Callback::toReflection($handler)->getParameters();
1✔
520
                        $args = [];
1✔
521
                        if ($params) {
1✔
522
                                $type = Helpers::getSingleType($params[0]);
1✔
523
                                $args[] = match (true) {
1✔
524
                                        !$type => $button ?? $this,
1✔
525
                                        $this instanceof $type => $this,
1✔
526
                                        $button instanceof $type => $button,
1✔
527
                                        default => $this->getValues($type),
1✔
528
                                };
529
                                if (isset($params[1])) {
1✔
530
                                        $args[] = $this->getValues(Helpers::getSingleType($params[1]));
1✔
531
                                }
532
                        }
533

534
                        $handler(...$args);
1✔
535

536
                        if (!$this->isValid()) {
1✔
537
                                return;
1✔
538
                        }
539
                }
540
        }
1✔
541

542

543
        /**
544
         * Resets form.
545
         */
546
        public function reset(): static
547
        {
548
                $this->setSubmittedBy(null);
1✔
549
                $this->setValues([], erase: true);
1✔
550
                return $this;
1✔
551
        }
552

553

554
        /**
555
         * Internal: returns submitted HTTP data or null when form was not submitted.
556
         */
557
        protected function receiveHttpData(): ?array
558
        {
559
                $httpRequest = $this->getHttpRequest();
1✔
560
                if (strcasecmp($this->getMethod(), $httpRequest->getMethod())) {
1✔
561
                        return null;
1✔
562
                }
563

564
                if ($httpRequest->isMethod('post')) {
1✔
565
                        if (!$this->crossOrigin && !$httpRequest->isSameSite()) {
1✔
566
                                return null;
1✔
567
                        }
568

569
                        $data = Nette\Utils\Arrays::mergeTree($httpRequest->getPost(), $httpRequest->getFiles());
1✔
570
                } else {
571
                        $data = $httpRequest->getQuery();
1✔
572
                        if (!$data) {
1✔
573
                                return null;
1✔
574
                        }
575
                }
576

577
                if ($tracker = $this->getComponent(self::TrackerId, throw: false)) {
1✔
578
                        if (!isset($data[self::TrackerId]) || $data[self::TrackerId] !== $tracker->getValue()) {
1✔
579
                                return null;
×
580
                        }
581
                }
582

583
                return $data;
1✔
584
        }
585

586

587
        /********************* validation ****************d*g**/
588

589

590
        public function validate(?array $controls = null): void
1✔
591
        {
592
                $this->cleanErrors();
1✔
593
                if ($controls === null && $this->submittedBy instanceof SubmitterControl) {
1✔
594
                        $controls = $this->submittedBy->getValidationScope();
1✔
595
                }
596

597
                $this->validateMaxPostSize();
1✔
598
                parent::validate($controls);
1✔
599
        }
1✔
600

601

602
        /** @internal */
603
        public function validateMaxPostSize(): void
604
        {
605
                if (!$this->submittedBy || !$this->isMethod('post') || empty($_SERVER['CONTENT_LENGTH'])) {
1✔
606
                        return;
1✔
607
                }
608

609
                $maxSize = Helpers::iniGetSize('post_max_size');
1✔
610
                if ($maxSize > 0 && $maxSize < $_SERVER['CONTENT_LENGTH']) {
1✔
611
                        $this->addError(sprintf(Validator::$messages[self::MaxFileSize], $maxSize));
1✔
612
                }
613
        }
1✔
614

615

616
        /**
617
         * Adds global error message.
618
         */
619
        public function addError(string|Stringable $message, bool $translate = true): void
1✔
620
        {
621
                if ($translate && $this->translator) {
1✔
622
                        $message = $this->translator->translate($message);
1✔
623
                }
624

625
                $this->errors[] = $message;
1✔
626
        }
1✔
627

628

629
        /**
630
         * Returns global validation errors.
631
         */
632
        public function getErrors(): array
633
        {
634
                return array_unique(array_merge($this->errors, parent::getErrors()));
1✔
635
        }
636

637

638
        public function hasErrors(): bool
639
        {
640
                return (bool) $this->getErrors();
1✔
641
        }
642

643

644
        public function cleanErrors(): void
645
        {
646
                $this->errors = [];
1✔
647
        }
1✔
648

649

650
        /**
651
         * Returns form's validation errors.
652
         */
653
        public function getOwnErrors(): array
654
        {
655
                return array_unique($this->errors);
1✔
656
        }
657

658

659
        /********************* rendering ****************d*g**/
660

661

662
        /**
663
         * Returns form's HTML element template.
664
         */
665
        public function getElementPrototype(): Html
666
        {
667
                if (!isset($this->element)) {
1✔
668
                        $this->element = Html::el('form');
1✔
669
                        $this->element->action = ''; // RFC 1808 -> empty uri means 'this'
1✔
670
                        $this->element->method = self::Post;
1✔
671
                }
672

673
                return $this->element;
1✔
674
        }
675

676

677
        /**
678
         * Sets form renderer.
679
         */
680
        public function setRenderer(?FormRenderer $renderer): static
1✔
681
        {
682
                $this->renderer = $renderer;
1✔
683
                return $this;
1✔
684
        }
685

686

687
        /**
688
         * Returns form renderer.
689
         */
690
        public function getRenderer(): FormRenderer
691
        {
692
                if (!isset($this->renderer)) {
1✔
693
                        $this->renderer = new Rendering\DefaultFormRenderer;
1✔
694
                }
695

696
                return $this->renderer;
1✔
697
        }
698

699

700
        protected function beforeRender()
701
        {
702
        }
1✔
703

704

705
        /**
706
         * Must be called before form is rendered and render() is not used.
707
         */
708
        public function fireRenderEvents(): void
709
        {
710
                if (!$this->beforeRenderCalled) {
1✔
711
                        $this->beforeRenderCalled = true;
1✔
712
                        $this->beforeRender();
1✔
713
                        Arrays::invoke($this->onRender, $this);
1✔
714
                }
715
        }
1✔
716

717

718
        /**
719
         * Renders form.
720
         */
721
        public function render(...$args): void
1✔
722
        {
723
                $this->fireRenderEvents();
1✔
724
                echo $this->getRenderer()->render($this, ...$args);
1✔
725
        }
1✔
726

727

728
        /**
729
         * Renders form to string.
730
         */
731
        public function __toString(): string
732
        {
733
                $this->fireRenderEvents();
1✔
734
                return $this->getRenderer()->render($this);
1✔
735
        }
736

737

738
        public function getToggles(): array
739
        {
740
                $toggles = [];
1✔
741
                foreach ($this->getComponentTree() as $control) {
1✔
742
                        if ($control instanceof Controls\BaseControl) {
1✔
743
                                $toggles = $control->getRules()->getToggleStates($toggles);
1✔
744
                        }
745
                }
746

747
                return $toggles;
1✔
748
        }
749

750

751
        /********************* backend ****************d*g**/
752

753

754
        /**
755
         * Initialize standalone forms.
756
         */
757
        public static function initialize(bool $reinit = false): void
1✔
758
        {
759
                if ($reinit) {
1✔
760
                        self::$defaultHttpRequest = null;
1✔
761
                        return;
1✔
762
                } elseif (self::$defaultHttpRequest) {
1✔
763
                        return;
1✔
764
                }
765

766
                self::$defaultHttpRequest = (new Nette\Http\RequestFactory)->fromGlobals();
1✔
767

768
                if (!in_array(PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
1✔
769
                        if (headers_sent($file, $line)) {
×
770
                                throw new Nette\InvalidStateException(
×
771
                                        'Create a form or call Nette\Forms\Form::initialize() before the headers are sent to initialize CSRF protection.'
772
                                        . ($file ? " (output started at $file:$line)" : '') . '. ',
×
773
                                );
774
                        }
775

776
                        $response = new Nette\Http\Response;
×
777
                        $response->cookieSecure = self::$defaultHttpRequest->isSecured();
×
778
                        Nette\Http\Helpers::initCookie(self::$defaultHttpRequest, $response);
×
779
                }
780
        }
1✔
781

782

783
        private function getHttpRequest(): Nette\Http\IRequest
784
        {
785
                if (!isset($this->httpRequest)) {
1✔
786
                        self::initialize();
1✔
787
                        $this->httpRequest = self::$defaultHttpRequest;
1✔
788
                }
789

790
                return $this->httpRequest;
1✔
791
        }
792
}
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