From edc00e5b40510999b727db81fb41a1c7d62c881b Mon Sep 17 00:00:00 2001 From: David Grudl Date: Wed, 28 Oct 2026 18:35:32 +0100 Subject: [PATCH 01/47] BaseControl: added setFixedValue() for a value the user cannot change --- src/Forms/Controls/BaseControl.php | 12 ++++++++ tests/Controls/BaseControl.fixedValue.phpt | 35 ++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 tests/Controls/BaseControl.fixedValue.phpt diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index d13ab2fa..acb13298 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -221,6 +221,18 @@ public function isOmitted(): bool } + /** + * Sets a value the user cannot change: the control is disabled, ignores submitted data + * and its value stays among the form values. + */ + public function setFixedValue(mixed $value): static + { + return $this->setDisabled() + ->setOmitted(false) + ->setValue($value); + } + + /********************* rendering ****************d*g**/ diff --git a/tests/Controls/BaseControl.fixedValue.phpt b/tests/Controls/BaseControl.fixedValue.phpt new file mode 100644 index 00000000..be08ecaf --- /dev/null +++ b/tests/Controls/BaseControl.fixedValue.phpt @@ -0,0 +1,35 @@ +addText('id')->setFixedValue('123'); + + Assert::true($input->isDisabled()); + Assert::same('123', $input->getValue()); + Assert::same(['id' => '123'], $form->getValues('array')); + Assert::contains('disabled', (string) $input->getControl()); +}); + + +test('submitted value is ignored', function () { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['id' => 'tampered', 'name' => 'John']; + + $form = new Form; + $form->allowCrossOrigin(); + $form->addText('id')->setFixedValue('123'); + $form->addText('name'); + + Assert::truthy($form->isSubmitted()); + Assert::same(['id' => '123', 'name' => 'John'], $form->getValues('array')); +}); From 4e77cac340aba888726c96eeeaa95e3ad8b4b4e1 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Tue, 25 Nov 2025 01:01:49 +0100 Subject: [PATCH 02/47] opened 4.0-dev --- composer.json | 2 +- readme.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 2e8651c0..978e352c 100644 --- a/composer.json +++ b/composer.json @@ -45,7 +45,7 @@ }, "extra": { "branch-alias": { - "dev-master": "3.3-dev" + "dev-master": "4.0-dev" } }, "config": { diff --git a/readme.md b/readme.md index 4d9211f4..afad1fa2 100644 --- a/readme.md +++ b/readme.md @@ -2,10 +2,10 @@ Nette Forms: greatly facilitates web forms ========================================== [![Downloads this Month](https://img.shields.io/packagist/dm/nette/forms.svg)](https://packagist.org/packages/nette/forms) -[![Tests](https://github.com/nette/forms/actions/workflows/tests.yml/badge.svg?branch=v3.3)](https://github.com/nette/forms/actions) -[![Coverage Status](https://coveralls.io/repos/github/nette/forms/badge.svg?branch=v3.3)](https://coveralls.io/github/nette/forms?branch=v3.3) +[![Tests](https://github.com/nette/forms/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/nette/forms/actions) +[![Coverage Status](https://coveralls.io/repos/github/nette/forms/badge.svg?branch=master)](https://coveralls.io/github/nette/forms?branch=master) [![Latest Stable Version](https://poser.pugx.org/nette/forms/v/stable)](https://github.com/nette/forms/releases) -[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/forms/blob/v3.3/license.md) +[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/forms/blob/master/license.md) Introduction From 71d65edc0647175d98478be0bac953afe97a1e54 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Fri, 6 Nov 2026 02:01:33 +0100 Subject: [PATCH 03/47] requires PHP 8.4 --- .github/workflows/tests.yml | 6 +++--- AGENTS.md | 2 +- composer.json | 2 +- readme.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6b1ba05e..4cd30925 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -7,7 +7,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - php: ['8.3', '8.4', '8.5', '8.6'] + php: ['8.4', '8.5', '8.6'] fail-fast: false @@ -35,7 +35,7 @@ jobs: - uses: actions/checkout@v7 - uses: shivammathur/setup-php@v2 with: - php-version: 8.3 + php-version: 8.4 coverage: none - run: composer update --no-progress --prefer-dist --prefer-lowest --prefer-stable @@ -49,7 +49,7 @@ jobs: - uses: actions/checkout@v7 - uses: shivammathur/setup-php@v2 with: - php-version: 8.3 + php-version: 8.4 coverage: pcov - run: composer install --no-progress --prefer-dist diff --git a/AGENTS.md b/AGENTS.md index e81a8894..30a4af6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,7 +26,7 @@ is extended at release time from the git history. Nette Forms (since 2004) creates, validates, and processes web forms with **both** server-side (PHP) and client-side (`netteForms.ts`) validation kept in sync. -- **PHP Version**: 8.3 - 8.6 +- **PHP Version**: 8.4 - 8.6 - **Package**: `nette/forms` - **Dependencies**: nette/component-model, nette/http, nette/utils; Latte 3.1.5+. diff --git a/composer.json b/composer.json index 978e352c..3edb774b 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ } ], "require": { - "php": "8.3 - 8.6", + "php": "8.4 - 8.6", "nette/component-model": "^3.2 || ^4.0", "nette/http": "^3.4", "nette/utils": "^4.1" diff --git a/readme.md b/readme.md index afad1fa2..01772363 100644 --- a/readme.md +++ b/readme.md @@ -44,7 +44,7 @@ The recommended way to install is via Composer: composer require nette/forms ``` -It requires PHP version 8.3 and supports PHP up to 8.6. +It requires PHP version 8.4 and supports PHP up to 8.6. Client-side support can be installed with npm or yarn: From 0ea7d9ecc43d90aaa27e80e810b0112d0d49f7f4 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Fri, 6 Nov 2026 03:09:47 +0100 Subject: [PATCH 04/47] used PHP 8.4 features --- src/Forms/Container.php | 21 +++--- src/Forms/Controls/BaseControl.php | 4 +- src/Forms/Controls/Checkbox.php | 2 +- src/Forms/Controls/CsrfProtection.php | 2 +- src/Forms/Controls/MultiSelectBox.php | 2 +- src/Forms/Controls/SelectBox.php | 4 +- src/Forms/Controls/TextInput.php | 4 +- src/Forms/Controls/UploadControl.php | 5 +- src/Forms/Form.php | 72 +++++++++---------- src/Forms/Helpers.php | 2 +- src/Forms/Validator.php | 21 ++---- .../Controls/CsrfProtection.breachAttack.phpt | 2 +- tests/Controls/CsrfProtection.phpt | 4 +- tests/Controls/MultiSelectBox.render.phpt | 4 +- tests/Controls/SelectBox.render.phpt | 4 +- .../Forms/Container.values.mapping-enum.phpt | 2 +- tests/Forms/Forms.omittedValue.phpt | 2 +- 17 files changed, 71 insertions(+), 86 deletions(-) diff --git a/src/Forms/Container.php b/src/Forms/Container.php index fb2ac5f9..8b517201 100644 --- a/src/Forms/Container.php +++ b/src/Forms/Container.php @@ -140,7 +140,7 @@ public function getUntrustedValues(string|object|null $returnType = null, ?array { if (is_object($returnType)) { $resultObj = $returnType; - $properties = (new \ReflectionClass($resultObj))->getProperties(); + $properties = new \ReflectionClass($resultObj)->getProperties(); } else { $returnType ??= $this->mappedType ?? ArrayHash::class; @@ -191,6 +191,7 @@ public function getUntrustedValues(string|object|null $returnType = null, ?array * @return object|mixed[] * @deprecated use getUntrustedValues() */ + #[\Deprecated('use getUntrustedValues()')] public function getUnsafeValues(string|object|null $returnType, ?array $controls = null): object|array { return $this->getUntrustedValues($returnType, $controls); @@ -370,7 +371,7 @@ public function addText( ?int $maxLength = null, ): Controls\TextInput { - return $this[$name] = (new Controls\TextInput($label, $maxLength)) + return $this[$name] = new Controls\TextInput($label, $maxLength) ->setHtmlAttribute('size', $cols); } @@ -385,7 +386,7 @@ public function addPassword( ?int $maxLength = null, ): Controls\TextInput { - return $this[$name] = (new Controls\TextInput($label, $maxLength)) + return $this[$name] = new Controls\TextInput($label, $maxLength) ->setHtmlAttribute('size', $cols) ->setHtmlType('password'); } @@ -401,7 +402,7 @@ public function addTextArea( ?int $rows = null, ): Controls\TextArea { - return $this[$name] = (new Controls\TextArea($label)) + return $this[$name] = new Controls\TextArea($label) ->setHtmlAttribute('cols', $cols) ->setHtmlAttribute('rows', $rows); } @@ -416,7 +417,7 @@ public function addEmail( int $maxLength = 255, ): Controls\TextInput { - return $this[$name] = (new Controls\TextInput($label, $maxLength)) + return $this[$name] = new Controls\TextInput($label, $maxLength) ->addRule(Form::Email); } @@ -426,7 +427,7 @@ public function addEmail( */ public function addInteger(string $name, string|Stringable|null $label = null): Controls\TextInput { - return $this[$name] = (new Controls\TextInput($label)) + return $this[$name] = new Controls\TextInput($label) ->setNullable() ->addRule(Form::Integer); } @@ -437,7 +438,7 @@ public function addInteger(string $name, string|Stringable|null $label = null): */ public function addFloat(string $name, string|Stringable|null $label = null): Controls\TextInput { - return $this[$name] = (new Controls\TextInput($label)) + return $this[$name] = new Controls\TextInput($label) ->setNullable() ->setHtmlType('number') ->setHtmlAttribute('step', 'any') @@ -556,7 +557,7 @@ public function addSelect( ?int $size = null, ): Controls\SelectBox { - return $this[$name] = (new Controls\SelectBox($label, $items)) + return $this[$name] = new Controls\SelectBox($label, $items) ->setHtmlAttribute('size', $size > 1 ? $size : null); } @@ -572,7 +573,7 @@ public function addMultiSelect( ?int $size = null, ): Controls\MultiSelectBox { - return $this[$name] = (new Controls\MultiSelectBox($label, $items)) + return $this[$name] = new Controls\MultiSelectBox($label, $items) ->setHtmlAttribute('size', $size > 1 ? $size : null); } @@ -624,7 +625,7 @@ public function addImageButton(string $name, ?string $src = null, ?string $alt = } - /** @deprecated use addImageButton() */ + #[\Deprecated('use addImageButton()')] public function addImage(): Controls\ImageButton { return $this->addImageButton(...func_get_args()); diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index acb13298..e3d38419 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -350,9 +350,7 @@ public function setHtmlAttribute(string $name, mixed $value = true): static } - /** - * @deprecated use setHtmlAttribute() - */ + #[\Deprecated('use setHtmlAttribute()')] public function setAttribute(string $name, mixed $value = true): static { return $this->setHtmlAttribute($name, $value); diff --git a/src/Forms/Controls/Checkbox.php b/src/Forms/Controls/Checkbox.php index 080dfe0d..f1bddd29 100644 --- a/src/Forms/Controls/Checkbox.php +++ b/src/Forms/Controls/Checkbox.php @@ -91,7 +91,7 @@ public function getContainerPrototype(): Html } - /** @deprecated use getContainerPrototype() */ + #[\Deprecated('use getContainerPrototype()')] public function getSeparatorPrototype(): Html { return $this->container; diff --git a/src/Forms/Controls/CsrfProtection.php b/src/Forms/Controls/CsrfProtection.php index 635941f7..6921e321 100644 --- a/src/Forms/Controls/CsrfProtection.php +++ b/src/Forms/Controls/CsrfProtection.php @@ -19,7 +19,7 @@ class CsrfProtection extends HiddenField { public const Protection = 'Nette\Forms\Controls\CsrfProtection::validateCsrf'; - /** @deprecated use CsrfProtection::Protection */ + #[\Deprecated('use CsrfProtection::Protection')] public const PROTECTION = self::Protection; public ?Nette\Http\Session $session = null; diff --git a/src/Forms/Controls/MultiSelectBox.php b/src/Forms/Controls/MultiSelectBox.php index 80f9b7ba..209c1f87 100644 --- a/src/Forms/Controls/MultiSelectBox.php +++ b/src/Forms/Controls/MultiSelectBox.php @@ -78,8 +78,8 @@ public function getControl(): Nette\Utils\Html /** * @param array $attributes - * @deprecated use setOptionAttribute() */ + #[\Deprecated('use setOptionAttribute()')] public function addOptionAttributes(array $attributes): static { $this->optionAttributes = $attributes + $this->optionAttributes; diff --git a/src/Forms/Controls/SelectBox.php b/src/Forms/Controls/SelectBox.php index e4539db8..48f08ee3 100644 --- a/src/Forms/Controls/SelectBox.php +++ b/src/Forms/Controls/SelectBox.php @@ -20,7 +20,7 @@ class SelectBox extends ChoiceControl /** validation rule */ public const Valid = ':selectBoxValid'; - /** @deprecated use SelectBox::Valid */ + #[\Deprecated('use SelectBox::Valid')] public const VALID = self::Valid; /** @var mixed[] option / optgroup */ @@ -122,8 +122,8 @@ public function getControl(): Nette\Utils\Html /** * @param array $attributes - * @deprecated use setOptionAttribute() */ + #[\Deprecated('use setOptionAttribute()')] public function addOptionAttributes(array $attributes): static { $this->optionAttributes = $attributes + $this->optionAttributes; diff --git a/src/Forms/Controls/TextInput.php b/src/Forms/Controls/TextInput.php index bb988f4d..2a685859 100644 --- a/src/Forms/Controls/TextInput.php +++ b/src/Forms/Controls/TextInput.php @@ -42,9 +42,7 @@ public function setHtmlType(string $type): static } - /** - * @deprecated use setHtmlType() - */ + #[\Deprecated('use setHtmlType()')] public function setType(string $type): static { return $this->setHtmlType($type); diff --git a/src/Forms/Controls/UploadControl.php b/src/Forms/Controls/UploadControl.php index 67a89e89..d2f206a6 100644 --- a/src/Forms/Controls/UploadControl.php +++ b/src/Forms/Controls/UploadControl.php @@ -11,7 +11,6 @@ use Nette\Forms; use Nette\Forms\Form; use Nette\Http\FileUpload; -use Nette\Utils\Arrays; use Stringable; use function ini_get, is_array; @@ -24,7 +23,7 @@ class UploadControl extends BaseControl /** validation rule */ public const Valid = ':uploadControlValid'; - /** @deprecated use UploadControl::Valid */ + #[\Deprecated('use UploadControl::Valid')] public const VALID = self::Valid; private bool $nullable = false; @@ -118,7 +117,7 @@ public function isOk(): bool { return match (true) { !$this->value => false, - is_array($this->value) => Arrays::every($this->value, fn(FileUpload $upload): bool => $upload->isOk()), + is_array($this->value) => array_all($this->value, fn(FileUpload $upload): bool => $upload->isOk()), default => $this->value->isOk(), }; } diff --git a/src/Forms/Form.php b/src/Forms/Form.php index 06474019..1931691b 100644 --- a/src/Forms/Form.php +++ b/src/Forms/Form.php @@ -82,106 +82,106 @@ class Form extends Container implements Nette\HtmlStringable /** @internal protection token ID */ public const ProtectorId = '_token_'; - /** @deprecated use Form::Equal */ + #[\Deprecated('use Form::Equal')] public const EQUAL = self::Equal; - /** @deprecated use Form::IsIn */ + #[\Deprecated('use Form::IsIn')] public const IS_IN = self::IsIn; - /** @deprecated use Form::NotEqual */ + #[\Deprecated('use Form::NotEqual')] public const NOT_EQUAL = self::NotEqual; - /** @deprecated use Form::IsNotIn */ + #[\Deprecated('use Form::IsNotIn')] public const IS_NOT_IN = self::IsNotIn; - /** @deprecated use Form::Filled */ + #[\Deprecated('use Form::Filled')] public const FILLED = self::Filled; - /** @deprecated use Form::Blank */ + #[\Deprecated('use Form::Blank')] public const BLANK = self::Blank; - /** @deprecated use Form::Required */ + #[\Deprecated('use Form::Required')] public const REQUIRED = self::Required; - /** @deprecated use Form::Valid */ + #[\Deprecated('use Form::Valid')] public const VALID = self::Valid; - /** @deprecated use Form::Submitted */ + #[\Deprecated('use Form::Submitted')] public const SUBMITTED = self::Submitted; - /** @deprecated use Form::MinLength */ + #[\Deprecated('use Form::MinLength')] public const MIN_LENGTH = self::MinLength; - /** @deprecated use Form::MaxLength */ + #[\Deprecated('use Form::MaxLength')] public const MAX_LENGTH = self::MaxLength; - /** @deprecated use Form::Length */ + #[\Deprecated('use Form::Length')] public const LENGTH = self::Length; - /** @deprecated use Form::Email */ + #[\Deprecated('use Form::Email')] public const EMAIL = self::Email; - /** @deprecated use Form::Pattern */ + #[\Deprecated('use Form::Pattern')] public const PATTERN = self::Pattern; - /** @deprecated use Form::PatternInsensitive */ + #[\Deprecated('use Form::PatternInsensitive')] public const PATTERN_ICASE = self::PatternInsensitive; - /** @deprecated use Form::Integer */ + #[\Deprecated('use Form::Integer')] public const INTEGER = self::Integer; - /** @deprecated use Form::Numeric */ + #[\Deprecated('use Form::Numeric')] public const NUMERIC = self::Numeric; - /** @deprecated use Form::Float */ + #[\Deprecated('use Form::Float')] public const FLOAT = self::Float; - /** @deprecated use Form::Min */ + #[\Deprecated('use Form::Min')] public const MIN = self::Min; - /** @deprecated use Form::Max */ + #[\Deprecated('use Form::Max')] public const MAX = self::Max; - /** @deprecated use Form::Range */ + #[\Deprecated('use Form::Range')] public const RANGE = self::Range; - /** @deprecated use Form::Count */ + #[\Deprecated('use Form::Count')] public const COUNT = self::Count; - /** @deprecated use Form::MaxFileSize */ + #[\Deprecated('use Form::MaxFileSize')] public const MAX_FILE_SIZE = self::MaxFileSize; - /** @deprecated use Form::MimeType */ + #[\Deprecated('use Form::MimeType')] public const MIME_TYPE = self::MimeType; - /** @deprecated use Form::Image */ + #[\Deprecated('use Form::Image')] public const IMAGE = self::Image; - /** @deprecated use Form::MaxPostSize */ + #[\Deprecated('use Form::MaxPostSize')] public const MAX_POST_SIZE = self::MaxPostSize; - /** @deprecated use Form::Get */ + #[\Deprecated('use Form::Get')] public const GET = self::Get; - /** @deprecated use Form::Post */ + #[\Deprecated('use Form::Post')] public const POST = self::Post; - /** @deprecated use Form::DataText */ + #[\Deprecated('use Form::DataText')] public const DATA_TEXT = self::DataText; - /** @deprecated use Form::DataLine */ + #[\Deprecated('use Form::DataLine')] public const DATA_LINE = self::DataLine; - /** @deprecated use Form::DataFile */ + #[\Deprecated('use Form::DataFile')] public const DATA_FILE = self::DataFile; - /** @deprecated use Form::DataKeys */ + #[\Deprecated('use Form::DataKeys')] public const DATA_KEYS = self::DataKeys; - /** @deprecated use Form::TrackerId */ + #[\Deprecated('use Form::TrackerId')] public const TRACKER_ID = self::TrackerId; - /** @deprecated use Form::ProtectorId */ + #[\Deprecated('use Form::ProtectorId')] public const PROTECTOR_ID = self::ProtectorId; /** @@ -301,9 +301,7 @@ public function allowCrossOrigin(): void } - /** - * @deprecated default protection is sufficient - */ + #[\Deprecated('default protection is sufficient')] public function addProtection(?string $errorMessage = null): Controls\CsrfProtection { $control = new Controls\CsrfProtection($errorMessage); diff --git a/src/Forms/Helpers.php b/src/Forms/Helpers.php index 840afca7..006f5782 100644 --- a/src/Forms/Helpers.php +++ b/src/Forms/Helpers.php @@ -347,7 +347,7 @@ public static function tryEnumConversion( } // form values arrive as strings, so int-backed enums need explicit conversion - if ((new \ReflectionEnum($type))->getBackingType()?->getName() === 'int') { + if (new \ReflectionEnum($type)->getBackingType()?->getName() === 'int') { $int = filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE); return $int === null ? $value : ($type::tryFrom($int) ?? $value); } diff --git a/src/Forms/Validator.php b/src/Forms/Validator.php index 22c13a69..f8941756 100644 --- a/src/Forms/Validator.php +++ b/src/Forms/Validator.php @@ -337,7 +337,7 @@ public static function validateEnum(Control $control, string $enum): bool throw new Nette\InvalidArgumentException("The Enum validator requires a backed enum class, '$enum' given."); } - $intBacked = (new \ReflectionEnum($enum))->getBackingType()?->getName() === 'int'; + $intBacked = new \ReflectionEnum($enum)->getBackingType()?->getName() === 'int'; foreach (static::toArray($control->getValue()) as $value) { if ($intBacked) { $value = filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE); @@ -405,13 +405,10 @@ public static function validateFloat(Control $control): bool */ public static function validateFileSize(Controls\UploadControl $control, int $limit): bool { - foreach (static::toArray($control->getValue()) as $file) { - if ($file->getSize() > $limit || $file->getError() === UPLOAD_ERR_INI_SIZE) { - return false; - } - } - - return true; + return array_all( + static::toArray($control->getValue()), + fn($file) => $file->getSize() <= $limit && $file->getError() !== UPLOAD_ERR_INI_SIZE, + ); } @@ -438,13 +435,7 @@ public static function validateMimeType(Controls\UploadControl $control, string| */ public static function validateImage(Controls\UploadControl $control): bool { - foreach (static::toArray($control->getValue()) as $file) { - if (!$file->isImage()) { - return false; - } - } - - return true; + return array_all(static::toArray($control->getValue()), fn($file) => $file->isImage()); } diff --git a/tests/Controls/CsrfProtection.breachAttack.phpt b/tests/Controls/CsrfProtection.breachAttack.phpt index 78b6f45f..3fc13188 100644 --- a/tests/Controls/CsrfProtection.breachAttack.phpt +++ b/tests/Controls/CsrfProtection.breachAttack.phpt @@ -12,7 +12,7 @@ require __DIR__ . '/../bootstrap.php'; $form = new Form; -$input = $form->addProtection('Security token did not match. Possible CSRF attack.'); +$input = @$form->addProtection('Security token did not match. Possible CSRF attack.'); // @ addProtection() is deprecated $token = $input->getControl()->value; Assert::notSame($token, $input->getControl()->value); diff --git a/tests/Controls/CsrfProtection.phpt b/tests/Controls/CsrfProtection.phpt index 6425e435..81eb4f99 100644 --- a/tests/Controls/CsrfProtection.phpt +++ b/tests/Controls/CsrfProtection.phpt @@ -16,7 +16,7 @@ $_SERVER['REQUEST_METHOD'] = 'POST'; $form = new Form; $form->allowCrossOrigin(); -$input = $form->addProtection('Security token did not match. Possible CSRF attack.'); +$input = @$form->addProtection('Security token did not match. Possible CSRF attack.'); // @ addProtection() is deprecated $form->onSuccess[] = function () {}; $form->fireEvents(); @@ -48,7 +48,7 @@ Assert::false(CsrfProtection::validateCsrf($input)); $form = new Form; $form->allowCrossOrigin(); $form->addText('text'); -$form->addProtection(); +@$form->addProtection(); // @ addProtection() is deprecated Assert::same([ $form::ProtectorId => $form[$form::ProtectorId], 'text' => $form['text'], diff --git a/tests/Controls/MultiSelectBox.render.phpt b/tests/Controls/MultiSelectBox.render.phpt index 7c4b6e4d..8a68b992 100644 --- a/tests/Controls/MultiSelectBox.render.phpt +++ b/tests/Controls/MultiSelectBox.render.phpt @@ -176,8 +176,8 @@ test('dynamic option attributes', function () { 1 => 'First', 2 => 'Second', ])->setValue(1); - $input->addOptionAttributes(['bar' => 'b', 'selected?' => 2]); - $input->addOptionAttributes(['bar' => 'c']); + $input->setOptionAttribute('bar', 'c'); + $input->setOptionAttribute('selected?', 2); $input->setOptionAttribute('foo:', [1 => 'a', 2 => 'b']); Assert::same( '', diff --git a/tests/Controls/SelectBox.render.phpt b/tests/Controls/SelectBox.render.phpt index ef9f2ab3..80ddc0d1 100644 --- a/tests/Controls/SelectBox.render.phpt +++ b/tests/Controls/SelectBox.render.phpt @@ -280,8 +280,8 @@ test('dynamic option attributes', function () { 1 => 'First', 2 => 'Second', ])->setValue(1); - $input->addOptionAttributes(['bar' => 'b', 'selected?' => 2]); - $input->addOptionAttributes(['bar' => 'c']); + $input->setOptionAttribute('bar', 'c'); + $input->setOptionAttribute('selected?', 2); $input->setOptionAttribute('foo:', [1 => 'a', 2 => 'b']); Assert::same( '', diff --git a/tests/Forms/Container.values.mapping-enum.phpt b/tests/Forms/Container.values.mapping-enum.phpt index 7b7d0d73..e5578797 100644 --- a/tests/Forms/Container.values.mapping-enum.phpt +++ b/tests/Forms/Container.values.mapping-enum.phpt @@ -83,7 +83,7 @@ test('mapping a numeric string to a string-backed enum', function () { test('incompatible values are left unchanged instead of raising TypeError/ValueError', function () { $intRef = new ReflectionProperty(FormWithIntEnum::class, 'value'); - $strRef = (new ReflectionClass(FormWithEnum::class))->getConstructor()->getParameters()[0]; + $strRef = new ReflectionClass(FormWithEnum::class)->getConstructor()->getParameters()[0]; $strIntRef = new ReflectionProperty(FormWithStringIntEnum::class, 'value'); // int-backed enum diff --git a/tests/Forms/Forms.omittedValue.phpt b/tests/Forms/Forms.omittedValue.phpt index 94e74eef..b141a9ec 100644 --- a/tests/Forms/Forms.omittedValue.phpt +++ b/tests/Forms/Forms.omittedValue.phpt @@ -12,7 +12,7 @@ require __DIR__ . '/../bootstrap.php'; $form = new Form('name'); -$form->addProtection(); +@$form->addProtection(); // @ addProtection() is deprecated $form->addText('input'); $form->addText('omittedInput') ->setOmitted(); From cedd3bbb256793ba12b12661f15f44b6629d7044 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Wed, 24 Jun 2026 15:26:11 +0200 Subject: [PATCH 05/47] composer: increased dependencies versions --- composer.json | 2 +- src/Forms/Container.php | 7 ++----- src/Forms/Controls/BaseControl.php | 7 ++----- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/composer.json b/composer.json index 3edb774b..f5a5928e 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ ], "require": { "php": "8.4 - 8.6", - "nette/component-model": "^3.2 || ^4.0", + "nette/component-model": "^4.0", "nette/http": "^3.4", "nette/utils": "^4.1" }, diff --git a/src/Forms/Container.php b/src/Forms/Container.php index 8b517201..844dffe6 100644 --- a/src/Forms/Container.php +++ b/src/Forms/Container.php @@ -647,11 +647,8 @@ public function addContainer(string|int $name): self /********************* extension methods ****************d*g**/ - /** - * @param mixed[] $args - * @return mixed - */ - public function __call(string $name, array $args) + /** @param mixed[] $args */ + public function __call(string $name, array $args): mixed { if (isset(self::$extMethods[$name])) { /** @var never[] $args */ diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index e3d38419..51684eca 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -568,11 +568,8 @@ public function getOptions(): array /********************* extension methods ****************d*g**/ - /** - * @param mixed[] $args - * @return mixed - */ - public function __call(string $name, array $args) + /** @param mixed[] $args */ + public function __call(string $name, array $args): mixed { $class = static::class; do { From 97d1d0918b2e48bbb33437730f557a0ce8732e05 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sun, 28 Jun 2026 13:22:06 +0200 Subject: [PATCH 06/47] Latte: removed BC alias for the removed formsStack provider Reverts the formsStack compatibility alias. Runtime::begin() no longer takes the template $global nor binds $global->formsStack, and the {form}/
tags stop passing global: to it. Intended for the next major version, where the legacy formsStack provider support is dropped for good. --- src/Bridges/FormsLatte/FormsExtension.php | 2 +- .../FormsLatte/Nodes/FormNNameNode.php | 2 +- src/Bridges/FormsLatte/Nodes/FormNode.php | 2 +- src/Bridges/FormsLatte/Runtime.php | 6 +--- tests/Forms.Latte/Runtime.formsStack.phpt | 29 ------------------- tests/Forms.Latte/expected/forms.button.php | 2 +- .../expected/forms.detached-scope.php | 8 ++--- tests/Forms.Latte/expected/forms.detached.php | 6 ++-- .../expected/forms.formContainer.php | 2 +- tests/Forms.Latte/expected/forms.get.php | 4 +-- tests/Forms.Latte/expected/forms.php | 12 ++++---- tests/Forms.Latte/expected/forms.scope.php | 10 +++---- tests/Forms.Latte/n-name.form.phpt | 4 +-- 13 files changed, 28 insertions(+), 61 deletions(-) delete mode 100644 tests/Forms.Latte/Runtime.formsStack.phpt diff --git a/src/Bridges/FormsLatte/FormsExtension.php b/src/Bridges/FormsLatte/FormsExtension.php index a4034710..9bedc90a 100644 --- a/src/Bridges/FormsLatte/FormsExtension.php +++ b/src/Bridges/FormsLatte/FormsExtension.php @@ -46,6 +46,6 @@ public function getProviders(): array public function getCacheKey(Latte\Engine $engine): mixed { - return 2; + return 3; } } diff --git a/src/Bridges/FormsLatte/Nodes/FormNNameNode.php b/src/Bridges/FormsLatte/Nodes/FormNNameNode.php index 949d5e5c..84cdd40d 100644 --- a/src/Bridges/FormsLatte/Nodes/FormNNameNode.php +++ b/src/Bridges/FormsLatte/Nodes/FormNNameNode.php @@ -42,7 +42,7 @@ public function print(PrintContext $context): string . ($this->name instanceof StringNode ? '$this->global->uiControl[%node]' : '(is_object($ʟ_tmp = %node) ? $ʟ_tmp : $this->global->uiControl[$ʟ_tmp])') - . ', global: $this->global) %line;' + . ') %line;' . '%node ' . '$form = $this->global->forms->end() ?? $form;', $this->name, diff --git a/src/Bridges/FormsLatte/Nodes/FormNode.php b/src/Bridges/FormsLatte/Nodes/FormNode.php index b59ae092..fe447176 100644 --- a/src/Bridges/FormsLatte/Nodes/FormNode.php +++ b/src/Bridges/FormsLatte/Nodes/FormNode.php @@ -81,7 +81,7 @@ public function print(PrintContext $context): string default => '(is_object($ʟ_tmp = %node) ? $ʟ_tmp : $this->global->uiControl[$ʟ_tmp])', }) . ($this->mode === self::ModeDetached ? ', detached: true' : '') - . ', global: $this->global) %line;' + . ') %line;' . (match ($this->mode) { self::ModeScope, self::ModeLegacyScope => ' %3.node ', self::ModeDetached => $renderBegin . $renderEnd . ' %3.node ', diff --git a/src/Bridges/FormsLatte/Runtime.php b/src/Bridges/FormsLatte/Runtime.php index 04b794f6..93c11916 100644 --- a/src/Bridges/FormsLatte/Runtime.php +++ b/src/Bridges/FormsLatte/Runtime.php @@ -110,12 +110,8 @@ public function get(object|string|int $item, string $type = Control::class): Con } - public function begin(Container $form, bool $detached = false, ?\stdClass $global = null, bool $bindsForm = true): void + public function begin(Container $form, bool $detached = false, bool $bindsForm = true): void { - if ($global !== null) { - $global->formsStack = &$this->stack; // BC alias for the removed formsStack provider - } - $this->stack[] = $form; $this->formBindings[] = $bindsForm; diff --git a/tests/Forms.Latte/Runtime.formsStack.phpt b/tests/Forms.Latte/Runtime.formsStack.phpt deleted file mode 100644 index e83e9d39..00000000 --- a/tests/Forms.Latte/Runtime.formsStack.phpt +++ /dev/null @@ -1,29 +0,0 @@ -formsStack) works. - -use Nette\Bridges\FormsLatte\Runtime; -use Nette\Forms\Form; -use Tester\Assert; - -require __DIR__ . '/../bootstrap.php'; - - -$runtime = new Runtime; -$global = new stdClass; - -$form = new Form; -$container = $form->addContainer('person'); - -$runtime->begin($form, global: $global); -Assert::same($form, end($global->formsStack)); - -$runtime->begin($container); -Assert::same($container, end($global->formsStack)); - -$runtime->end(); -Assert::same($form, end($global->formsStack)); - -$runtime->end(); -Assert::same(false, end($global->formsStack)); diff --git a/tests/Forms.Latte/expected/forms.button.php b/tests/Forms.Latte/expected/forms.button.php index 35f9db48..c9d4948b 100644 --- a/tests/Forms.Latte/expected/forms.button.php +++ b/tests/Forms.Latte/expected/forms.button.php @@ -1,5 +1,5 @@ global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos 1:7 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos 1:7 */; echo 'global->forms->renderFormBegin([], false) /* pos 1:7 */; echo '> diff --git a/tests/Forms.Latte/expected/forms.detached-scope.php b/tests/Forms.Latte/expected/forms.detached-scope.php index 30eb1065..fe377077 100644 --- a/tests/Forms.Latte/expected/forms.detached-scope.php +++ b/tests/Forms.Latte/expected/forms.detached-scope.php @@ -1,5 +1,5 @@ global->forms->begin($form = $this->global->uiControl['main'], detached: true, global: $this->global) /* pos 4:1 */; + $this->global->forms->begin($form = $this->global->uiControl['main'], detached: true) /* pos 4:1 */; echo $this->global->forms->renderFormBegin([]) /* pos 4:1 */; echo $this->global->forms->renderFormEnd() /* pos 9:1 */; echo ' @@ -7,7 +7,7 @@ echo $this->global->forms->get('name')->getControl() /* pos 5:2 */; echo ' '; - $this->global->forms->begin($form = (is_object($ʟ_tmp = 'address') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp])), global: $this->global) /* pos 6:2 */; + $this->global->forms->begin($form = (is_object($ʟ_tmp = 'address') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp]))) /* pos 6:2 */; echo ' '; echo $this->global->forms->get('street')->getControl() /* pos 7:3 */; @@ -22,13 +22,13 @@ '; - $this->global->forms->begin($form = (is_object($ʟ_tmp = 'wrap') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp])), global: $this->global) /* pos 16:1 */; + $this->global->forms->begin($form = (is_object($ʟ_tmp = 'wrap') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp]))) /* pos 16:1 */; echo ' '; echo $this->global->forms->get('title')->getControl() /* pos 17:2 */; echo ' '; - $this->global->forms->begin($form = $this->global->uiControl['side'], detached: true, global: $this->global) /* pos 18:2 */; + $this->global->forms->begin($form = $this->global->uiControl['side'], detached: true) /* pos 18:2 */; echo $this->global->forms->renderFormBegin([]) /* pos 18:2 */; echo $this->global->forms->renderFormEnd() /* pos 20:2 */; echo ' diff --git a/tests/Forms.Latte/expected/forms.detached.php b/tests/Forms.Latte/expected/forms.detached.php index 8eb6a5fc..29708db1 100644 --- a/tests/Forms.Latte/expected/forms.detached.php +++ b/tests/Forms.Latte/expected/forms.detached.php @@ -1,5 +1,5 @@ global->forms->begin($form = $this->global->uiControl['myForm'], detached: true, global: $this->global) /* pos 5:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm'], detached: true) /* pos 5:1 */; echo $this->global->forms->renderFormBegin([]) /* pos 5:1 */; echo $this->global->forms->renderFormEnd() /* pos 12:1 */; echo ' @@ -24,7 +24,7 @@ '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], detached: true, global: $this->global) /* pos 17:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm'], detached: true) /* pos 17:1 */; echo $this->global->forms->renderFormBegin(['class' => 'shell']) /* pos 17:1 */; echo $this->global->forms->renderFormEnd() /* pos 19:1 */; echo ' @@ -38,7 +38,7 @@ '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], detached: true, global: $this->global) /* pos 24:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm'], detached: true) /* pos 24:1 */; echo $this->global->forms->renderFormBegin([]) /* pos 24:1 */; echo $this->global->forms->renderFormEnd() /* pos 33:1 */; echo ' diff --git a/tests/Forms.Latte/expected/forms.formContainer.php b/tests/Forms.Latte/expected/forms.formContainer.php index 66035d12..0491e268 100644 --- a/tests/Forms.Latte/expected/forms.formContainer.php +++ b/tests/Forms.Latte/expected/forms.formContainer.php @@ -1,5 +1,5 @@ global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos %d%:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:1 */; echo $this->global->forms->renderFormBegin([]) /* pos %d%:1 */; echo ' diff --git a/tests/Forms.Latte/expected/forms.get.php b/tests/Forms.Latte/expected/forms.get.php index 0d5d1bad..be9469dc 100644 --- a/tests/Forms.Latte/expected/forms.get.php +++ b/tests/Forms.Latte/expected/forms.get.php @@ -1,5 +1,5 @@ global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos 1:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos 1:1 */; echo $this->global->forms->renderFormBegin([]) /* pos 1:1 */; echo $this->global->forms->renderFormEnd() /* pos 1:1 */; $form = $this->global->forms->end() ?? $form; @@ -7,7 +7,7 @@ echo ' '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos 3:7 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos 3:7 */; echo 'global->forms->renderFormBegin([], false) /* pos 3:7 */; echo '> diff --git a/tests/Forms.Latte/expected/forms.php b/tests/Forms.Latte/expected/forms.php index 92f57c01..4823d9f5 100644 --- a/tests/Forms.Latte/expected/forms.php +++ b/tests/Forms.Latte/expected/forms.php @@ -1,5 +1,5 @@ global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos %d%:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:1 */; echo $this->global->forms->renderFormBegin(['id' => 'myForm', 'class' => 'ajax']) /* pos %d%:1 */; echo "\n"; foreach (['id', 'username', 'select', 'area', 'send'] as $name) /* pos %d%:2 */ { @@ -63,7 +63,7 @@ '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos %d%:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:1 */; echo $this->global->forms->renderFormBegin([]) /* pos %d%:1 */; echo $this->global->forms->renderFormEnd() /* pos %d%:1 */; $form = $this->global->forms->end() ?? $form; @@ -71,7 +71,7 @@ echo ' '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos %d%:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:1 */; echo $this->global->forms->renderFormBegin([]) /* pos %d%:1 */; echo "\n"; foreach ($form['sex']->items as $key => $label) /* pos %d%:1 */ { @@ -185,7 +185,7 @@ '; if (1) /* pos %d%:48 */ { - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos %d%:7 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:7 */; echo 'global->forms->renderFormBegin(['id' => null, 'class' => null], false) /* pos %d%:7 */; echo ' id="myForm" class="ajax"> @@ -201,7 +201,7 @@ echo ' '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos %d%:7 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:7 */; echo 'global->forms->renderFormBegin(['class' => null], false) /* pos %d%:7 */; echo ($ʟ_tmp = array_filter(['nclass'])) ? ' class="' . LR\HtmlHelpers::escapeAttr(implode(" ", array_unique($ʟ_tmp))) . '"' : "" /* pos %d%:23 */; @@ -245,7 +245,7 @@ '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos %d%:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:1 */; echo ' global->forms->get('sex')->getLabelPart())->attributes() /* pos %d%:8 */; diff --git a/tests/Forms.Latte/expected/forms.scope.php b/tests/Forms.Latte/expected/forms.scope.php index 7e4886e5..6f2be0a0 100644 --- a/tests/Forms.Latte/expected/forms.scope.php +++ b/tests/Forms.Latte/expected/forms.scope.php @@ -1,5 +1,5 @@ global->forms->begin($form = (is_object($ʟ_tmp = 'myForm') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp])), global: $this->global) /* pos 3:1 */; + $this->global->forms->begin($form = (is_object($ʟ_tmp = 'myForm') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp]))) /* pos 3:1 */; echo ' '; echo ($ʟ_label = $this->global->forms->get('name')->getLabel()) /* pos 4:2 */; @@ -13,7 +13,7 @@ '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos 11:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos 11:1 */; echo ' '; echo ($ʟ_label = $this->global->forms->get('name')->getLabel()) /* pos 12:2 */; @@ -27,7 +27,7 @@ '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos 19:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos 19:1 */; echo $this->global->forms->renderFormBegin(['class' => 'outer']) /* pos 19:1 */; echo ' '; @@ -35,7 +35,7 @@ echo ' '; - $this->global->forms->begin($form = (is_object($ʟ_tmp = 'person') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp])), global: $this->global) /* pos 22:2 */; + $this->global->forms->begin($form = (is_object($ʟ_tmp = 'person') ? $ʟ_tmp : ($this->global->forms->isNested() ? $this->global->forms->get($ʟ_tmp, Nette\Forms\Container::class) : $this->global->uiControl[$ʟ_tmp]))) /* pos 22:2 */; echo ' '; echo $this->global->forms->get('city')->getControl() /* pos 23:3 */; @@ -51,7 +51,7 @@ '; - $this->global->forms->begin($form = $this->global->uiControl['myForm'], global: $this->global) /* pos 30:1 */; + $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos 30:1 */; echo $this->global->forms->renderFormBegin(['class' => 'outer']) /* pos 30:1 */; echo ' '; diff --git a/tests/Forms.Latte/n-name.form.phpt b/tests/Forms.Latte/n-name.form.phpt index 3a8637b8..083e8d97 100644 --- a/tests/Forms.Latte/n-name.form.phpt +++ b/tests/Forms.Latte/n-name.form.phpt @@ -13,7 +13,7 @@ $latte->addExtension(new FormsExtension); Assert::match( <<<'XX' %A% - $this->global->forms->begin($form = $this->global->uiControl['foo'], global: $this->global) /* pos 1:7 */; + $this->global->forms->begin($form = $this->global->uiControl['foo']) /* pos 1:7 */; echo 'global->forms->renderFormBegin([], false) /* pos 1:7 */; echo '>'; @@ -29,7 +29,7 @@ Assert::match( Assert::match( <<<'XX' %A% - $this->global->forms->begin($form = $this->global->uiControl['foo'], global: $this->global) /* pos 1:18 */; + $this->global->forms->begin($form = $this->global->uiControl['foo']) /* pos 1:18 */; $ʟ_tag = ''; if (0) /* pos 1:7 */ { $ʟ_tag = '' . $ʟ_tag; From 459656aa9d2f2c26e41c8b4a15861e128ce1a307 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Tue, 20 Dec 2022 00:33:10 +0100 Subject: [PATCH 07/47] removed compatibility for old class names --- phpstan.neon | 3 --- src/Forms/Control.php | 3 --- src/Forms/FormRenderer.php | 3 --- src/Forms/SubmitterControl.php | 3 --- src/compatibility.php | 35 ---------------------------------- 5 files changed, 47 deletions(-) delete mode 100644 src/compatibility.php diff --git a/phpstan.neon b/phpstan.neon index 7b3ef4f6..3cefb7df 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -4,9 +4,6 @@ parameters: paths: - src - excludePaths: - - src/compatibility.php - ignoreErrors: - # Latte nodes use new static() by design for extensibility identifier: new.static diff --git a/src/Forms/Control.php b/src/Forms/Control.php index 7eafdd11..e38cfbdd 100644 --- a/src/Forms/Control.php +++ b/src/Forms/Control.php @@ -34,6 +34,3 @@ function getErrors(): array; */ function isOmitted(): bool; } - - -interface_exists(IControl::class); diff --git a/src/Forms/FormRenderer.php b/src/Forms/FormRenderer.php index 99a274d0..35cb8748 100644 --- a/src/Forms/FormRenderer.php +++ b/src/Forms/FormRenderer.php @@ -18,6 +18,3 @@ interface FormRenderer */ function render(Form $form): string; } - - -interface_exists(IFormRenderer::class); diff --git a/src/Forms/SubmitterControl.php b/src/Forms/SubmitterControl.php index 54605880..0d52f409 100644 --- a/src/Forms/SubmitterControl.php +++ b/src/Forms/SubmitterControl.php @@ -19,6 +19,3 @@ interface SubmitterControl extends Control */ function getValidationScope(): ?array; } - - -interface_exists(ISubmitterControl::class); diff --git a/src/compatibility.php b/src/compatibility.php deleted file mode 100644 index 5c6a5a9b..00000000 --- a/src/compatibility.php +++ /dev/null @@ -1,35 +0,0 @@ - Date: Tue, 10 Feb 2026 06:14:16 +0100 Subject: [PATCH 08/47] removed deprecated CsrfProtection control and related code Deleted CsrfProtection class, its tests, ProtectorId constant, and validation message. The addProtection() method now only triggers a deprecation warning. --- dresscode.neon | 3 - src/Forms/Controls/CsrfProtection.php | 100 ------------------ src/Forms/Form.php | 17 +-- src/Forms/Validator.php | 1 - .../Controls/CsrfProtection.breachAttack.phpt | 55 ---------- tests/Controls/CsrfProtection.phpt | 55 ---------- 6 files changed, 1 insertion(+), 230 deletions(-) delete mode 100644 src/Forms/Controls/CsrfProtection.php delete mode 100644 tests/Controls/CsrfProtection.breachAttack.phpt delete mode 100644 tests/Controls/CsrfProtection.phpt diff --git a/dresscode.neon b/dresscode.neon index dac836fb..25487b47 100644 --- a/dresscode.neon +++ b/dresscode.neon @@ -25,9 +25,6 @@ overrides: use: - compilerOptimizations - deprecations - - # the BC branch of the deprecated addProtection() and its message - paths: [src/Forms/Form.php, src/Forms/Validator.php] - upgrading: {declarations: {deprecatedClass: keep}} - # Form::URL is established public API paths: [src/Forms/Form.php] naming: {constant: keep} diff --git a/src/Forms/Controls/CsrfProtection.php b/src/Forms/Controls/CsrfProtection.php deleted file mode 100644 index 6921e321..00000000 --- a/src/Forms/Controls/CsrfProtection.php +++ /dev/null @@ -1,100 +0,0 @@ -setOmitted() - ->setRequired() - ->addRule(self::Protection, $errorMessage); - - $this->monitor(Presenter::class, function (Presenter $presenter): void { - if (!$this->session) { - $this->session = $presenter->getSession(); - $this->session->start(); - } - }); - - $this->monitor(Nette\Forms\Form::class, function (Nette\Forms\Form $form): void { - if (!$this->session && !$form instanceof Nette\Application\UI\Form) { - $this->session = new Nette\Http\Session($form->httpRequest, new Nette\Http\Response); - $this->session->start(); - } - }); - } - - - /** - * @internal - */ - public function setValue(mixed $value): static - { - return $this; - } - - - public function loadHttpData(): void - { - $this->value = $this->getHttpData(Nette\Forms\Form::DataText); - } - - - public function getToken(): string - { - if (!$this->session) { - throw new Nette\InvalidStateException('Session initialization error'); - } - - $session = $this->session->getSection(self::class); - if (!$session->get('token')) { - $session->set('token', Nette\Utils\Random::generate()); - } - - return $session->get('token') ^ $this->session->getId(); - } - - - private function generateToken(?string $random = null): string - { - $random ??= Nette\Utils\Random::generate(); - return $random . base64_encode(sha1($this->getToken() . $random, binary: true)); - } - - - public function getControl(): Nette\Utils\Html - { - return parent::getControl()->value($this->generateToken()); - } - - - /** @internal */ - public static function validateCsrf(self $control): bool - { - $value = (string) $control->getValue(); - return $control->generateToken(substr($value, 0, 10)) === $value; - } -} diff --git a/src/Forms/Form.php b/src/Forms/Form.php index 1931691b..e4d81cd1 100644 --- a/src/Forms/Form.php +++ b/src/Forms/Form.php @@ -79,9 +79,6 @@ class Form extends Container implements Nette\HtmlStringable /** @internal tracker ID */ public const TrackerId = '_form_'; - /** @internal protection token ID */ - public const ProtectorId = '_token_'; - #[\Deprecated('use Form::Equal')] public const EQUAL = self::Equal; @@ -181,9 +178,6 @@ class Form extends Container implements Nette\HtmlStringable #[\Deprecated('use Form::TrackerId')] public const TRACKER_ID = self::TrackerId; - #[\Deprecated('use Form::ProtectorId')] - public const PROTECTOR_ID = self::ProtectorId; - /** * Occurs when the form is submitted and successfully validated * @var array @@ -302,17 +296,8 @@ public function allowCrossOrigin(): void #[\Deprecated('default protection is sufficient')] - public function addProtection(?string $errorMessage = null): Controls\CsrfProtection + public function addProtection(?string $errorMessage = null): void { - $control = new Controls\CsrfProtection($errorMessage); - $first = null; - foreach ($this->getComponents() as $name => $component) { - $first = (string) $name; - break; - } - - $this->addComponent($control, self::ProtectorId, $first); - return $control; } diff --git a/src/Forms/Validator.php b/src/Forms/Validator.php index f8941756..da868ad5 100644 --- a/src/Forms/Validator.php +++ b/src/Forms/Validator.php @@ -21,7 +21,6 @@ final class Validator /** @var array */ public static array $messages = [ - Controls\CsrfProtection::Protection => 'Your session has expired. Please return to the home page and try again.', Form::Equal => 'Please enter %s.', Form::NotEqual => 'This value should not be %s.', Form::Filled => 'This field is required.', diff --git a/tests/Controls/CsrfProtection.breachAttack.phpt b/tests/Controls/CsrfProtection.breachAttack.phpt deleted file mode 100644 index 3fc13188..00000000 --- a/tests/Controls/CsrfProtection.breachAttack.phpt +++ /dev/null @@ -1,55 +0,0 @@ -addProtection('Security token did not match. Possible CSRF attack.'); // @ addProtection() is deprecated -$token = $input->getControl()->value; - -Assert::notSame($token, $input->getControl()->value); - -/* BREACH attack test: skipped because $input->getControl() always generates different token -$charlist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -$charCount = strlen($charlist); - -$strings = []; -for ($a = 0; $a < $charCount; $a++) { - for ($b = 0; $b < $charCount; $b++) { - $strings[] = $charlist[$a] . $charlist[$b]; - } -} - -for ($i = 3; $i <= strlen($token); $i++) { - $code = (string) $input->getControl(); - $shortest = null; - $adepts = []; - foreach ($strings as $string) { - for ($j = 0; $j < $charCount; $j++) { - $try = $string . $charlist[$j]; - $length = strlen(gzdeflate($code . $try)); - if ($shortest === null || $length < $shortest) { - $shortest = $length; - $adepts = []; - } - if ($shortest === $length) { - $adepts[] = $try; - } - } - } - $strings = $adepts; -} - -foreach ($strings as $string) { - $input->setValue($string); - Assert::false(CsrfProtection::validateCsrf($input)); -} -*/ diff --git a/tests/Controls/CsrfProtection.phpt b/tests/Controls/CsrfProtection.phpt deleted file mode 100644 index 81eb4f99..00000000 --- a/tests/Controls/CsrfProtection.phpt +++ /dev/null @@ -1,55 +0,0 @@ -allowCrossOrigin(); - -$input = @$form->addProtection('Security token did not match. Possible CSRF attack.'); // @ addProtection() is deprecated - -$form->onSuccess[] = function () {}; -$form->fireEvents(); - -Assert::same(['This field is required.'], $form->getErrors()); -Assert::null($input->getOption('rendered')); -Assert::match('', (string) $input->getControl()); -Assert::true($input->getOption('rendered')); -Assert::same('hidden', $input->getOption('type')); - -$input->setValue(null); -Assert::false(CsrfProtection::validateCsrf($input)); - -$setValue = new ReflectionMethod(BaseControl::class, 'setValue'); -$setValue->invoke($input, '12345678901234567890123456789012345678'); -Assert::false(CsrfProtection::validateCsrf($input)); - -$value = $input->getControl()->value; -$setValue->invoke($input, $value); -Assert::true(CsrfProtection::validateCsrf($input)); - -session_regenerate_id(); -$setValue->invoke($input, $value); -Assert::false(CsrfProtection::validateCsrf($input)); - - - -// protection is always the first -$form = new Form; -$form->allowCrossOrigin(); -$form->addText('text'); -@$form->addProtection(); // @ addProtection() is deprecated -Assert::same([ - $form::ProtectorId => $form[$form::ProtectorId], - 'text' => $form['text'], -], $form->getComponents()); From 4e56bbaf049226f17eecdaef5224c5512cc2a9e4 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Mon, 29 Jun 2026 22:14:55 +0200 Subject: [PATCH 09/47] InputNode, LabelNode: deprecate missing comma before arguments Extends the {form} deprecation to {input} and {label}, which share the same "name[:part] followed by bare arguments without a comma" syntax. Triggers E_USER_DEPRECATED when a token follows the name (and optional :part) without a separating comma, pointing to the offending column; the tag still compiles. A genuinely malformed {input foo: class=>val} emits the deprecation alongside the existing CompileException, which is correct: the comma really is missing (canonical: {input foo:, class=>val}). All three Forms tags route through Latte's shared TagParser::consumeCommaBeforeArguments() helper, so {form} is converted from its inline check too -- no duplicated logic. --- src/Bridges/FormsLatte/Nodes/InputNode.php | 2 +- src/Bridges/FormsLatte/Nodes/LabelNode.php | 2 +- tests/Forms.Latte/expected/forms.php | 4 ++-- tests/Forms.Latte/forms.commaWarning.phpt | 27 ++++++++++++++++++++++ tests/Forms.Latte/templates/forms.latte | 4 ++-- tests/Forms.Latte/{input}.phpt | 19 ++++++++------- tests/Forms.Latte/{label}.phpt | 19 ++++++++------- 7 files changed, 55 insertions(+), 22 deletions(-) diff --git a/src/Bridges/FormsLatte/Nodes/InputNode.php b/src/Bridges/FormsLatte/Nodes/InputNode.php index 0fe39e69..9596c8ac 100644 --- a/src/Bridges/FormsLatte/Nodes/InputNode.php +++ b/src/Bridges/FormsLatte/Nodes/InputNode.php @@ -37,7 +37,7 @@ public static function create(Tag $tag): static ? new StringNode('') : $tag->parser->parseUnquotedStringOrExpression(); } - $tag->parser->stream->tryConsume(','); + $tag->parser->consumeCommaBeforeArguments(strict: false); $node->attributes = $tag->parser->parseArguments(); return $node; } diff --git a/src/Bridges/FormsLatte/Nodes/LabelNode.php b/src/Bridges/FormsLatte/Nodes/LabelNode.php index 049cffb9..eeeea506 100644 --- a/src/Bridges/FormsLatte/Nodes/LabelNode.php +++ b/src/Bridges/FormsLatte/Nodes/LabelNode.php @@ -47,7 +47,7 @@ public static function create(Tag $tag): \Generator : $tag->parser->parseUnquotedStringOrExpression(); } - $tag->parser->stream->tryConsume(','); + $tag->parser->consumeCommaBeforeArguments(strict: false); $node->attributes = $tag->parser->parseArguments(); $node->void = $tag->void; [$node->content] = yield; diff --git a/tests/Forms.Latte/expected/forms.php b/tests/Forms.Latte/expected/forms.php index 4823d9f5..751dca51 100644 --- a/tests/Forms.Latte/expected/forms.php +++ b/tests/Forms.Latte/expected/forms.php @@ -18,9 +18,9 @@ '; echo ($ʟ_label = $this->global->forms->get($form[$name])->getLabel())?->addAttributes(['title' => 'hello'])?->startTag() /* pos %d%:3 */; echo ' '; - echo $this->global->forms->get($form[$name])->getControl()->addAttributes(['title' => 'Hello', 'size' => 10]) /* pos %d%:39 */; + echo $this->global->forms->get($form[$name])->getControl()->addAttributes(['title' => 'Hello', 'size' => 10]) /* pos %d%:40 */; echo ' '; - echo $ʟ_label?->endTag() /* pos %d%:87 */; + echo $ʟ_label?->endTag() /* pos %d%:89 */; echo ' '; echo LR\HtmlHelpers::escapeText($this->global->forms->get($form[$name])->getError()) /* pos %d%:3 */; diff --git a/tests/Forms.Latte/forms.commaWarning.phpt b/tests/Forms.Latte/forms.commaWarning.phpt index 516746a0..d7a5fd70 100644 --- a/tests/Forms.Latte/forms.commaWarning.phpt +++ b/tests/Forms.Latte/forms.commaWarning.phpt @@ -33,3 +33,30 @@ test('deprecation warning when comma is missing before arguments', function () u 'Missing comma before tag arguments on line 1 at column 14.', ); }); + + +test('deprecation warning when comma is missing in {input}', function () use ($latte) { + Assert::error( + fn() => $latte->compile("{input name class => 'a'}\n"), + E_USER_DEPRECATED, + 'Missing comma before tag arguments on line 1 at column 13.', + ); +}); + + +test('deprecation warning when comma is missing in {label}', function () use ($latte) { + Assert::error( + fn() => $latte->compile("{label name class => 'a' /}\n"), + E_USER_DEPRECATED, + 'Missing comma before tag arguments on line 1 at column 13.', + ); +}); + + +test('deprecation warning also fires after the :part syntax', function () use ($latte) { + Assert::error( + fn() => $latte->compile("{input name:x class => 'a'}\n"), + E_USER_DEPRECATED, + 'Missing comma before tag arguments on line 1 at column 15.', + ); +}); diff --git a/tests/Forms.Latte/templates/forms.latte b/tests/Forms.Latte/templates/forms.latte index b9f30cec..ad20bf6f 100644 --- a/tests/Forms.Latte/templates/forms.latte +++ b/tests/Forms.Latte/templates/forms.latte @@ -1,12 +1,12 @@ {form myForm, id => myForm, class=>"ajax"} {foreach [id, username, select, area, send] as $name} {label $name /} - {input $name title => Hello, size => 10} + {input $name, title => Hello, size => 10} {inputError $name}
- {label $form[$name] title => hello} {input $form[$name] title => Hello, size => 10} {/label} + {label $form[$name], title => hello} {input $form[$name], title => Hello, size => 10} {/label} {inputError $form[$name]} {/foreach} diff --git a/tests/Forms.Latte/{input}.phpt b/tests/Forms.Latte/{input}.phpt index 4b8baec1..4fb99a89 100644 --- a/tests/Forms.Latte/{input}.phpt +++ b/tests/Forms.Latte/{input}.phpt @@ -15,9 +15,10 @@ Assert::match( $latte->compile('{input foo}'), ); -Assert::match( - '%A%echo $this->global->forms->get(\'foo\')->getControl()->addAttributes([\'class\' => \'foo\']) %A%', - $latte->compile('{input foo class => foo}'), +Assert::error( + fn() => $latte->compile('{input foo class => foo}'), + E_USER_DEPRECATED, + 'Missing comma before tag arguments on line 1 at column 12.', ); Assert::match( @@ -30,11 +31,13 @@ Assert::match( $latte->compile('{input foo:}'), ); -Assert::exception( - fn() => $latte->compile('{input foo: class => foo}'), - Latte\CompileException::class, - "Unexpected '=>', expecting end of tag in {input} (on line 1 at column 19)", -); +Assert::error(function () use ($latte) { + Assert::exception( + fn() => $latte->compile('{input foo: class => foo}'), + Latte\CompileException::class, + "Unexpected '=>', expecting end of tag in {input} (on line 1 at column 19)", + ); +}, E_USER_DEPRECATED, 'Missing comma before tag arguments on line 1 at column 19.'); Assert::match( '%A%echo $this->global->forms->get(\'foo\')->getControlPart(\'\') %A%', diff --git a/tests/Forms.Latte/{label}.phpt b/tests/Forms.Latte/{label}.phpt index 9c4302f1..247c79d3 100644 --- a/tests/Forms.Latte/{label}.phpt +++ b/tests/Forms.Latte/{label}.phpt @@ -15,9 +15,10 @@ Assert::match( $latte->compile('{label foo /}'), ); -Assert::match( - '%A%echo ($ʟ_label = $this->global->forms->get(\'foo\')->getLabel())?->addAttributes([\'class\' => \'foo\']) %A%', - $latte->compile('{label foo class => foo /}'), +Assert::error( + fn() => $latte->compile('{label foo class => foo /}'), + E_USER_DEPRECATED, + 'Missing comma before tag arguments on line 1 at column 12.', ); Assert::match( @@ -30,11 +31,13 @@ Assert::match( $latte->compile('{label foo: /}'), ); -Assert::exception( - fn() => $latte->compile('{label foo: class => foo /}'), - Latte\CompileException::class, - "Unexpected '=>', expecting end of tag in {label} (on line 1 at column 19)", -); +Assert::error(function () use ($latte) { + Assert::exception( + fn() => $latte->compile('{label foo: class => foo /}'), + Latte\CompileException::class, + "Unexpected '=>', expecting end of tag in {label} (on line 1 at column 19)", + ); +}, E_USER_DEPRECATED, 'Missing comma before tag arguments on line 1 at column 19.'); Assert::match( '%A%echo ($ʟ_label = $this->global->forms->get(\'foo\')->getLabelPart(\'\')) %A%', From c3ec6697049f04c7afc719f3ba294998efae69d1 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 25 Jun 2026 15:28:56 +0200 Subject: [PATCH 10/47] added type hints (BC break) --- src/Forms/Control.php | 8 ++---- src/Forms/Controls/BaseControl.php | 30 +++++++++-------------- src/Forms/Controls/Button.php | 2 +- src/Forms/Controls/Checkbox.php | 9 +++---- src/Forms/Controls/CheckboxList.php | 6 ++--- src/Forms/Controls/ChoiceControl.php | 6 ++--- src/Forms/Controls/HiddenField.php | 9 +++---- src/Forms/Controls/MultiChoiceControl.php | 10 +++----- src/Forms/Controls/MultiSelectBox.php | 3 +-- src/Forms/Controls/RadioList.php | 6 ++--- src/Forms/Controls/SelectBox.php | 3 +-- src/Forms/Controls/SubmitButton.php | 2 +- src/Forms/Controls/TextBase.php | 15 ++++-------- src/Forms/Controls/TextInput.php | 8 +++--- src/Forms/Controls/UploadControl.php | 15 ++++-------- src/Forms/Form.php | 4 +-- 16 files changed, 48 insertions(+), 88 deletions(-) diff --git a/src/Forms/Control.php b/src/Forms/Control.php index e38cfbdd..77943378 100644 --- a/src/Forms/Control.php +++ b/src/Forms/Control.php @@ -13,13 +13,9 @@ */ interface Control { - /** - * @return static - */ - function setValue(mixed $value); + function setValue(mixed $value): static; - /** @return mixed */ - function getValue(); + function getValue(): mixed; function validate(): void; diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index 51684eca..6df80f65 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -133,19 +133,15 @@ public function getHtmlName(): string /********************* interface Control ****************d*g**/ - /** - * @return static - * @internal - */ - public function setValue(mixed $value) + /** @internal */ + public function setValue($value): static { $this->value = $value; return $this; } - /** @return mixed */ - public function getValue() + public function getValue(): mixed { return $this->value; } @@ -163,9 +159,8 @@ public function isFilled(): bool /** * Sets the default value. Has no effect on submitted or disabled controls. - * @return static */ - public function setDefaultValue(mixed $value) + public function setDefaultValue(mixed $value): static { $form = $this->getForm(throw: false); if ($this->isDisabled() || !$form || !$form->isAnchored() || !$form->isSubmitted()) { @@ -178,9 +173,8 @@ public function setDefaultValue(mixed $value) /** * Disables or enables control. - * @return static */ - public function setDisabled(bool $state = true) + public function setDisabled(bool $state = true): static { $this->disabled = $state; if ($state) { @@ -238,9 +232,8 @@ public function setFixedValue(mixed $value): static /** * Generates control's HTML element. - * @return Html|string */ - public function getControl() + public function getControl(): Html|string { $this->setOption('rendered', true); $el = clone $this->control; @@ -256,9 +249,8 @@ public function getControl() /** * Generates label's HTML element. - * @return Html|string|null */ - public function getLabel(string|Stringable|null $caption = null) + public function getLabel(string|Stringable|null $caption = null): Html|string|null { $label = clone $this->label; $label->for = $this->getHtmlId(); @@ -406,13 +398,13 @@ public function translate(mixed $value, mixed ...$parameters): mixed /** * Adds a validation rule. * @param (callable(never, never): bool)|string $validator - * @return static */ public function addRule( callable|string $validator, string|Stringable|null $errorMessage = null, mixed $arg = null, - ) { + ): static + { $this->rules->addRule($validator, $errorMessage, $arg); return $this; } @@ -422,7 +414,7 @@ public function addRule( * Adds a validation condition and returns a new branch. * @param (callable(never, never): bool)|string|bool $validator */ - public function addCondition($validator, mixed $value = null): Rules + public function addCondition(callable|string|bool $validator, mixed $value = null): Rules { return $this->rules->addCondition($validator, $value); } @@ -432,7 +424,7 @@ public function addCondition($validator, mixed $value = null): Rules * Adds a validation condition based on another control and returns a new branch. * @param (callable(never, never): bool)|string $validator */ - public function addConditionOn(Control $control, $validator, mixed $value = null): Rules + public function addConditionOn(Control $control, callable|string $validator, mixed $value = null): Rules { return $this->rules->addConditionOn($control, $validator, $value); } diff --git a/src/Forms/Controls/Button.php b/src/Forms/Controls/Button.php index 999d1d72..6d6c7dda 100644 --- a/src/Forms/Controls/Button.php +++ b/src/Forms/Controls/Button.php @@ -38,7 +38,7 @@ public function isFilled(): bool /** * Bypasses label generation. */ - public function getLabel($caption = null): Html|string|null + public function getLabel(string|Stringable|null $caption = null): Html|string|null { return null; } diff --git a/src/Forms/Controls/Checkbox.php b/src/Forms/Controls/Checkbox.php index f1bddd29..0173f104 100644 --- a/src/Forms/Controls/Checkbox.php +++ b/src/Forms/Controls/Checkbox.php @@ -30,11 +30,8 @@ public function __construct(string|Stringable|null $label = null) } - /** - * @return static - * @internal - */ - public function setValue(mixed $value) + /** @internal */ + public function setValue(mixed $value): static { if (!is_scalar($value) && $value !== null) { throw new Nette\InvalidArgumentException(sprintf( @@ -64,7 +61,7 @@ public function getControl(): Html /** * Bypasses label generation. */ - public function getLabel($caption = null): Html|string|null + public function getLabel(string|Stringable|null $caption = null): Html|string|null { return null; } diff --git a/src/Forms/Controls/CheckboxList.php b/src/Forms/Controls/CheckboxList.php index b541dc77..a08902a9 100644 --- a/src/Forms/Controls/CheckboxList.php +++ b/src/Forms/Controls/CheckboxList.php @@ -76,7 +76,7 @@ public function getControl(): Html } - public function getLabel($caption = null): Html + public function getLabel(string|Stringable|null $caption = null): Html { return parent::getLabel($caption)->for(null); } @@ -85,7 +85,7 @@ public function getLabel($caption = null): Html /** * Returns the HTML input element for a specific checkbox item by key. */ - public function getControlPart($key = null): Html + public function getControlPart(int|string|null $key = null): Html { $this->getItem($key); return parent::getControl()->addAttributes([ @@ -101,7 +101,7 @@ public function getControlPart($key = null): Html /** * Returns the label element for the whole checkbox list, or the item label for a specific key. */ - public function getLabelPart($key = null): Html + public function getLabelPart(int|string|null $key = null): Html { $itemLabel = clone $this->itemLabel; return func_num_args() diff --git a/src/Forms/Controls/ChoiceControl.php b/src/Forms/Controls/ChoiceControl.php index 54940e64..d140339d 100644 --- a/src/Forms/Controls/ChoiceControl.php +++ b/src/Forms/Controls/ChoiceControl.php @@ -46,10 +46,9 @@ public function loadHttpData(): void /** * Sets selected item (by key). * @param string|int|\BackedEnum|null $value - * @return static * @internal */ - public function setValue($value) + public function setValue($value): static { if ($value instanceof \BackedEnum) { $value = $value->value; @@ -104,9 +103,8 @@ public function isFilled(): bool /** * Sets items from which to choose. When $useKeys is false, values are used as keys too. * @param mixed[] $items - * @return static */ - public function setItems(array $items, bool $useKeys = true) + public function setItems(array $items, bool $useKeys = true): static { $this->items = $useKeys ? $items : array_combine($items, $items); return $this; diff --git a/src/Forms/Controls/HiddenField.php b/src/Forms/Controls/HiddenField.php index d72fb03d..f9e983cd 100644 --- a/src/Forms/Controls/HiddenField.php +++ b/src/Forms/Controls/HiddenField.php @@ -36,11 +36,8 @@ public function __construct(mixed $persistentValue = null) } - /** - * @return static - * @internal - */ - public function setValue(mixed $value) + /** @internal */ + public function setValue(mixed $value): static { if ($value === null) { $value = ''; @@ -99,7 +96,7 @@ public function getControl(): Html /** * Bypasses label generation. */ - public function getLabel($caption = null): Html|string|null + public function getLabel(string|Stringable|null $caption = null): Html|string|null { return null; } diff --git a/src/Forms/Controls/MultiChoiceControl.php b/src/Forms/Controls/MultiChoiceControl.php index 40520111..cfa4846b 100644 --- a/src/Forms/Controls/MultiChoiceControl.php +++ b/src/Forms/Controls/MultiChoiceControl.php @@ -42,11 +42,8 @@ public function loadHttpData(): void } - /** - * @return static - * @internal - */ - public function setValue(mixed $values) + /** @internal */ + public function setValue(mixed $values): static { if (is_scalar($values) || $values === null) { $values = (array) $values; @@ -112,9 +109,8 @@ public function getRawValue(): array /** * Sets items from which to choose. When $useKeys is false, values are used as keys too. * @param mixed[] $items - * @return static */ - public function setItems(array $items, bool $useKeys = true) + public function setItems(array $items, bool $useKeys = true): static { $this->items = $useKeys ? $items : array_combine($items, $items); return $this; diff --git a/src/Forms/Controls/MultiSelectBox.php b/src/Forms/Controls/MultiSelectBox.php index 209c1f87..a7be790d 100644 --- a/src/Forms/Controls/MultiSelectBox.php +++ b/src/Forms/Controls/MultiSelectBox.php @@ -34,9 +34,8 @@ public function __construct(string|\Stringable|null $label = null, ?array $items /** * Sets options and option groups from which to choose. * @param mixed[] $items - * @return static */ - public function setItems(array $items, bool $useKeys = true) + public function setItems(array $items, bool $useKeys = true): static { if (!$useKeys) { $res = []; diff --git a/src/Forms/Controls/RadioList.php b/src/Forms/Controls/RadioList.php index 51c876ca..6b209756 100644 --- a/src/Forms/Controls/RadioList.php +++ b/src/Forms/Controls/RadioList.php @@ -71,7 +71,7 @@ public function getControl(): Html } - public function getLabel($caption = null): Html + public function getLabel(string|\Stringable|null $caption = null): Html { return parent::getLabel($caption)->for(null); } @@ -80,7 +80,7 @@ public function getLabel($caption = null): Html /** * Returns the HTML input element for a specific radio button item by key. */ - public function getControlPart($key = null): Html + public function getControlPart(int|string|null $key = null): Html { $this->getItem($key); return parent::getControl()->addAttributes([ @@ -95,7 +95,7 @@ public function getControlPart($key = null): Html /** * Returns the label element for the whole radio list, or the item label for a specific key. */ - public function getLabelPart($key = null): Html + public function getLabelPart(int|string|null $key = null): Html { $itemLabel = clone $this->itemLabel; return func_num_args() diff --git a/src/Forms/Controls/SelectBox.php b/src/Forms/Controls/SelectBox.php index 48f08ee3..92892837 100644 --- a/src/Forms/Controls/SelectBox.php +++ b/src/Forms/Controls/SelectBox.php @@ -66,9 +66,8 @@ public function getPrompt(): string|Stringable|false /** * Sets options and option groups from which to choose. * @param mixed[] $items - * @return static */ - public function setItems(array $items, bool $useKeys = true) + public function setItems(array $items, bool $useKeys = true): static { if (!$useKeys) { $res = []; diff --git a/src/Forms/Controls/SubmitButton.php b/src/Forms/Controls/SubmitButton.php index b5716c3e..b415617e 100644 --- a/src/Forms/Controls/SubmitButton.php +++ b/src/Forms/Controls/SubmitButton.php @@ -103,7 +103,7 @@ public function click(): void } - public function getControl($caption = null): Nette\Utils\Html + public function getControl(string|Stringable|null $caption = null): Nette\Utils\Html { $scope = []; foreach ((array) $this->validationScope as $control) { diff --git a/src/Forms/Controls/TextBase.php b/src/Forms/Controls/TextBase.php index c8628d82..8f350f19 100644 --- a/src/Forms/Controls/TextBase.php +++ b/src/Forms/Controls/TextBase.php @@ -24,11 +24,8 @@ abstract class TextBase extends BaseControl private bool $nullable = false; - /** - * @return static - * @internal - */ - public function setValue(mixed $value) + /** @internal */ + public function setValue(mixed $value): static { if ($value === null) { $value = ''; @@ -126,15 +123,13 @@ protected function getRenderedValue(): ?string } - /** - * @param (callable(never, never): bool)|string $validator - * @return static - */ + /** @param (callable(never, never): bool)|string $validator */ public function addRule( callable|string $validator, string|Stringable|null $errorMessage = null, mixed $arg = null, - ) { + ): static + { foreach ($this->getRules() as $rule) { if (!$rule->canExport() && !$rule->branch) { return parent::addRule($validator, $errorMessage, $arg); diff --git a/src/Forms/Controls/TextInput.php b/src/Forms/Controls/TextInput.php index 2a685859..c50a2f5d 100644 --- a/src/Forms/Controls/TextInput.php +++ b/src/Forms/Controls/TextInput.php @@ -58,15 +58,13 @@ public function getControl(): Nette\Utils\Html } - /** - * @param (callable(never, never): bool)|string $validator - * @return static - */ + /** @param (callable(never, never): bool)|string $validator */ public function addRule( callable|string $validator, string|Stringable|null $errorMessage = null, mixed $arg = null, - ) { + ): static + { foreach ($this->getRules() as $rule) { if (!$rule->canExport() && !$rule->branch) { return parent::addRule($validator, $errorMessage, $arg); diff --git a/src/Forms/Controls/UploadControl.php b/src/Forms/Controls/UploadControl.php index d2f206a6..eb464c71 100644 --- a/src/Forms/Controls/UploadControl.php +++ b/src/Forms/Controls/UploadControl.php @@ -64,11 +64,8 @@ public function getHtmlName(): string } - /** - * @return static - * @internal - */ - public function setValue(mixed $value) + /** @internal */ + public function setValue(mixed $value): static { return $this; } @@ -123,15 +120,13 @@ public function isOk(): bool } - /** - * @param (callable(never, never): bool)|string $validator - * @return static - */ + /** @param (callable(never, never): bool)|string $validator */ public function addRule( callable|string $validator, string|Stringable|null $errorMessage = null, mixed $arg = null, - ) { + ): static + { if ($validator === Form::Image) { $this->control->accept = implode(', ', Forms\Helpers::getSupportedImages()); diff --git a/src/Forms/Form.php b/src/Forms/Form.php index e4d81cd1..50cd9751 100644 --- a/src/Forms/Form.php +++ b/src/Forms/Form.php @@ -195,9 +195,7 @@ class Form extends Container implements Nette\HtmlStringable /** @internal used only by standalone form */ public Nette\Http\IRequest $httpRequest; - - /** @var bool */ - protected $crossOrigin = false; + protected bool $crossOrigin = false; private static ?Nette\Http\IRequest $defaultHttpRequest = null; private SubmitterControl|bool $submittedBy = false; From e80edbc61c4751ad5b638cbaea90aceb529dfbfc Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sun, 12 Sep 2021 22:25:45 +0200 Subject: [PATCH 11/47] Container: only Control/Container can be added to form (BC break) --- src/Forms/Container.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Forms/Container.php b/src/Forms/Container.php index 844dffe6..56d190d6 100644 --- a/src/Forms/Container.php +++ b/src/Forms/Container.php @@ -323,6 +323,10 @@ public function addComponent( ?string $insertBefore = null, ): static { + if (!$component instanceof Control && !$component instanceof self) { + throw new Nette\InvalidStateException("Component '$name' of type " . get_debug_type($component) . ' is not intended to be used in the form.'); + } + parent::addComponent($component, $name, $insertBefore); if ($component instanceof Control || $component instanceof self) { $this->currentGroup?->add($component); From 15fd6afc02f4fb7a3ad25a7d6a6cb87a88b413df Mon Sep 17 00:00:00 2001 From: David Grudl Date: Tue, 26 May 2026 17:07:37 +0200 Subject: [PATCH 12/47] Container::getControls() returns non-repeatable generator (BC break) --- src/Forms/Container.php | 12 +++++------- tests/Forms/Container.getControls().phpt | 15 ++++++--------- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/Forms/Container.php b/src/Forms/Container.php index 56d190d6..4fd1e3f1 100644 --- a/src/Forms/Container.php +++ b/src/Forms/Container.php @@ -337,18 +337,16 @@ public function addComponent( /** - * Iterates over all form controls. + * Iterates over all form controls including nested. Keys are control names and are not unique across containers. * @return iterable */ public function getControls(): iterable { - return Nette\Utils\Iterables::repeatable(function () { - foreach ($this->getComponentTree() as $component) { - if ($component instanceof Control) { - yield $component->getName() => $component; - } + foreach ($this->getComponentTree() as $component) { + if ($component instanceof Control) { + yield $component->getName() => $component; } - }); + } } diff --git a/tests/Forms/Container.getControls().phpt b/tests/Forms/Container.getControls().phpt index f766b627..0b93c7cb 100644 --- a/tests/Forms/Container.getControls().phpt +++ b/tests/Forms/Container.getControls().phpt @@ -23,12 +23,9 @@ foreach ($controls as $name => $value) { Assert::same(['name', 'age', 'name'], $names); Assert::same([$form['name'], $form['age'], $form['cont-name']], $values); -// again -$names = $values = []; -foreach ($controls as $name => $value) { - $names[] = $name; - $values[] = $value; -} - -Assert::same(['name', 'age', 'name'], $names); -Assert::same([$form['name'], $form['age'], $form['cont-name']], $values); +// generator cannot be traversed again +Assert::exception( + fn() => iterator_to_array($controls), + Throwable::class, + 'Cannot traverse an already closed generator', +); From a1df70653f5d9d9e2546f92ebdf0a43dd3fcb2b0 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Mon, 31 Mar 2025 03:14:00 +0200 Subject: [PATCH 13/47] BaseControl::$disabled is bool, added $disabledChoices --- src/Forms/Controls/BaseControl.php | 6 ++---- src/Forms/Controls/CheckboxList.php | 6 +++--- src/Forms/Controls/ChoiceControl.php | 12 ++++++------ src/Forms/Controls/MultiChoiceControl.php | 12 ++++++------ src/Forms/Controls/MultiSelectBox.php | 2 +- src/Forms/Controls/RadioList.php | 6 +++--- src/Forms/Controls/SelectBox.php | 2 +- 7 files changed, 22 insertions(+), 24 deletions(-) diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index 6df80f65..8ffd06bc 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -46,9 +46,7 @@ abstract class BaseControl extends Nette\ComponentModel\Component implements Con protected mixed $value = null; protected Html $control; protected Html $label; - - /** @var bool|bool[] */ - protected bool|array $disabled = false; + protected bool $disabled = false; /** @var array> */ private static array $extMethods = []; @@ -192,7 +190,7 @@ public function setDisabled(bool $state = true): static */ public function isDisabled(): bool { - return $this->disabled === true; + return $this->disabled; } diff --git a/src/Forms/Controls/CheckboxList.php b/src/Forms/Controls/CheckboxList.php index a08902a9..5d9295aa 100644 --- a/src/Forms/Controls/CheckboxList.php +++ b/src/Forms/Controls/CheckboxList.php @@ -10,7 +10,7 @@ use Nette; use Nette\Utils\Html; use Stringable; -use function func_num_args, is_array, is_string; +use function func_num_args, is_string; /** @@ -65,7 +65,7 @@ public function getControl(): Html ...$input->attrs, 'id' => null, 'checked?' => $this->value, - 'disabled:' => $this->disabled, + 'disabled:' => $this->disabled ?: $this->disabledChoices, 'required' => null, 'data-nette-rules:' => [array_key_first($items) => $input->attrs['data-nette-rules']], ], @@ -91,7 +91,7 @@ public function getControlPart(int|string|null $key = null): Html return parent::getControl()->addAttributes([ 'id' => $this->getHtmlId() . '-' . $key, 'checked' => in_array($key, (array) $this->value, true), - 'disabled' => is_array($this->disabled) ? isset($this->disabled[$key]) : $this->disabled, + 'disabled' => $this->disabled || isset($this->disabledChoices[$key]), 'required' => null, 'value' => $key, ]); diff --git a/src/Forms/Controls/ChoiceControl.php b/src/Forms/Controls/ChoiceControl.php index d140339d..2a503124 100644 --- a/src/Forms/Controls/ChoiceControl.php +++ b/src/Forms/Controls/ChoiceControl.php @@ -15,11 +15,12 @@ * Choice control that allows single item selection. * * @property mixed[] $items - * @property bool|array $disabled * @property-deprecated mixed $selectedItem */ abstract class ChoiceControl extends BaseControl { + /** @var bool[] */ + protected array $disabledChoices = []; private bool $checkDefaultValue = true; /** @var mixed[] */ @@ -76,7 +77,7 @@ public function getValue(): mixed { return $this->value !== null && array_key_exists($this->value, $this->items) - && !isset($this->disabled[$this->value]) + && !isset($this->disabledChoices[$this->value]) ? $this->value : null; } @@ -138,12 +139,11 @@ public function getSelectedItem(): mixed public function setDisabled(bool|array $state = true): static { if (!is_array($state)) { + $this->disabledChoices = []; return parent::setDisabled($state); } - - parent::setDisabled(false); - $this->disabled = array_fill_keys($state, value: true); - return $this; + $this->disabledChoices = array_fill_keys($state, value: true); + return parent::setDisabled(false); } diff --git a/src/Forms/Controls/MultiChoiceControl.php b/src/Forms/Controls/MultiChoiceControl.php index cfa4846b..0e7109fd 100644 --- a/src/Forms/Controls/MultiChoiceControl.php +++ b/src/Forms/Controls/MultiChoiceControl.php @@ -15,11 +15,12 @@ * Choice control that allows multiple items selection. * * @property mixed[] $items - * @property bool|array $disabled * @property-deprecated mixed[] $selectedItems */ abstract class MultiChoiceControl extends BaseControl { + /** @var bool[] */ + protected array $disabledChoices = []; private bool $checkDefaultValue = true; /** @var mixed[] */ @@ -135,7 +136,7 @@ public function getSelectedItems(): array { $res = []; foreach ($this->value as $key) { - if (isset($this->items[$key]) && !isset($this->disabled[$key])) { + if (isset($this->items[$key]) && !isset($this->disabledChoices[$key])) { $res[$key] = $this->items[$key]; } } @@ -150,12 +151,11 @@ public function getSelectedItems(): array public function setDisabled(bool|array $state = true): static { if (!is_array($state)) { + $this->disabledChoices = []; return parent::setDisabled($state); } - - parent::setDisabled(false); - $this->disabled = array_fill_keys($state, value: true); - return $this; + $this->disabledChoices = array_fill_keys($state, value: true); + return parent::setDisabled(false); } diff --git a/src/Forms/Controls/MultiSelectBox.php b/src/Forms/Controls/MultiSelectBox.php index a7be790d..1e8c2031 100644 --- a/src/Forms/Controls/MultiSelectBox.php +++ b/src/Forms/Controls/MultiSelectBox.php @@ -68,7 +68,7 @@ public function getControl(): Nette\Utils\Html return Nette\Forms\Helpers::createSelectBox( $items, [ - 'disabled:' => is_array($this->disabled) ? $this->disabled : null, + 'disabled:' => $this->disabledChoices, ] + $this->optionAttributes, $this->value, )->addAttributes(parent::getControl()->attrs)->multiple(true); diff --git a/src/Forms/Controls/RadioList.php b/src/Forms/Controls/RadioList.php index 6b209756..d0e35cdb 100644 --- a/src/Forms/Controls/RadioList.php +++ b/src/Forms/Controls/RadioList.php @@ -10,7 +10,7 @@ use Nette; use Nette\Utils\Html; use Stringable; -use function func_num_args, is_array; +use function func_num_args; /** @@ -61,7 +61,7 @@ public function getControl(): Html ...$input->attrs, 'id:' => $ids, 'checked?' => $this->value, - 'disabled:' => $this->disabled, + 'disabled:' => $this->disabled ?: $this->disabledChoices, 'data-nette-rules:' => [array_key_first($items) => $input->attrs['data-nette-rules']], ], ['for:' => $ids] + $this->itemLabel->attrs, @@ -86,7 +86,7 @@ public function getControlPart(int|string|null $key = null): Html return parent::getControl()->addAttributes([ 'id' => $this->getHtmlId() . '-' . $key, 'checked' => in_array($key, (array) $this->value, true), - 'disabled' => is_array($this->disabled) ? isset($this->disabled[$key]) : $this->disabled, + 'disabled' => $this->disabled || isset($this->disabledChoices[$key]), 'value' => $key, ]); } diff --git a/src/Forms/Controls/SelectBox.php b/src/Forms/Controls/SelectBox.php index 92892837..d01825c7 100644 --- a/src/Forms/Controls/SelectBox.php +++ b/src/Forms/Controls/SelectBox.php @@ -98,7 +98,7 @@ public function getControl(): Nette\Utils\Html } $attrs = $this->optionAttributes; - $attrs['disabled:'] = is_array($this->disabled) ? $this->disabled : []; + $attrs['disabled:'] = $this->disabledChoices; $selected = $this->value; if ($this->prompt !== false) { From 0efcd08e9fcd80d04c61e19fca1b53ec888f743a Mon Sep 17 00:00:00 2001 From: David Grudl Date: Wed, 24 Jun 2026 18:30:12 +0200 Subject: [PATCH 14/47] Latte: {formContext}, {formContainer}, {formPrint} & {formClassPrint) are deprecated --- .../FormsLatte/Nodes/FormContainerNode.php | 1 + src/Bridges/FormsLatte/Nodes/FormNode.php | 4 +++- src/Bridges/FormsLatte/Nodes/FormPrintNode.php | 5 +++++ tests/Forms.Latte/expected/forms.html | 6 ------ tests/Forms.Latte/expected/forms.php | 17 ----------------- tests/Forms.Latte/forms.error.phpt | 4 ++-- tests/Forms.Latte/forms.formContainer.phpt | 4 ++-- tests/Forms.Latte/forms.scope.phpt | 6 +++--- tests/Forms.Latte/templates/forms.latte | 6 ------ 9 files changed, 16 insertions(+), 37 deletions(-) diff --git a/src/Bridges/FormsLatte/Nodes/FormContainerNode.php b/src/Bridges/FormsLatte/Nodes/FormContainerNode.php index 7fb29d7e..99b3edb6 100644 --- a/src/Bridges/FormsLatte/Nodes/FormContainerNode.php +++ b/src/Bridges/FormsLatte/Nodes/FormContainerNode.php @@ -25,6 +25,7 @@ class FormContainerNode extends StatementNode /** @return \Generator, array{AreaNode, ?Tag}, static> */ public static function create(Tag $tag): \Generator { + trigger_error('Tag {formContainer} is deprecated, use {form scope}', E_USER_DEPRECATED); $tag->outputMode = $tag::OutputRemoveIndentation; $tag->expectArguments(); diff --git a/src/Bridges/FormsLatte/Nodes/FormNode.php b/src/Bridges/FormsLatte/Nodes/FormNode.php index fe447176..6bbc278e 100644 --- a/src/Bridges/FormsLatte/Nodes/FormNode.php +++ b/src/Bridges/FormsLatte/Nodes/FormNode.php @@ -17,7 +17,6 @@ /** * {form [scope|detached] name [, attributes]} ... {/form} - * {formContext name} ... {/formContext} * Renders form tags and initializes form context. */ class FormNode extends StatementNode @@ -42,6 +41,9 @@ public static function create(Tag $tag): \Generator $tag->outputMode = $tag::OutputKeepIndentation; $tag->expectArguments(); $node = $tag->node = new static; + if ($tag->name === 'formContext') { + trigger_error('Tag {formContext} is deprecated, use {form scope}', E_USER_DEPRECATED); + } $node->mode = match (true) { $tag->name === 'formContext' => self::ModeLegacyScope, in_array( diff --git a/src/Bridges/FormsLatte/Nodes/FormPrintNode.php b/src/Bridges/FormsLatte/Nodes/FormPrintNode.php index d0e95590..11f46252 100644 --- a/src/Bridges/FormsLatte/Nodes/FormPrintNode.php +++ b/src/Bridges/FormsLatte/Nodes/FormPrintNode.php @@ -25,6 +25,11 @@ class FormPrintNode extends StatementNode public static function create(Tag $tag): static { + if ($tag->name === 'formPrint') { + trigger_error('Tag {formPrint} is deprecated, use Nette\Forms\Blueprint::latte($form)', E_USER_DEPRECATED); + } else { + trigger_error('Tag {formClassPrint} is deprecated, use Nette\Forms\Blueprint::dataClass($form)', E_USER_DEPRECATED); + } $node = new static; $node->name = $tag->parser->isEnd() ? null diff --git a/tests/Forms.Latte/expected/forms.html b/tests/Forms.Latte/expected/forms.html index f7985bb9..948fc13e 100644 --- a/tests/Forms.Latte/expected/forms.html +++ b/tests/Forms.Latte/expected/forms.html @@ -106,9 +106,3 @@ - - - - - - \ No newline at end of file diff --git a/tests/Forms.Latte/expected/forms.php b/tests/Forms.Latte/expected/forms.php index 751dca51..0092bf3c 100644 --- a/tests/Forms.Latte/expected/forms.php +++ b/tests/Forms.Latte/expected/forms.php @@ -240,21 +240,4 @@ '; echo $this->global->forms->renderFormEnd() /* pos %d%:1 */; $form = $this->global->forms->end() ?? $form; - - echo ' - - -'; - $this->global->forms->begin($form = $this->global->uiControl['myForm']) /* pos %d%:1 */; - echo ' -global->forms->get('sex')->getLabelPart())->attributes() /* pos %d%:8 */; - echo '>'; - echo $ʟ_elem->getHtml() /* pos %d%:8 */; - echo ' -global->forms->get('username')->getControlPart())->attributes() /* pos %d%:8 */; - echo '> -'; - $form = $this->global->forms->end() ?? $form; %A% diff --git a/tests/Forms.Latte/forms.error.phpt b/tests/Forms.Latte/forms.error.phpt index cc1d8607..150671b5 100644 --- a/tests/Forms.Latte/forms.error.phpt +++ b/tests/Forms.Latte/forms.error.phpt @@ -36,9 +36,9 @@ Assert::exception( ); Assert::exception( - fn() => $latte->compile('{formContainer /}'), + fn() => $latte->compile('{form scope /}'), Latte\CompileException::class, - 'Missing arguments in {formContainer} (on line 1 at column 7)', + 'Unexpected end (on line 1 at column 19)', ); diff --git a/tests/Forms.Latte/forms.formContainer.phpt b/tests/Forms.Latte/forms.formContainer.phpt index 7b703ef2..549449f9 100644 --- a/tests/Forms.Latte/forms.formContainer.phpt +++ b/tests/Forms.Latte/forms.formContainer.phpt @@ -37,9 +37,9 @@ $latte->addProvider('uiControl', ['myForm' => $form]); Assert::matchFile( __DIR__ . '/expected/forms.formContainer.php', - $latte->compile(__DIR__ . '/templates/forms.formContainer.latte'), + @$latte->compile(__DIR__ . '/templates/forms.formContainer.latte'), // @ {formContainer} is deprecated ); Assert::matchFile( __DIR__ . '/expected/forms.formContainer.html', - $latte->renderToString(__DIR__ . '/templates/forms.formContainer.latte'), + @$latte->renderToString(__DIR__ . '/templates/forms.formContainer.latte'), // @ {formContainer} is deprecated ); diff --git a/tests/Forms.Latte/forms.scope.phpt b/tests/Forms.Latte/forms.scope.phpt index 64218d2b..dc230a65 100644 --- a/tests/Forms.Latte/forms.scope.phpt +++ b/tests/Forms.Latte/forms.scope.phpt @@ -18,12 +18,12 @@ $latte->addProvider('uiControl', ['myForm' => $form]); Assert::matchFile( __DIR__ . '/expected/forms.scope.php', - $latte->compile(__DIR__ . '/templates/forms.scope.latte'), + @$latte->compile(__DIR__ . '/templates/forms.scope.latte'), // @ {formContext} and {formContainer} are deprecated ); Assert::matchFile( __DIR__ . '/expected/forms.scope.html', - $latte->renderToString(__DIR__ . '/templates/forms.scope.latte'), + @$latte->renderToString(__DIR__ . '/templates/forms.scope.latte'), // @ {formContext} and {formContainer} are deprecated ); @@ -46,7 +46,7 @@ test('arguments are rejected in {formContext}', function () { $latte->addExtension(new FormsExtension); Assert::exception( - fn() => $latte->compile('{formContext myForm, class: x}{/formContext}'), + fn() => @$latte->compile('{formContext myForm, class: x}{/formContext}'), // @ {formContext} is deprecated Latte\CompileException::class, 'Arguments are not allowed in {formContext}%a%', ); diff --git a/tests/Forms.Latte/templates/forms.latte b/tests/Forms.Latte/templates/forms.latte index ad20bf6f..fd3f4547 100644 --- a/tests/Forms.Latte/templates/forms.latte +++ b/tests/Forms.Latte/templates/forms.latte @@ -75,9 +75,3 @@ -{/formContext myForm} From dd0aeb88e00683de1a4e0fe674f456e1aac1b9c8 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Tue, 6 Aug 2024 00:27:12 +0200 Subject: [PATCH 15/47] netteForms: removed distribution files (BC break) --- src/assets/netteForms.js | 580 ----------------------------------- src/assets/netteForms.min.js | 7 - 2 files changed, 587 deletions(-) delete mode 100644 src/assets/netteForms.js delete mode 100644 src/assets/netteForms.min.js diff --git a/src/assets/netteForms.js b/src/assets/netteForms.js deleted file mode 100644 index dd39aee1..00000000 --- a/src/assets/netteForms.js +++ /dev/null @@ -1,580 +0,0 @@ -/*! - * NetteForms - simple form validation. - * - * This file is part of the Nette Framework (https://nette.org) - * Copyright (c) 2004 David Grudl (https://davidgrudl.com) - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Nette?.noInit ? (global.Nette = factory()) : (global.Nette = factory()).initOnLoad()); -})(this, (function () { 'use strict'; - - class Validators { - filled(elem, arg, val) { - return val !== '' && val !== false && val !== null - && (!Array.isArray(val) || val.length > 0) - && (!(val instanceof FileList) || val.length > 0); - } - blank(elem, arg, val) { - return !this.filled(elem, arg, val); - } - valid(elem, arg) { - return arg.validateControl(elem, undefined, true); - } - equal(elem, arg, val) { - if (arg === undefined) { - return null; - } - let toString = (val) => { - if (typeof val === 'number' || typeof val === 'string') { - return '' + val; - } - else { - return val === true ? '1' : ''; - } - }; - let vals = Array.isArray(val) ? val : [val]; - let args = Array.isArray(arg) ? arg : [arg]; - loop: for (let a of vals) { - for (let b of args) { - if (toString(a) === toString(b)) { - continue loop; - } - } - return false; - } - return vals.length > 0; - } - notEqual(elem, arg, val) { - return arg === undefined ? null : !this.equal(elem, arg, val); - } - minLength(elem, arg, val) { - return Validators.lengthOf(val) >= arg; - } - maxLength(elem, arg, val) { - return Validators.lengthOf(val) <= arg; - } - length(elem, arg, val) { - arg = Array.isArray(arg) ? arg : [arg, arg]; - let len = Validators.lengthOf(val); - return ((arg[0] === null || len >= arg[0]) - && (arg[1] === null || len <= arg[1])); - } - // strings are measured in code points to match the server-side Strings::length() - static lengthOf(val) { - val = typeof val === 'number' ? val.toString() : val; - return typeof val === 'string' ? [...val].length : val.length; - } - email(elem, arg, val) { - return (/^("([ !#-[\]-~]|\\[ -~])+"|[-a-z0-9!#$%&'*+/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+/=?^_`{|}~]+)*)@([0-9a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,61}[0-9a-z\u00C0-\u02FF\u0370-\u1EFF])?\.)+[a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,17}[a-z\u00C0-\u02FF\u0370-\u1EFF])?$/i).test(val); - } - url(elem, arg, val, newValue) { - if (!(/^[a-z\d+.-]+:/).test(val)) { - val = 'https://' + val; - } - if ((/^https?:\/\/((([-_0-9a-z\u00C0-\u02FF\u0370-\u1EFF]+\.)*[0-9a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,61}[0-9a-z\u00C0-\u02FF\u0370-\u1EFF])?\.)?[a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,17}[a-z\u00C0-\u02FF\u0370-\u1EFF])?|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[0-9a-f:]{3,39}\])(:\d{1,5})?(\/\S*)?(\?\S*)?(#\S*)?$/i).test(val)) { - newValue.value = val; - return true; - } - return false; - } - regexp(elem, arg, val) { - let parts = typeof arg === 'string' ? arg.match(/^\/(.*)\/([imu]*)$/) : false; - try { - return parts && (new RegExp(parts[1], parts[2].replace('u', ''))).test(val); - } - catch { - return null; - } - } - pattern(elem, arg, val, newValue, caseInsensitive) { - if (typeof arg !== 'string') { - return null; - } - try { - let regExp; - try { - regExp = new RegExp('^(?:' + arg + ')$', caseInsensitive ? 'ui' : 'u'); - } - catch { - regExp = new RegExp('^(?:' + arg + ')$', caseInsensitive ? 'i' : ''); - } - return val instanceof FileList - ? Array.from(val).every((file) => regExp.test(file.name)) - : regExp.test(val); - } - catch { - return null; - } - } - patternCaseInsensitive(elem, arg, val) { - return this.pattern(elem, arg, val, null, true); - } - numeric(elem, arg, val) { - return (/^[0-9]+$/).test(val); - } - integer(elem, arg, val, newValue) { - if ((/^-?[0-9]+$/).test(val)) { - newValue.value = parseFloat(val); - return true; - } - return false; - } - float(elem, arg, val, newValue) { - val = val.replace(/ +/g, '').replace(/,/g, '.'); - if ((/^-?[0-9]*\.?[0-9]+$/).test(val)) { - newValue.value = parseFloat(val); - return true; - } - return false; - } - min(elem, arg, val) { - [val, arg] = Validators.toComparable(val, arg); - return val >= arg; - } - max(elem, arg, val) { - [val, arg] = Validators.toComparable(val, arg); - return val <= arg; - } - // if either side is numeric (a bound referencing another control arrives as a string), - // both compare as numbers and a partially numeric value fails; otherwise as strings (dates, times) - static toComparable(a, b) { - let isNumeric = (v) => typeof v === 'number' - || (/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/).test(v); - let toNumber = (v) => isNumeric(v) ? parseFloat(v) : NaN; - return isNumeric(a) || isNumeric(b) - ? [toNumber(a), toNumber(b)] - : [String(a), String(b)]; - } - range(elem, arg, val) { - if (!Array.isArray(arg)) { - return null; - } - else if (elem.type === 'time' && arg[0] > arg[1]) { - return val >= arg[0] || val <= arg[1]; - } - return (arg[0] === null || this.min(elem, arg[0], val)) - && (arg[1] === null || this.max(elem, arg[1], val)); - } - submitted(elem) { - return elem.form['nette-submittedBy'] === elem; - } - fileSize(elem, arg, val) { - return Array.from(val).every((file) => file.size <= arg); - } - mimeType(elem, args, val) { - let parts = []; - args = Array.isArray(args) ? args : [args]; - args.forEach((arg) => parts.push('^' + arg.replace(/([^\w])/g, '\\$1').replace('\\*', '.*') + '$')); - let re = new RegExp(parts.join('|')); - return Array.from(val).every((file) => !file.type || re.test(file.type)); - } - image(elem, arg, val) { - return this.mimeType(elem, arg ?? ['image/gif', 'image/png', 'image/jpeg', 'image/webp', 'image/avif'], val); - } - static(elem, arg) { - return arg; - } - } - - class FormValidator { - formErrors = []; - validators = new Validators; - #preventFiltering = {}; - #formToggles = {}; - #toggleListeners = new WeakMap; - #getFormElement(form, name) { - let res = form.elements.namedItem(name); - return (res instanceof RadioNodeList ? res[0] : res); - } - #expandRadioElement(elem) { - let res = elem.form.elements.namedItem(elem.name); - return (res instanceof RadioNodeList ? Array.from(res) : [res]); - } - /** - * Function to execute when the DOM is fully loaded. - */ - #onDocumentReady(callback) { - if (document.readyState !== 'loading') { - callback.call(this); - } - else { - document.addEventListener('DOMContentLoaded', callback); - } - } - /** - * Returns the value of form element. - */ - getValue(elem) { - if (elem instanceof HTMLInputElement) { - if (elem.type === 'radio') { - return this.#expandRadioElement(elem) - .find((input) => input.checked) - ?.value ?? null; - } - else if (elem.type === 'file') { - return elem.files; - } - else if (elem.type === 'checkbox') { - return elem.name.endsWith('[]') // checkbox list - ? this.#expandRadioElement(elem) - .filter((input) => input.checked) - .map((input) => input.value) - : elem.checked; - } - else { - return elem.value.trim(); - } - } - else if (elem instanceof HTMLSelectElement) { - return elem.multiple - ? Array.from(elem.selectedOptions, (option) => option.value) - : elem.selectedOptions[0]?.value ?? null; - } - else if (elem instanceof HTMLTextAreaElement) { - return elem.value; - } - else if (elem instanceof RadioNodeList) { - return this.getValue(elem[0]); - } - else { - return null; - } - } - /** - * Returns the effective value of form element. - */ - getEffectiveValue(elem, filter = false) { - let val = this.getValue(elem); - if (val === elem.getAttribute('data-nette-empty-value')) { - val = ''; - } - if (filter && this.#preventFiltering[elem.name] === undefined) { - this.#preventFiltering[elem.name] = true; - let ref = { value: val }; - this.validateControl(elem, undefined, true, ref); - val = ref.value; - delete this.#preventFiltering[elem.name]; - } - return val; - } - /** - * Validates form element against given rules. - */ - validateControl(elem, rules, onlyCheck = false, value, emptyOptional) { - rules ??= JSON.parse(elem.getAttribute('data-nette-rules') ?? '[]'); - value ??= { value: this.getEffectiveValue(elem) }; - emptyOptional ??= !this.validateRule(elem, ':filled', null, value); - for (let rule of rules) { - let op = rule.op.match(/(~)?([^?]+)/), curElem = rule.control ? this.#getFormElement(elem.form, rule.control) : elem; - rule.neg = !!op[1]; - rule.op = op[2]; - rule.condition = !!rule.rules; - if (!curElem) { - continue; - } - else if (emptyOptional && !rule.condition && rule.op !== ':filled') { - continue; - } - let success = this.validateRule(curElem, rule.op, rule.arg, elem === curElem ? value : undefined); - if (success === null) { - continue; - } - else if (rule.neg) { - success = !success; - } - if (rule.condition && success) { - if (!this.validateControl(elem, rule.rules, onlyCheck, value, rule.op === ':blank' ? false : emptyOptional)) { - return false; - } - } - else if (!rule.condition && !success) { - if (this.isDisabled(curElem)) { - continue; - } - if (!onlyCheck) { - let arr = Array.isArray(rule.arg) ? rule.arg : [rule.arg], toDisplay = (val) => val instanceof FileList - ? Array.from(val, (file) => file.name).join(', ') - : val, message = rule.msg.replace(/%(value|\d+)/g, (foo, m) => toDisplay(this.getValue(m === 'value' ? curElem : elem.form.elements.namedItem(arr[m].control)))); - this.addError(curElem, message); - } - return false; - } - } - return true; - } - /** - * Validates whole form. - */ - validateForm(sender, onlyCheck = false) { - let form = sender.form ?? sender, scope; - this.formErrors = []; - if (sender.getAttribute('formnovalidate') !== null) { - let scopeArr = JSON.parse(sender.getAttribute('data-nette-validation-scope') ?? '[]'); - if (scopeArr.length) { - scope = new RegExp('^(' + scopeArr.join('-|') + '-)'); - } - else { - this.showFormErrors(form, []); - return true; - } - } - let inScope = (elem) => !scope || scope.test(elem.name.replace(/]\[|\[|]|$/g, '-')); - for (let elem of form.elements) { - if (elem.willValidate && elem.validity.badInput && inScope(elem)) { - if (!onlyCheck) { - elem.reportValidity(); - } - return false; - } - } - for (let elem of form.elements) { - if (elem.getAttribute('data-nette-rules') - && inScope(elem) - && !this.isDisabled(elem) - && !this.validateControl(elem, undefined, onlyCheck) - && !this.formErrors.length) { - return false; - } - } - let success = !this.formErrors.length; - this.showFormErrors(form, this.formErrors); - return success; - } - /** - * Check if input is disabled. - */ - isDisabled(elem) { - if (elem.type === 'radio') { - return this.#expandRadioElement(elem) - .every((input) => input.disabled); - } - return elem.disabled; - } - /** - * Adds error message to the queue. - */ - addError(elem, message) { - this.formErrors.push({ - element: elem, - message: message, - }); - } - /** - * Display error messages. - */ - showFormErrors(form, errors) { - let messages = [], focusElem; - for (let error of errors) { - if (messages.indexOf(error.message) < 0) { - messages.push(error.message); - focusElem ??= error.element; - } - } - if (messages.length) { - this.showModal(messages.join('\n'), () => { - focusElem?.focus(); - }); - } - } - /** - * Display modal window. - */ - showModal(message, onclose) { - let dialog = document.createElement('dialog'); - if (!dialog.showModal) { - alert(message); - onclose(); - return; - } - let style = document.createElement('style'); - style.innerText = '.netteFormsModal { text-align: center; margin: auto; border: 2px solid black; padding: 1rem } .netteFormsModal button { padding: .1em 2em }'; - let button = document.createElement('button'); - button.innerText = 'OK'; - button.onclick = () => { - dialog.remove(); - onclose(); - }; - dialog.setAttribute('class', 'netteFormsModal'); - dialog.innerText = message + '\n\n'; - dialog.append(style, button); - document.body.append(dialog); - dialog.showModal(); - } - /** - * Validates single rule. - */ - validateRule(elem, op, arg, value) { - if (elem.validity.badInput) { - return op === ':filled'; - } - value ??= { value: this.getEffectiveValue(elem, true) }; - let method = op.charAt(0) === ':' ? op.substring(1) : op; - method = method.replace('::', '_').replaceAll('\\', ''); - let args = Array.isArray(arg) ? arg : [arg]; - if (args.some((arg) => arg?.control && !this.#getFormElement(elem.form, arg.control))) { - return null; // the referenced control is not rendered - } - args = args.map((arg) => { - if (arg?.control) { - let control = this.#getFormElement(elem.form, arg.control); - return control === elem ? value.value : this.getEffectiveValue(control, true); - } - return arg; - }); - if (method === 'valid') { - args[0] = this; // todo - } - return this.validators[method] - ? this.validators[method](elem, Array.isArray(arg) ? args : args[0], value.value, value) - : null; - } - /** - * Process all toggles in form. - */ - toggleForm(form, event) { - this.#formToggles = {}; - for (let elem of Array.from(form.elements)) { - if (elem.getAttribute('data-nette-rules')) { - this.toggleControl(elem, undefined, null, !event); - } - } - for (let i in this.#formToggles) { - this.toggle(i, this.#formToggles[i].state, this.#formToggles[i].elem, event); - } - } - /** - * Process toggles on form element. - */ - toggleControl(elem, rules, success = null, firsttime = false, value, emptyOptional) { - rules ??= JSON.parse(elem.getAttribute('data-nette-rules') ?? '[]'); - value ??= { value: this.getEffectiveValue(elem) }; - emptyOptional ??= !this.validateRule(elem, ':filled', null, value); - let has = false, curSuccess; - for (let rule of rules) { - let op = rule.op.match(/(~)?([^?]+)/), curElem = rule.control ? this.#getFormElement(elem.form, rule.control) : elem; - rule.neg = !!op[1]; - rule.op = op[2]; - rule.condition = !!rule.rules; - if (!curElem) { - continue; - } - else if (emptyOptional && !rule.condition && rule.op !== ':filled') { - continue; - } - curSuccess = success; - if (success !== false) { - curSuccess = this.validateRule(curElem, rule.op, rule.arg, elem === curElem ? value : undefined); - if (curSuccess === null) { - continue; - } - else if (rule.neg) { - curSuccess = !curSuccess; - } - if (!rule.condition) { - success = curSuccess; - } - } - if ((rule.condition && this.toggleControl(elem, rule.rules, curSuccess, firsttime, value, rule.op === ':blank' ? false : emptyOptional)) || rule.toggle) { - has = true; - if (firsttime) { - this.#expandRadioElement(curElem) - .filter((el) => !this.#toggleListeners.has(el)) - .forEach((el) => { - el.addEventListener('change', (e) => this.toggleForm(elem.form, e)); - this.#toggleListeners.set(el, null); - }); - } - for (let id in rule.toggle ?? {}) { - this.#formToggles[id] ??= { elem: elem, state: false }; - this.#formToggles[id].state ||= rule.toggle[id] ? !!curSuccess : !curSuccess; - } - } - } - return has; - } - /** - * Displays or hides HTML element. - */ - toggle(selector, visible, srcElement, event) { - if (/^\w[\w.:-]*$/.test(selector)) { // id - selector = '#' + selector; - } - Array.from(document.querySelectorAll(selector)) - .forEach((elem) => elem.hidden = !visible); - } - /** - * Compact checkboxes - */ - compactCheckboxes(form, formData) { - let values = {}; - for (let elem of form.elements) { - if (elem instanceof HTMLInputElement && elem.type === 'checkbox' && elem.name.endsWith('[]') && elem.checked && !elem.disabled) { - formData.delete(elem.name); - values[elem.name] ??= []; - values[elem.name].push(elem.value); - } - } - for (let name in values) { - formData.set(name.substring(0, name.length - 2), values[name].join(',')); - } - } - /** - * Setup handlers. - */ - initForm(form) { - if (form.method === 'get' && form.hasAttribute('data-nette-compact')) { - form.addEventListener('formdata', (e) => this.compactCheckboxes(form, e.formData)); - } - if (!Array.from(form.elements).some((elem) => elem.getAttribute('data-nette-rules'))) { - return; - } - this.toggleForm(form); - if (form.noValidate) { - return; - } - form.noValidate = true; - form.addEventListener('submit', (e) => { - if (!this.validateForm((e.submitter || form))) { - e.stopImmediatePropagation(); - e.preventDefault(); - } - }); - form.addEventListener('reset', () => { - setTimeout(() => this.toggleForm(form)); - }); - } - initOnLoad() { - this.#onDocumentReady(() => { - Array.from(document.forms) - .forEach((form) => this.initForm(form)); - }); - } - } - - let webalizeTable = { \u00e1: 'a', \u00e4: 'a', \u010d: 'c', \u010f: 'd', \u00e9: 'e', \u011b: 'e', \u00ed: 'i', \u013e: 'l', \u0148: 'n', \u00f3: 'o', \u00f4: 'o', \u0159: 'r', \u0161: 's', \u0165: 't', \u00fa: 'u', \u016f: 'u', \u00fd: 'y', \u017e: 'z' }; - /** - * Converts string to web safe characters [a-z0-9-] text. - * @param {string} s - * @return {string} - */ - function webalize(s) { - s = s.toLowerCase(); - let res = ''; - for (let i = 0; i < s.length; i++) { - let ch = webalizeTable[s.charAt(i)]; - res += ch ? ch : s.charAt(i); - } - return res.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); - } - - var version = "3.5.4"; - - let nette = new FormValidator; - nette.version = version; - nette.webalize = webalize; - - return nette; - -})); diff --git a/src/assets/netteForms.min.js b/src/assets/netteForms.min.js deleted file mode 100644 index 52d941e2..00000000 --- a/src/assets/netteForms.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * NetteForms - simple form validation. - * - * This file is part of the Nette Framework (https://nette.org) - * Copyright (c) 2004 David Grudl (https://davidgrudl.com) - */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self,e.Nette?.noInit?e.Nette=t():(e.Nette=t()).initOnLoad())}(this,function(){"use strict";class e{filled(e,t,r){return""!==r&&!1!==r&&null!==r&&(!Array.isArray(r)||r.length>0)&&(!(r instanceof FileList)||r.length>0)}blank(e,t,r){return!this.filled(e,t,r)}valid(e,t){return t.validateControl(e,void 0,!0)}equal(e,t,r){if(void 0===t)return null;let n=e=>"number"==typeof e||"string"==typeof e?""+e:!0===e?"1":"",l=Array.isArray(r)?r:[r],i=Array.isArray(t)?t:[t];e:for(let e of l){for(let t of i)if(n(e)===n(t))continue e;return!1}return l.length>0}notEqual(e,t,r){return void 0===t?null:!this.equal(e,t,r)}minLength(t,r,n){return e.lengthOf(n)>=r}maxLength(t,r,n){return e.lengthOf(n)<=r}length(t,r,n){r=Array.isArray(r)?r:[r,r];let l=e.lengthOf(n);return(null===r[0]||l>=r[0])&&(null===r[1]||l<=r[1])}static lengthOf(e){return"string"==typeof(e="number"==typeof e?e.toString():e)?[...e].length:e.length}email(e,t,r){return/^("([ !#-[\]-~]|\\[ -~])+"|[-a-z0-9!#$%&'*+/=?^_`{|}~]+(\.[-a-z0-9!#$%&'*+/=?^_`{|}~]+)*)@([0-9a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,61}[0-9a-z\u00C0-\u02FF\u0370-\u1EFF])?\.)+[a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,17}[a-z\u00C0-\u02FF\u0370-\u1EFF])?$/i.test(r)}url(e,t,r,n){return/^[a-z\d+.-]+:/.test(r)||(r="https://"+r),!!/^https?:\/\/((([-_0-9a-z\u00C0-\u02FF\u0370-\u1EFF]+\.)*[0-9a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,61}[0-9a-z\u00C0-\u02FF\u0370-\u1EFF])?\.)?[a-z\u00C0-\u02FF\u0370-\u1EFF]([-0-9a-z\u00C0-\u02FF\u0370-\u1EFF]{0,17}[a-z\u00C0-\u02FF\u0370-\u1EFF])?|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[0-9a-f:]{3,39}\])(:\d{1,5})?(\/\S*)?(\?\S*)?(#\S*)?$/i.test(r)&&(n.value=r,!0)}regexp(e,t,r){let n="string"==typeof t&&t.match(/^\/(.*)\/([imu]*)$/);try{return n&&new RegExp(n[1],n[2].replace("u","")).test(r)}catch{return null}}pattern(e,t,r,n,l){if("string"!=typeof t)return null;try{let e;try{e=new RegExp("^(?:"+t+")$",l?"ui":"u")}catch{e=new RegExp("^(?:"+t+")$",l?"i":"")}return r instanceof FileList?Array.from(r).every(t=>e.test(t.name)):e.test(r)}catch{return null}}patternCaseInsensitive(e,t,r){return this.pattern(e,t,r,null,!0)}numeric(e,t,r){return/^[0-9]+$/.test(r)}integer(e,t,r,n){return!!/^-?[0-9]+$/.test(r)&&(n.value=parseFloat(r),!0)}float(e,t,r,n){return r=r.replace(/ +/g,"").replace(/,/g,"."),!!/^-?[0-9]*\.?[0-9]+$/.test(r)&&(n.value=parseFloat(r),!0)}min(t,r,n){return[n,r]=e.toComparable(n,r),n>=r}max(t,r,n){return[n,r]=e.toComparable(n,r),n<=r}static toComparable(e,t){let r=e=>"number"==typeof e||/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/.test(e),n=e=>r(e)?parseFloat(e):NaN;return r(e)||r(t)?[n(e),n(t)]:[String(e),String(t)]}range(e,t,r){return Array.isArray(t)?"time"===e.type&&t[0]>t[1]?r>=t[0]||r<=t[1]:(null===t[0]||this.min(e,t[0],r))&&(null===t[1]||this.max(e,t[1],r)):null}submitted(e){return e.form["nette-submittedBy"]===e}fileSize(e,t,r){return Array.from(r).every(e=>e.size<=t)}mimeType(e,t,r){let n=[];(t=Array.isArray(t)?t:[t]).forEach(e=>n.push("^"+e.replace(/([^\w])/g,"\\$1").replace("\\*",".*")+"$"));let l=new RegExp(n.join("|"));return Array.from(r).every(e=>!e.type||l.test(e.type))}image(e,t,r){return this.mimeType(e,t??["image/gif","image/png","image/jpeg","image/webp","image/avif"],r)}static(e,t){return t}}let t={"á":"a","ä":"a","č":"c","ď":"d","é":"e","ě":"e","í":"i","ľ":"l","ň":"n","ó":"o","ô":"o","ř":"r","š":"s","ť":"t","ú":"u","ů":"u","ý":"y","ž":"z"};let r=new class{formErrors=[];validators=new e;#e={};#t={};#r=new WeakMap;#n(e,t){let r=e.elements.namedItem(t);return r instanceof RadioNodeList?r[0]:r}#l(e){let t=e.form.elements.namedItem(e.name);return t instanceof RadioNodeList?Array.from(t):[t]}#i(e){"loading"!==document.readyState?e.call(this):document.addEventListener("DOMContentLoaded",e)}getValue(e){return e instanceof HTMLInputElement?"radio"===e.type?this.#l(e).find(e=>e.checked)?.value??null:"file"===e.type?e.files:"checkbox"===e.type?e.name.endsWith("[]")?this.#l(e).filter(e=>e.checked).map(e=>e.value):e.checked:e.value.trim():e instanceof HTMLSelectElement?e.multiple?Array.from(e.selectedOptions,e=>e.value):e.selectedOptions[0]?.value??null:e instanceof HTMLTextAreaElement?e.value:e instanceof RadioNodeList?this.getValue(e[0]):null}getEffectiveValue(e,t=!1){let r=this.getValue(e);if(r===e.getAttribute("data-nette-empty-value")&&(r=""),t&&void 0===this.#e[e.name]){this.#e[e.name]=!0;let t={value:r};this.validateControl(e,void 0,!0,t),r=t.value,delete this.#e[e.name]}return r}validateControl(e,t,r=!1,n,l){t??=JSON.parse(e.getAttribute("data-nette-rules")??"[]"),n??={value:this.getEffectiveValue(e)},l??=!this.validateRule(e,":filled",null,n);for(let i of t){let t=i.op.match(/(~)?([^?]+)/),a=i.control?this.#n(e.form,i.control):e;if(i.neg=!!t[1],i.op=t[2],i.condition=!!i.rules,!a)continue;if(l&&!i.condition&&":filled"!==i.op)continue;let o=this.validateRule(a,i.op,i.arg,e===a?n:void 0);if(null!==o)if(i.neg&&(o=!o),i.condition&&o){if(!this.validateControl(e,i.rules,r,n,":blank"!==i.op&&l))return!1}else if(!i.condition&&!o){if(this.isDisabled(a))continue;if(!r){let t=Array.isArray(i.arg)?i.arg:[i.arg],r=e=>e instanceof FileList?Array.from(e,e=>e.name).join(", "):e,n=i.msg.replace(/%(value|\d+)/g,(n,l)=>r(this.getValue("value"===l?a:e.form.elements.namedItem(t[l].control))));this.addError(a,n)}return!1}}return!0}validateForm(e,t=!1){let r,n=e.form??e;if(this.formErrors=[],null!==e.getAttribute("formnovalidate")){let t=JSON.parse(e.getAttribute("data-nette-validation-scope")??"[]");if(!t.length)return this.showFormErrors(n,[]),!0;r=new RegExp("^("+t.join("-|")+"-)")}let l=e=>!r||r.test(e.name.replace(/]\[|\[|]|$/g,"-"));for(let e of n.elements)if(e.willValidate&&e.validity.badInput&&l(e))return t||e.reportValidity(),!1;for(let e of n.elements)if(e.getAttribute("data-nette-rules")&&l(e)&&!this.isDisabled(e)&&!this.validateControl(e,void 0,t)&&!this.formErrors.length)return!1;let i=!this.formErrors.length;return this.showFormErrors(n,this.formErrors),i}isDisabled(e){return"radio"===e.type?this.#l(e).every(e=>e.disabled):e.disabled}addError(e,t){this.formErrors.push({element:e,message:t})}showFormErrors(e,t){let r,n=[];for(let e of t)n.indexOf(e.message)<0&&(n.push(e.message),r??=e.element);n.length&&this.showModal(n.join("\n"),()=>{r?.focus()})}showModal(e,t){let r=document.createElement("dialog");if(!r.showModal)return alert(e),void t();let n=document.createElement("style");n.innerText=".netteFormsModal { text-align: center; margin: auto; border: 2px solid black; padding: 1rem } .netteFormsModal button { padding: .1em 2em }";let l=document.createElement("button");l.innerText="OK",l.onclick=()=>{r.remove(),t()},r.setAttribute("class","netteFormsModal"),r.innerText=e+"\n\n",r.append(n,l),document.body.append(r),r.showModal()}validateRule(e,t,r,n){if(e.validity.badInput)return":filled"===t;n??={value:this.getEffectiveValue(e,!0)};let l=":"===t.charAt(0)?t.substring(1):t;l=l.replace("::","_").replaceAll("\\","");let i=Array.isArray(r)?r:[r];return i.some(t=>t?.control&&!this.#n(e.form,t.control))?null:(i=i.map(t=>{if(t?.control){let r=this.#n(e.form,t.control);return r===e?n.value:this.getEffectiveValue(r,!0)}return t}),"valid"===l&&(i[0]=this),this.validators[l]?this.validators[l](e,Array.isArray(r)?i:i[0],n.value,n):null)}toggleForm(e,t){this.#t={};for(let r of Array.from(e.elements))r.getAttribute("data-nette-rules")&&this.toggleControl(r,void 0,null,!t);for(let e in this.#t)this.toggle(e,this.#t[e].state,this.#t[e].elem,t)}toggleControl(e,t,r=null,n=!1,l,i){t??=JSON.parse(e.getAttribute("data-nette-rules")??"[]"),l??={value:this.getEffectiveValue(e)},i??=!this.validateRule(e,":filled",null,l);let a,o=!1;for(let s of t){let t=s.op.match(/(~)?([^?]+)/),u=s.control?this.#n(e.form,s.control):e;if(s.neg=!!t[1],s.op=t[2],s.condition=!!s.rules,u&&(!i||s.condition||":filled"===s.op)){if(a=r,!1!==r){if(a=this.validateRule(u,s.op,s.arg,e===u?l:void 0),null===a)continue;s.neg&&(a=!a),s.condition||(r=a)}if(s.condition&&this.toggleControl(e,s.rules,a,n,l,":blank"!==s.op&&i)||s.toggle){o=!0,n&&this.#l(u).filter(e=>!this.#r.has(e)).forEach(t=>{t.addEventListener("change",t=>this.toggleForm(e.form,t)),this.#r.set(t,null)});for(let t in s.toggle??{})this.#t[t]??={elem:e,state:!1},this.#t[t].state||=s.toggle[t]?!!a:!a}}}return o}toggle(e,t,r,n){/^\w[\w.:-]*$/.test(e)&&(e="#"+e),Array.from(document.querySelectorAll(e)).forEach(e=>e.hidden=!t)}compactCheckboxes(e,t){let r={};for(let n of e.elements)n instanceof HTMLInputElement&&"checkbox"===n.type&&n.name.endsWith("[]")&&n.checked&&!n.disabled&&(t.delete(n.name),r[n.name]??=[],r[n.name].push(n.value));for(let e in r)t.set(e.substring(0,e.length-2),r[e].join(","))}initForm(e){"get"===e.method&&e.hasAttribute("data-nette-compact")&&e.addEventListener("formdata",t=>this.compactCheckboxes(e,t.formData)),Array.from(e.elements).some(e=>e.getAttribute("data-nette-rules"))&&(this.toggleForm(e),e.noValidate||(e.noValidate=!0,e.addEventListener("submit",t=>{this.validateForm(t.submitter||e)||(t.stopImmediatePropagation(),t.preventDefault())}),e.addEventListener("reset",()=>{setTimeout(()=>this.toggleForm(e))})))}initOnLoad(){this.#i(()=>{Array.from(document.forms).forEach(e=>this.initForm(e))})}};return r.version="3.5.4",r.webalize=function(e){e=e.toLowerCase();let r="";for(let n=0;n Date: Tue, 6 Aug 2024 01:34:19 +0200 Subject: [PATCH 16/47] netteForms: restructured package, includes UMD and ESM (BC break) --- package.json | 1 + rollup.config.js | 41 +++++++++++++++++++++++++----- src/assets/{ => dist}/package.json | 12 ++++----- src/assets/index.esm.ts | 7 +++++ src/assets/index.umd.ts | 2 +- tests/netteForms/setup.js | 2 +- 6 files changed, 49 insertions(+), 16 deletions(-) rename src/assets/{ => dist}/package.json (68%) create mode 100644 src/assets/index.esm.ts diff --git a/package.json b/package.json index deb29566..dd20bf35 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "rollup": "^4.62.2", "rollup-plugin-dts": "^6.4.1", "terser": "^5.48.0", + "tslib": "^2.8.1", "typescript": "^5.9.3", "vitest": "^4.1.9" }, diff --git a/rollup.config.js b/rollup.config.js index 8a369754..95ba912a 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -34,21 +34,21 @@ function spaces2tabs() { export default [ - { + { // TODO: consider the possibility of cutting off the UMD versions completely due to collision input: 'src/assets/index.umd.ts', output: [ { format: 'umd', name: 'Nette', - dir: 'src/assets', - entryFileNames: 'netteForms.js', + dir: 'src/assets/dist', + entryFileNames: 'nette-forms.umd.js', generatedCode: 'es2015', }, { format: 'umd', name: 'Nette', - dir: 'src/assets', - entryFileNames: 'netteForms.min.js', + dir: 'src/assets/dist', + entryFileNames: 'nette-forms.umd.min.js', generatedCode: 'es2015', plugins: [ terser(), @@ -65,9 +65,36 @@ export default [ }, { - input: 'src/assets/index.umd.ts', + input: 'src/assets/index.esm.ts', + output: [ + { + format: 'es', + dir: 'src/assets/dist', + entryFileNames: 'nette-forms.esm.js', + generatedCode: 'es2015', + }, + { + format: 'es', + dir: 'src/assets/dist', + entryFileNames: 'nette-forms.esm.min.js', + generatedCode: 'es2015', + plugins: [ + terser(), + ], + }, + ], + plugins: [ + json(), + nodeResolve(), + typescript(), + spaces2tabs(), + ], + }, + + { + input: 'src/assets/index.esm.ts', output: [{ - file: 'src/assets/netteForms.d.ts', + file: 'src/assets/dist/nette-forms.d.ts', format: 'es', }], plugins: [ diff --git a/src/assets/package.json b/src/assets/dist/package.json similarity index 68% rename from src/assets/package.json rename to src/assets/dist/package.json index d588874d..3aabed2d 100644 --- a/src/assets/package.json +++ b/src/assets/dist/package.json @@ -1,6 +1,6 @@ { "name": "nette-forms", - "version": "3.5.4", + "version": "4.0.0", "description": "Client side script for Nette Forms Component", "keywords": [ "nette", @@ -10,12 +10,10 @@ "homepage": "https://nette.org", "author": "David Grudl (https://davidgrudl.com)", "license": "BSD-3-Clause", - "main": "src/assets/netteForms.js", - "types": "src/assets/netteForms.d.ts", - "unpkg": "src/assets/netteForms.min.js", - "files": [ - "src/assets" - ], + "main": "nette-forms.umd.js", + "module": "nette-forms.esm.js", + "types": "nette-forms.d.ts", + "unpkg": "nette-forms.umd.min.js", "repository": { "type": "git", "url": "git+https://github.com/nette/forms.git", diff --git a/src/assets/index.esm.ts b/src/assets/index.esm.ts new file mode 100644 index 00000000..5be89db1 --- /dev/null +++ b/src/assets/index.esm.ts @@ -0,0 +1,7 @@ +import { FormValidator } from './formValidator'; + +// TODO +export function initialize() { +} + +export { FormValidator }; diff --git a/src/assets/index.umd.ts b/src/assets/index.umd.ts index 55621a62..1e73639f 100644 --- a/src/assets/index.umd.ts +++ b/src/assets/index.umd.ts @@ -1,6 +1,6 @@ import { FormValidator } from './formValidator'; import { webalize } from './webalize'; -import { version } from './package.json'; +import { version } from './dist/package.json'; type NetteForms = FormValidator & { version: string; webalize: typeof webalize }; let nette = new FormValidator as NetteForms; diff --git a/tests/netteForms/setup.js b/tests/netteForms/setup.js index f465b5fa..b3880044 100644 --- a/tests/netteForms/setup.js +++ b/tests/netteForms/setup.js @@ -7,6 +7,6 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); // Load and execute netteForms.js in global context -const netteFormsPath = join(__dirname, '../../src/assets/netteForms.js'); +const netteFormsPath = join(__dirname, '../../src/assets/dist/nette-forms.umd.js'); const netteFormsCode = fs.readFileSync(netteFormsPath, 'utf-8'); vm.runInThisContext(netteFormsCode); From 8e7f338a146e31949d91f9cbf68728a344d07ce3 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 2 Jul 2026 20:41:17 +0200 Subject: [PATCH 17/47] fixed PHPStan errors: setValue() accepts mixed, simplified Container::addComponent() --- phpstan.neon | 12 ------------ src/Forms/Container.php | 4 +--- src/Forms/Controls/BaseControl.php | 2 +- 3 files changed, 2 insertions(+), 16 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index 3cefb7df..4d473afc 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -98,18 +98,6 @@ parameters: path: src/Forms/Rules.php count: 1 - - # Parameters $caption / $key keep untyped for BC - adding native types would break - # existing user overrides of these methods in custom form controls. - identifier: missingType.parameter - message: '#^Method Nette\\Forms\\Controls\\\w+::(getLabel|getControl|getControlPart|getLabelPart)\(\) has parameter \$(caption|key) with no type specified\.$#' - paths: - - src/Forms/Controls/Button.php - - src/Forms/Controls/Checkbox.php - - src/Forms/Controls/CheckboxList.php - - src/Forms/Controls/HiddenField.php - - src/Forms/Controls/RadioList.php - - src/Forms/Controls/SubmitButton.php - - # beforeRender() keeps untyped return for BC - user overrides may not declare void. identifier: missingType.return path: src/Forms/Form.php diff --git a/src/Forms/Container.php b/src/Forms/Container.php index 4fd1e3f1..34fa1ba0 100644 --- a/src/Forms/Container.php +++ b/src/Forms/Container.php @@ -328,9 +328,7 @@ public function addComponent( } parent::addComponent($component, $name, $insertBefore); - if ($component instanceof Control || $component instanceof self) { - $this->currentGroup?->add($component); - } + $this->currentGroup?->add($component); return $this; } diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index 8ffd06bc..3e03b030 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -132,7 +132,7 @@ public function getHtmlName(): string /** @internal */ - public function setValue($value): static + public function setValue(mixed $value): static { $this->value = $value; return $this; From cb27f180a6af284541501a94641061d8060e0ddf Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 2 Jul 2026 23:17:42 +0200 Subject: [PATCH 18/47] Form, Container: submitted data are accessed layer by layer via getSubmittedData() & getSubmittedValue() (BC break) --- src/Forms/Container.php | 22 +- src/Forms/Controls/BaseControl.php | 57 ++++- src/Forms/Controls/CheckboxList.php | 5 +- src/Forms/Controls/ChoiceControl.php | 2 +- src/Forms/Controls/ImageButton.php | 12 +- src/Forms/Controls/MultiChoiceControl.php | 4 +- src/Forms/Controls/TextInput.php | 2 +- src/Forms/Controls/UploadControl.php | 2 +- src/Forms/Form.php | 55 ++-- src/Forms/Helpers.php | 67 +++-- tests/Controls/BaseControl.phpt | 11 +- tests/Forms/Container.getSubmittedData.phpt | 237 ++++++++++++++++++ ...phpt => Forms.getSubmittedData.get.2.phpt} | 2 +- ...t.phpt => Forms.getSubmittedData.get.phpt} | 6 +- ....phpt => Forms.getSubmittedData.post.phpt} | 4 +- tests/Forms/Helpers.extractHttpData.phpt | 6 +- tests/types/forms-types.php | 7 + 17 files changed, 423 insertions(+), 78 deletions(-) create mode 100644 tests/Forms/Container.getSubmittedData.phpt rename tests/Forms/{Forms.getHttpData.get.2.phpt => Forms.getSubmittedData.get.2.phpt} (91%) rename tests/Forms/{Forms.getHttpData.get.phpt => Forms.getSubmittedData.get.phpt} (87%) rename tests/Forms/{Forms.getHttpData.post.phpt => Forms.getSubmittedData.post.phpt} (92%) diff --git a/src/Forms/Container.php b/src/Forms/Container.php index 34fa1ba0..6ed1adae 100644 --- a/src/Forms/Container.php +++ b/src/Forms/Container.php @@ -10,7 +10,7 @@ use Nette; use Nette\Utils\ArrayHash; use Stringable; -use function array_key_exists, func_get_args, is_object; +use function array_key_exists, func_get_args, is_array, is_object; /** @@ -47,6 +47,26 @@ class Container extends Nette\ComponentModel\Container implements \ArrayAccess /********************* data exchange ****************d*g**/ + /** + * Returns the raw submitted HTTP data for this container's subtree. Individual values are + * unsanitized; controls sanitize them when reading via BaseControl::getSubmittedValue(). + * @return mixed[] + */ + public function getSubmittedData(): array + { + $parent = $this->getParent() ?? throw new Nette\InvalidStateException('Container has no parent.'); + assert($parent instanceof self); + $name = $this->getName(); + assert($name !== null); + if ($parent instanceof Form) { + $name = Helpers::sanitizeHtmlName($name); // mirrors generateHtmlName() which sanitizes only top-level names + } + + $data = $parent->getSubmittedData()[$name] ?? null; + return is_array($data) ? $data : []; + } + + /** * Populates controls with default values. Has no effect on submitted forms. * @param iterable|\stdClass $values diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index 3e03b030..acc9ecee 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -11,7 +11,7 @@ use Nette\Forms\{Control, Form, Rules}; use Nette\Utils\Html; use Stringable; -use function is_array; +use function is_array, is_string; /** @@ -106,21 +106,68 @@ public function getForm(bool $throw = true): ?Form */ public function loadHttpData(): void { - $this->setValue($this->getHttpData(Form::DataText)); + $this->setValue($this->getSubmittedValue(Form::DataText)); } /** - * Returns submitted HTTP value for this control. + * Returns the submitted HTTP value for this control, or one of its sub-values when $key is specified. + */ + protected function getSubmittedValue(int $type, ?string $key = null): mixed + { + $htmlName = $this->control->name; + if (is_string($htmlName)) { + // overridden HTML name attribute is an absolute pointer into the raw submitted data, bypassing the component hierarchy + $path = explode('[', str_replace(['[]', ']', '.'], ['', '', '_'], $htmlName . ($key === null ? '' : "[$key]"))); + $value = Nette\Utils\Arrays::get($this->getForm()->getSubmittedData(), $path, null); + return Nette\Forms\Helpers::sanitizeData($type, $value); + } + + $parent = $this->getParent() ?? throw new Nette\InvalidStateException('Control is not attached to any form.'); + assert($parent instanceof Nette\Forms\Container); + $name = $this->getName(); + assert($name !== null); + if ($parent instanceof Form) { + $name = Nette\Forms\Helpers::sanitizeHtmlName($name); // mirrors generateHtmlName() which sanitizes only top-level names + } + + $value = $parent->getSubmittedData()[$name] ?? null; + if ($key !== null) { + $value = is_array($value) ? ($value[$key] ?? null) : null; + } + + return Nette\Forms\Helpers::sanitizeData($type, $value); + } + + + /** + * Returns the submitted HTTP value for this control. */ protected function getHttpData(int $type, ?string $htmlTail = null): mixed { - return $this->getForm()->getHttpData($type, $this->getHtmlName() . $htmlTail); + if ($htmlTail === null || $htmlTail === '') { + return $this->getSubmittedValue($type); + } + + if (str_ends_with($htmlTail, '[]')) { + $type |= Form::DataList; + $htmlTail = substr($htmlTail, 0, -2); + } + + $keys = explode('[', str_replace([']', '.'], ['', '_'], $htmlTail)); + if ($keys[0] === '') { + array_shift($keys); + } + + $data = $this->getSubmittedValue(Form::DataArray); + assert(is_array($data)); + return Nette\Forms\Helpers::sanitizeData($type, Nette\Utils\Arrays::get($data, $keys, null)); } /** - * Returns HTML name of control. + * Returns HTML name of control. When the 'name' attribute is overridden, it is used + * both for rendering and as an absolute key for reading submitted data. */ public function getHtmlName(): string { diff --git a/src/Forms/Controls/CheckboxList.php b/src/Forms/Controls/CheckboxList.php index 5d9295aa..ef3185f3 100644 --- a/src/Forms/Controls/CheckboxList.php +++ b/src/Forms/Controls/CheckboxList.php @@ -8,6 +8,7 @@ namespace Nette\Forms\Controls; use Nette; +use Nette\Forms\Form; use Nette\Utils\Html; use Stringable; use function func_num_args, is_string; @@ -41,9 +42,9 @@ public function __construct(string|Stringable|null $label = null, ?array $items public function loadHttpData(): void { - $data = $this->getForm()->getHttpData(Nette\Forms\Form::DataText, substr($this->getHtmlName(), 0, -2)); + $data = $this->getSubmittedValue(Form::DataText); $data = match (true) { - $data === null => $this->getHttpData(Nette\Forms\Form::DataText), + $data === null => $this->getSubmittedValue(Form::DataList | Form::DataText), is_string($data) => explode(',', $data), default => [], }; diff --git a/src/Forms/Controls/ChoiceControl.php b/src/Forms/Controls/ChoiceControl.php index 2a503124..43a4b7ef 100644 --- a/src/Forms/Controls/ChoiceControl.php +++ b/src/Forms/Controls/ChoiceControl.php @@ -39,7 +39,7 @@ public function __construct(string|\Stringable|null $label = null, ?array $items public function loadHttpData(): void { - $value = $this->getHttpData(Nette\Forms\Form::DataText); + $value = $this->getSubmittedValue(Nette\Forms\Form::DataText); $this->value = $value === null ? null : key([$value => null]); } diff --git a/src/Forms/Controls/ImageButton.php b/src/Forms/Controls/ImageButton.php index 108b0406..44195ad1 100644 --- a/src/Forms/Controls/ImageButton.php +++ b/src/Forms/Controls/ImageButton.php @@ -7,6 +7,8 @@ namespace Nette\Forms\Controls; +use Nette\Forms\Form; + /** * Submittable image button form control. @@ -28,10 +30,14 @@ public function __construct(?string $src = null, ?string $alt = null) public function loadHttpData(): void { - parent::loadHttpData(); - $this->value = $this->value - ? [(int) array_shift($this->value), (int) array_shift($this->value)] + $value = $this->getSubmittedValue(Form::DataList | Form::DataText); + $this->value = $value + ? [(int) $value[0], (int) ($value[1] ?? 0)] : null; + + if ($this->value) { + $this->getForm()->setSubmittedBy($this); + } } diff --git a/src/Forms/Controls/MultiChoiceControl.php b/src/Forms/Controls/MultiChoiceControl.php index 0e7109fd..93edd709 100644 --- a/src/Forms/Controls/MultiChoiceControl.php +++ b/src/Forms/Controls/MultiChoiceControl.php @@ -8,6 +8,7 @@ namespace Nette\Forms\Controls; use Nette; +use Nette\Forms\Form; use function array_key_exists, count, is_array, is_scalar, sprintf; @@ -39,7 +40,8 @@ public function __construct(string|\Stringable|null $label = null, ?array $items public function loadHttpData(): void { - $this->value = array_keys(array_flip($this->getHttpData(Nette\Forms\Form::DataText))); + $data = $this->getSubmittedValue(Form::DataList | Form::DataText); + $this->value = array_keys(array_flip($data)); } diff --git a/src/Forms/Controls/TextInput.php b/src/Forms/Controls/TextInput.php index c50a2f5d..5a1bac18 100644 --- a/src/Forms/Controls/TextInput.php +++ b/src/Forms/Controls/TextInput.php @@ -28,7 +28,7 @@ public function __construct(string|Stringable|null $label = null, ?int $maxLengt public function loadHttpData(): void { - $this->setValue($this->getHttpData(Form::DataLine)); + $this->setValue($this->getSubmittedValue(Form::DataLine)); } diff --git a/src/Forms/Controls/UploadControl.php b/src/Forms/Controls/UploadControl.php index eb464c71..436cda0a 100644 --- a/src/Forms/Controls/UploadControl.php +++ b/src/Forms/Controls/UploadControl.php @@ -54,7 +54,7 @@ public function __construct(string|Stringable|null $label = null, bool $multiple public function loadHttpData(): void { - $this->value = $this->getHttpData(Form::DataFile); + $this->value = $this->getSubmittedValue($this->control->multiple ? Form::DataList | Form::DataFile : Form::DataFile); } diff --git a/src/Forms/Form.php b/src/Forms/Form.php index 50cd9751..409115c2 100644 --- a/src/Forms/Form.php +++ b/src/Forms/Form.php @@ -74,7 +74,8 @@ class Form extends Container implements Nette\HtmlStringable DataText = 1, DataLine = 2, DataFile = 3, - DataKeys = 8; + DataArray = 8, + DataList = 16; /** @internal tracker ID */ public const TrackerId = '_form_'; @@ -172,8 +173,11 @@ class Form extends Container implements Nette\HtmlStringable #[\Deprecated('use Form::DataFile')] public const DATA_FILE = self::DataFile; - #[\Deprecated('use Form::DataKeys')] - public const DATA_KEYS = self::DataKeys; + #[\Deprecated('use Form::DataArray')] + public const DataKeys = self::DataArray; + + #[\Deprecated('use Form::DataArray')] + public const DATA_KEYS = self::DataArray; #[\Deprecated('use Form::TrackerId')] public const TRACKER_ID = self::TrackerId; @@ -200,7 +204,7 @@ class Form extends Container implements Nette\HtmlStringable private SubmitterControl|bool $submittedBy = false; /** @var mixed[] */ - private array $httpData; + private array $submittedData; private Html $element; private FormRenderer $renderer; private ?Nette\Localization\Translator $translator = null; @@ -250,7 +254,7 @@ public function getAction(): string public function setMethod(string $method): static { - if (isset($this->httpData)) { + if (isset($this->submittedData)) { throw new Nette\InvalidStateException(__METHOD__ . '() must be called until the form is empty.'); } @@ -394,10 +398,7 @@ public function isAnchored(): bool */ public function isSubmitted(): SubmitterControl|bool { - if (!isset($this->httpData)) { - $this->getHttpData(); - } - + $this->getSubmittedData(); return $this->submittedBy; } @@ -422,30 +423,40 @@ public function setSubmittedBy(?SubmitterControl $by): static /** - * Returns raw submitted HTTP data for a control, or all form data when called without arguments. - * @return ($htmlName is null ? mixed[] : string|string[]|Nette\Http\FileUpload|Nette\Http\FileUpload[]|null) + * Returns the raw submitted HTTP data for the entire form. Individual values are + * unsanitized; controls sanitize them when reading via BaseControl::getSubmittedValue(). + * @return mixed[] */ - public function getHttpData(?int $type = null, ?string $htmlName = null): string|array|Nette\Http\FileUpload|null + public function getSubmittedData(): array { - if (!isset($this->httpData)) { + if (!isset($this->submittedData)) { if (!$this->isAnchored()) { throw new Nette\InvalidStateException('Form is not anchored and therefore can not determine whether it was submitted.'); } $data = $this->receiveHttpData(); - $this->httpData = (array) $data; + $this->submittedData = (array) $data; $this->submittedBy = is_array($data); } - if ($htmlName === null) { - return $this->httpData; - } + return $this->submittedData; + } - return Helpers::extractHttpData( - $this->httpData, - $htmlName, - $type ?? throw new Nette\InvalidArgumentException('Parameter $type must be provided when $htmlName is specified.'), - ); + + /** + * Returns submitted HTTP data. Note: inside a Repeater it operates on the raw, + * not renumbered data; use BaseControl::getSubmittedValue() instead. + * @return ($htmlName is null ? mixed[] : string|string[]|Nette\Http\FileUpload|Nette\Http\FileUpload[]|null) + */ + public function getHttpData(?int $type = null, ?string $htmlName = null): string|array|Nette\Http\FileUpload|null + { + return $htmlName === null + ? $this->getSubmittedData() + : Helpers::extractHttpData( + $this->getSubmittedData(), + $htmlName, + $type ?? throw new Nette\InvalidArgumentException('Parameter $type must be provided when $htmlName is specified.'), + ); } diff --git a/src/Forms/Helpers.php b/src/Forms/Helpers.php index 006f5782..e6fcce72 100644 --- a/src/Forms/Helpers.php +++ b/src/Forms/Helpers.php @@ -29,7 +29,7 @@ final class Helpers /** * Extracts and sanitizes submitted form data for single control. * @param mixed[] $data - * @param int $type type Form::DataText, DataLine, DataFile, DataKeys + * @param int $type type Form::DataText, DataLine, DataFile, DataArray * @return string|mixed[]|Nette\Http\FileUpload|null * @internal */ @@ -40,36 +40,41 @@ public static function extractHttpData( ): string|array|Nette\Http\FileUpload|null { $name = explode('[', str_replace(['[]', ']', '.'], ['', '', '_'], $htmlName)); - $data = Nette\Utils\Arrays::get($data, $name, null); - $itype = $type & ~Form::DataKeys; + $value = Nette\Utils\Arrays::get($data, $name, null); + $type = str_ends_with($htmlName, '[]') + ? $type | Form::DataList + : $type & ~Form::DataArray; + return static::sanitizeData($type, $value); + } + - if (str_ends_with($htmlName, '[]')) { - if (!is_array($data)) { + /** + * Sanitizes a submitted value according to the given data type (Form::DataText, DataLine, DataFile, + * optionally combined with DataArray to keep array keys or DataList to renumber them). + * @return string|mixed[]|Nette\Http\FileUpload|null + */ + public static function sanitizeData(int $type, mixed $value): string|array|Nette\Http\FileUpload|null + { + if (($type & Form::DataList) || ($type & Form::DataArray)) { + if (!is_array($value)) { return []; } - foreach ($data as $k => $v) { - $data[$k] = $v = static::sanitize($itype, $v); - if ($v === null) { - unset($data[$k]); + $itype = $type & ~(Form::DataList | Form::DataArray); + if ($itype) { + foreach ($value as $k => $v) { + $value[$k] = $v = static::sanitizeData($itype, $v); + if ($v === null) { + unset($value[$k]); + } } } - if ($type & Form::DataKeys) { - return $data; - } - - return array_values($data); - - } else { - return static::sanitize($itype, $data); - } - } - + return $type & Form::DataArray + ? $value + : array_values($value); - private static function sanitize(int $type, mixed $value): string|Nette\Http\FileUpload|null - { - if ($type === Form::DataText) { + } elseif ($type === Form::DataText) { return is_scalar($value) ? Strings::unixNewLines((string) $value) : null; @@ -100,11 +105,19 @@ public static function generateHtmlName(string $id): string $name = substr_replace($name, '', $pos, 1) . ']'; } - if (is_numeric($name) || in_array($name, self::UnsafeNames, true)) { - $name = '_' . $name; - } + return static::sanitizeHtmlName($name); + } + - return $name; + /** + * Prefixes names that would clash with JavaScript form properties or are numeric, + * mirroring the transformation applied by generateHtmlName(). + */ + public static function sanitizeHtmlName(string $name): string + { + return is_numeric($name) || in_array($name, self::UnsafeNames, true) + ? '_' . $name + : $name; } diff --git a/tests/Controls/BaseControl.phpt b/tests/Controls/BaseControl.phpt index eee11f10..9a2802b5 100644 --- a/tests/Controls/BaseControl.phpt +++ b/tests/Controls/BaseControl.phpt @@ -195,17 +195,18 @@ test('translator integration for labels and errors', function () { }); -test('dynamic HTML name attribute handling', function () { - $_POST = ['b' => '123', 'send' => '']; +test('overridden HTML name attribute redirects both rendering and loading', function () { + $_POST = ['a' => '123', 'b' => '456', 'send' => '']; $form = new Form; $form->allowCrossOrigin(); $form->addSubmit('send', 'Send'); $input = $form->addText('a'); - Assert::same('', $input->getValue()); - $input->setHtmlAttribute('name', 'b'); Assert::same('123', $input->getValue()); + $input->setHtmlAttribute('name', 'b'); + // value is reloaded using the overridden HTML name + Assert::same('456', $input->getValue()); - Assert::match('', (string) $input->getControl()); + Assert::match('', (string) $input->getControl()); }); diff --git a/tests/Forms/Container.getSubmittedData.phpt b/tests/Forms/Container.getSubmittedData.phpt new file mode 100644 index 00000000..29987832 --- /dev/null +++ b/tests/Forms/Container.getSubmittedData.phpt @@ -0,0 +1,237 @@ +day = $this->getSubmittedValue(Form::DataLine, 'day') ?? ''; + $this->month = $this->getSubmittedValue(Form::DataLine, 'month') ?? ''; + $this->year = $this->getSubmittedValue(Form::DataLine, 'year') ?? ''; + } +} + + +class LegacyDateInput extends Nette\Forms\Controls\BaseControl +{ + public string $day = ''; + public array $list = []; + + + public function loadHttpData(): void + { + $this->day = @$this->getHttpData(Form::DataLine, '[day]') ?? ''; // @ - deprecated + $this->list = @$this->getHttpData(Form::DataLine, '[items][]'); // @ - deprecated + } +} + + +test('container receives its slice of submitted data', function () { + $_POST = [ + 'name' => 'jim', + 'person' => ['age' => '30', 'address' => ['city' => 'Praha']], + 'send' => '', + ]; + + $form = new Form; + $form->allowCrossOrigin(); + $person = $form->addContainer('person'); + $address = $person->addContainer('address'); + + Assert::same($_POST, $form->getSubmittedData()); + Assert::same(['age' => '30', 'address' => ['city' => 'Praha']], $person->getSubmittedData()); + Assert::same(['city' => 'Praha'], $address->getSubmittedData()); +}); + + +test('controls in nested containers load values through their parents', function () { + $_POST = [ + 'person' => ['name' => 'jim', 'address' => ['city' => 'Praha']], + 'send' => '', + ]; + + $form = new Form; + $form->allowCrossOrigin(); + $form->addSubmit('send'); + $person = $form->addContainer('person'); + $person->addText('name'); + $person->addContainer('address')->addText('city'); + + Assert::same([ + 'person' => ['name' => 'jim', 'address' => ['city' => 'Praha']], + ], $form->getValues('array')); +}); + + +test('unsafe control names are sanitized only at the top level', function () { + $_POST = [ + '_submit' => 'a', + '_style' => ['x', 'y'], + '_123' => 'b', + 'person' => ['submit' => 'c'], + ]; + + $form = new Form; + $form->allowCrossOrigin(); + $form->addText('submit'); + $form->addCheckboxList('style', items: ['x' => 1, 'y' => 2]); + $form->addText('123'); + $form->addContainer('person')->addText('submit'); + + Assert::same('_submit', $form['submit']->getHtmlName()); + Assert::same('_style[]', $form['style']->getHtmlName()); + Assert::same('_123', $form['123']->getHtmlName()); + Assert::same('person[submit]', $form['person']['submit']->getHtmlName()); + + Assert::same('a', $form['submit']->getValue()); + Assert::same(['x', 'y'], $form['style']->getValue()); + Assert::same('b', $form['123']->getValue()); + Assert::same('c', $form['person']['submit']->getValue()); +}); + + +test('composite control reads sub-values via getSubmittedValue() with key', function () { + $_POST = [ + 'date' => ['day' => '7', 'month' => '12', 'year' => '2025'], + 'person' => ['date' => ['day' => '1', 'month' => '2', 'year' => '2000']], + 'send' => '', + ]; + + $form = new Form; + $form->allowCrossOrigin(); + $form['date'] = new CompositeDateInput; + $form->addContainer('person')['date'] = new CompositeDateInput; + + Assert::true((bool) $form->isSubmitted()); + Assert::same('7', $form['date']->day); + Assert::same('12', $form['date']->month); + Assert::same('1', $form['person']['date']->day); + Assert::same('2000', $form['person']['date']->year); +}); + + +test('deprecated getHttpData() with htmlTail works through the layered path', function () { + $_POST = [ + 'date' => ['day' => '7', 'items' => ['a', 'b']], + 'person' => ['date' => ['day' => '1', 'items' => []]], + 'send' => '', + ]; + + $form = new Form; + $form->allowCrossOrigin(); + $form['date'] = new LegacyDateInput; + $form->addContainer('person')['date'] = new LegacyDateInput; + + Assert::true((bool) $form->isSubmitted()); + Assert::same('7', $form['date']->day); + Assert::same(['a', 'b'], $form['date']->list); + Assert::same('1', $form['person']['date']->day); + Assert::same([], $form['person']['date']->list); +}); + + +test('file uploads inside containers', function () { + $file = new Nette\Http\FileUpload([ + 'name' => 'license.txt', + 'type' => '', + 'size' => 3013, + 'tmp_name' => 'tmp', + 'error' => 0, + ]); + $_POST = ['send' => '']; + $_FILES = ['person' => [ + 'name' => ['avatar' => 'license.txt'], + 'type' => ['avatar' => 'text/plain'], + 'tmp_name' => ['avatar' => 'tmp'], + 'error' => ['avatar' => 0], + 'size' => ['avatar' => 3013], + ]]; + + $form = new Form; + $form->allowCrossOrigin(); + $person = $form->addContainer('person'); + $person->addUpload('avatar'); + + Assert::equal($file, $person['avatar']->getValue()); +}); + + +test('unsubmitted form returns empty data for containers', function () { + $_SERVER['REQUEST_METHOD'] = 'GET'; + + $form = new Form; + $person = $form->addContainer('person'); + $person->addText('name'); + + Assert::false($form->isSubmitted()); + Assert::same([], $form->getSubmittedData()); + Assert::same([], $person->getSubmittedData()); + Assert::same('', $person['name']->getValue()); +}); + + +test('GET form distributes query data through containers', function () { + $_SERVER['REQUEST_METHOD'] = 'GET'; + $_GET = ['person' => ['name' => 'jim'], 'send' => '']; + $_SERVER['REQUEST_URI'] = '/?person[name]=jim&send='; + + $form = new Form; + $form->setMethod($form::Get); + $form->addContainer('person')->addText('name'); + $form->addSubmit('send'); + + Assert::truthy($form->isSubmitted()); + Assert::same(['person' => ['name' => 'jim']], $form->getValues('array')); +}); + + +test('overridden HTML name attribute is an absolute pointer bypassing the hierarchy', function () { + $_POST = [ + 'fixed_field' => 'external', + 'person' => ['a' => 'nested', 'date' => ['day' => '7']], + 'send' => '', + ]; + + $form = new Form; + $form->allowCrossOrigin(); + $person = $form->addContainer('person'); + $input = $person->addText('a'); + + Assert::same('nested', $input->getValue()); + $input->setHtmlAttribute('name', 'fixed_field'); + // the override escapes the container and reads the top-level key, exactly as in 3.x + Assert::same('external', $input->getValue()); + + // composite sub-values follow the override too + $date = new CompositeDateInput; + $form['mydate'] = $date; + $date->setHtmlAttribute('name', 'person[date]'); + Assert::same('7', $date->day); +}); + + +testException('detached container has no submitted data', function () { + $container = new Container; + $container->getSubmittedData(); +}, Nette\InvalidStateException::class, 'Container has no parent.'); diff --git a/tests/Forms/Forms.getHttpData.get.2.phpt b/tests/Forms/Forms.getSubmittedData.get.2.phpt similarity index 91% rename from tests/Forms/Forms.getHttpData.get.2.phpt rename to tests/Forms/Forms.getSubmittedData.get.2.phpt index f75ca0c6..529f57f3 100644 --- a/tests/Forms/Forms.getHttpData.get.2.phpt +++ b/tests/Forms/Forms.getSubmittedData.get.2.phpt @@ -25,6 +25,6 @@ test('GET method form submission', function () { $form->addSubmit('send', 'Send'); Assert::truthy($form->isSubmitted()); - Assert::same(['item'], $form->getHttpData()); + Assert::same(['item'], $form->getSubmittedData()); Assert::same([], $form->getValues('array')); }); diff --git a/tests/Forms/Forms.getHttpData.get.phpt b/tests/Forms/Forms.getSubmittedData.get.phpt similarity index 87% rename from tests/Forms/Forms.getHttpData.get.phpt rename to tests/Forms/Forms.getSubmittedData.get.phpt index 9d2c886c..7ab2eafa 100644 --- a/tests/Forms/Forms.getHttpData.get.phpt +++ b/tests/Forms/Forms.getSubmittedData.get.phpt @@ -24,7 +24,7 @@ test('empty GET form submission', function () { Assert::false($form->isSubmitted()); Assert::false($form->isSuccess()); - Assert::same([], $form->getHttpData()); + Assert::same([], $form->getSubmittedData()); Assert::same([], $form->getValues('array')); }); @@ -35,7 +35,7 @@ test('unsubmitted form handling', function () { $form->addSubmit('send', 'Send'); Assert::false($form->isSubmitted()); - Assert::same([], $form->getHttpData()); + Assert::same([], $form->getSubmittedData()); Assert::same([], $form->getValues('array')); }); @@ -50,7 +50,7 @@ test('tracker ID in GET submission', function () { $form->addSubmit('send', 'Send'); Assert::truthy($form->isSubmitted()); - Assert::same([Form::TrackerId => $name], $form->getHttpData()); + Assert::same([Form::TrackerId => $name], $form->getSubmittedData()); Assert::same([], $form->getValues('array')); Assert::same($name, $form[Form::TrackerId]->getValue()); }); diff --git a/tests/Forms/Forms.getHttpData.post.phpt b/tests/Forms/Forms.getSubmittedData.post.phpt similarity index 92% rename from tests/Forms/Forms.getHttpData.post.phpt rename to tests/Forms/Forms.getSubmittedData.post.phpt index 624892db..fb783a6c 100644 --- a/tests/Forms/Forms.getHttpData.post.phpt +++ b/tests/Forms/Forms.getSubmittedData.post.phpt @@ -24,7 +24,7 @@ test('GET method in POST context', function () { Assert::false($form->isSubmitted()); Assert::false($form->isSuccess()); - Assert::same([], $form->getHttpData()); + Assert::same([], $form->getSubmittedData()); Assert::same([], $form->getValues('array')); }); @@ -38,7 +38,7 @@ test('tracker ID in POST submission', function () { $form->addSubmit('send', 'Send'); Assert::truthy($form->isSubmitted()); - Assert::same([Form::TrackerId => $name], $form->getHttpData()); + Assert::same([Form::TrackerId => $name], $form->getSubmittedData()); Assert::same([], $form->getValues('array')); Assert::same($name, $form[Form::TrackerId]->getValue()); }); diff --git a/tests/Forms/Helpers.extractHttpData.phpt b/tests/Forms/Helpers.extractHttpData.phpt index aa8ffda9..464f2d73 100644 --- a/tests/Forms/Helpers.extractHttpData.phpt +++ b/tests/Forms/Helpers.extractHttpData.phpt @@ -1,7 +1,7 @@ ['x' => '1', 2 => '2']], 'multi[]', Form::DataText)); Assert::same( ['x' => '1', 2 => '2'], - Helpers::extractHttpData(['multi' => ['x' => '1', 2 => '2']], 'multi[]', Form::DataKeys | Form::DataText), + Helpers::extractHttpData(['multi' => ['x' => '1', 2 => '2']], 'multi[]', Form::DataArray | Form::DataText), ); Assert::same(['3', '4'], Helpers::extractHttpData([ @@ -80,7 +80,7 @@ test('file upload data extraction', function () { Assert::equal(['x' => $file, $file], Helpers::extractHttpData([ 'multiple' => ['avatar' => ['x' => $file, $file]], - ], 'multiple[avatar][]', Form::DataKeys | Form::DataFile)); + ], 'multiple[avatar][]', Form::DataArray | Form::DataFile)); Assert::same([], Helpers::extractHttpData([], 'missing[]', Form::DataFile)); Assert::same([], Helpers::extractHttpData(['invalid' => null], 'invalid[]', Form::DataFile)); diff --git a/tests/types/forms-types.php b/tests/types/forms-types.php index d88f1d60..396147fa 100644 --- a/tests/types/forms-types.php +++ b/tests/types/forms-types.php @@ -57,3 +57,10 @@ function testFormGetHttpData(Form $form): void assertType('array', $form->getHttpData()); assertType('array|Nette\Http\FileUpload|string|null', $form->getHttpData(Form::DataLine, 'name')); } + + +function testFormGetSubmittedData(Form $form, Nette\Forms\Container $container): void +{ + assertType('array', $form->getSubmittedData()); + assertType('array', $container->getSubmittedData()); +} From 18e2a9b2ddec938879834a563358c20a21c4c767 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sat, 4 Jul 2026 13:52:08 +0200 Subject: [PATCH 19/47] deprecated Form::getHttpData(), BaseControl::getHttpData() and Helpers::extractHttpData() --- dresscode.neon | 3 +++ examples/custom-control.php | 10 +++++----- src/Forms/Controls/BaseControl.php | 2 ++ src/Forms/Form.php | 4 +++- src/Forms/Helpers.php | 3 ++- tests/Forms/Helpers.extractHttpData.phpt | 2 ++ 6 files changed, 17 insertions(+), 7 deletions(-) diff --git a/dresscode.neon b/dresscode.neon index 25487b47..9d527d50 100644 --- a/dresscode.neon +++ b/dresscode.neon @@ -25,6 +25,9 @@ overrides: use: - compilerOptimizations - deprecations + - # the deprecated getHttpData() keeps working through the deprecated extractHttpData() + paths: [src/Forms/Form.php] + upgrading: {declarations: {deprecatedMember: keep}} - # Form::URL is established public API paths: [src/Forms/Form.php] naming: {constant: keep} diff --git a/examples/custom-control.php b/examples/custom-control.php index aa407f33..d2dbc6c4 100644 --- a/examples/custom-control.php +++ b/examples/custom-control.php @@ -27,7 +27,7 @@ public function __construct($label = null) } - public function setValue($value) + public function setValue(mixed $value): static { if ($value === null) { $this->day = $this->month = $this->year = ''; @@ -57,16 +57,16 @@ public function isFilled(): bool public function loadHttpData(): void { - $this->day = $this->getHttpData(Form::DataLine, '[day]'); - $this->month = $this->getHttpData(Form::DataLine, '[month]'); - $this->year = $this->getHttpData(Form::DataLine, '[year]'); + $this->day = $this->getSubmittedValue(Form::DataLine, 'day') ?? ''; + $this->month = $this->getSubmittedValue(Form::DataLine, 'month') ?? ''; + $this->year = $this->getSubmittedValue(Form::DataLine, 'year') ?? ''; } /** * Generates control's HTML element. */ - public function getControl() + public function getControl(): Html|string { $name = $this->getHtmlName(); return Html::el('input', [ diff --git a/src/Forms/Controls/BaseControl.php b/src/Forms/Controls/BaseControl.php index acc9ecee..6e31c9ab 100644 --- a/src/Forms/Controls/BaseControl.php +++ b/src/Forms/Controls/BaseControl.php @@ -142,7 +142,9 @@ protected function getSubmittedValue(int $type, ?string $key = null): mixed /** * Returns the submitted HTTP value for this control. + * @deprecated use getSubmittedValue() */ + #[\Deprecated('use getSubmittedValue()')] protected function getHttpData(int $type, ?string $htmlTail = null): mixed { if ($htmlTail === null || $htmlTail === '') { diff --git a/src/Forms/Form.php b/src/Forms/Form.php index 409115c2..be3bdb31 100644 --- a/src/Forms/Form.php +++ b/src/Forms/Form.php @@ -447,12 +447,14 @@ public function getSubmittedData(): array * Returns submitted HTTP data. Note: inside a Repeater it operates on the raw, * not renumbered data; use BaseControl::getSubmittedValue() instead. * @return ($htmlName is null ? mixed[] : string|string[]|Nette\Http\FileUpload|Nette\Http\FileUpload[]|null) + * @deprecated use getSubmittedData() */ + #[\Deprecated('use getSubmittedData()')] public function getHttpData(?int $type = null, ?string $htmlName = null): string|array|Nette\Http\FileUpload|null { return $htmlName === null ? $this->getSubmittedData() - : Helpers::extractHttpData( + : @Helpers::extractHttpData( // @ the deprecation is already reported above $this->getSubmittedData(), $htmlName, $type ?? throw new Nette\InvalidArgumentException('Parameter $type must be provided when $htmlName is specified.'), diff --git a/src/Forms/Helpers.php b/src/Forms/Helpers.php index e6fcce72..5493448b 100644 --- a/src/Forms/Helpers.php +++ b/src/Forms/Helpers.php @@ -31,8 +31,9 @@ final class Helpers * @param mixed[] $data * @param int $type type Form::DataText, DataLine, DataFile, DataArray * @return string|mixed[]|Nette\Http\FileUpload|null - * @internal + * @deprecated use getSubmittedData() */ + #[\Deprecated('use getSubmittedData()')] public static function extractHttpData( array $data, string $htmlName, diff --git a/tests/Forms/Helpers.extractHttpData.phpt b/tests/Forms/Helpers.extractHttpData.phpt index 464f2d73..dde37f9a 100644 --- a/tests/Forms/Helpers.extractHttpData.phpt +++ b/tests/Forms/Helpers.extractHttpData.phpt @@ -9,6 +9,8 @@ use Tester\Assert; require __DIR__ . '/../bootstrap.php'; +error_reporting(E_ALL & ~E_USER_DEPRECATED); + test('extracting simple HTTP data values', function () { Assert::same('jim', Helpers::extractHttpData(['name' => 'jim'], 'name', Form::DataLine)); From 308328f8896bb43a68487cac871b3ff1660d5e1b Mon Sep 17 00:00:00 2001 From: David Grudl Date: Wed, 8 Jul 2026 01:48:33 +0200 Subject: [PATCH 20/47] added Repeater: container with dynamically repeating items --- src/Forms/Container.php | 17 + src/Forms/Rendering/DefaultFormRenderer.php | 55 ++ src/Forms/Repeater.php | 370 +++++++++++++ src/Forms/Validator.php | 2 + tests/Forms/Repeater.loadData.phpt | 541 ++++++++++++++++++++ tests/Forms/Repeater.render.phpt | 307 +++++++++++ tests/Forms/Repeater.validation.phpt | 143 ++++++ tests/Forms/Repeater.values.phpt | 113 ++++ 8 files changed, 1548 insertions(+) create mode 100644 src/Forms/Repeater.php create mode 100644 tests/Forms/Repeater.loadData.phpt create mode 100644 tests/Forms/Repeater.render.phpt create mode 100644 tests/Forms/Repeater.validation.phpt create mode 100644 tests/Forms/Repeater.values.phpt diff --git a/src/Forms/Container.php b/src/Forms/Container.php index 6ed1adae..d098846b 100644 --- a/src/Forms/Container.php +++ b/src/Forms/Container.php @@ -652,6 +652,23 @@ public function addImage(): Controls\ImageButton } + /** + * Adds repeater (dynamic container) to the form. + * @param \Closure(Container): void $factory + */ + public function addRepeater( + string $name, + \Closure $factory, + int $min = 0, + ?int $max = null, + ?int $default = null, + ): Repeater + { + // bounds are set before attaching, when the submitted items are built + return $this[$name] = new Repeater($factory)->setBounds($min, $max, $default); + } + + /** * Adds a named sub-container for grouping related controls. */ diff --git a/src/Forms/Rendering/DefaultFormRenderer.php b/src/Forms/Rendering/DefaultFormRenderer.php index ad716f76..ed0172bb 100644 --- a/src/Forms/Rendering/DefaultFormRenderer.php +++ b/src/Forms/Rendering/DefaultFormRenderer.php @@ -75,6 +75,11 @@ class DefaultFormRenderer implements Nette\Forms\FormRenderer 'container' => 'table', ], + 'repeater' => [ + 'container' => 'fieldset class=repeater', + 'item' => null, + ], + 'pair' => [ 'container' => 'tr', '.required' => 'required', @@ -119,6 +124,9 @@ class DefaultFormRenderer implements Nette\Forms\FormRenderer protected Nette\Forms\Form $form; protected int $counter = 0; + /** @var array object ids of already rendered repeaters */ + private array $renderedRepeaters = []; + /** * Provides complete form rendering. @@ -158,6 +166,7 @@ public function render(Nette\Forms\Form $form, ?string $mode = null): string public function renderBegin(): string { $this->counter = 0; + $this->renderedRepeaters = []; foreach ($this->form->getControls() as $control) { $control->setOption('rendered', false); @@ -329,6 +338,14 @@ public function renderControls(Nette\Forms\Container|Nette\Forms\ControlGroup $p ) { // skip + } elseif ($repeater = $this->findUnrenderedRepeater($control)) { + if ($buttons) { + $container->addHtml($this->renderPairMulti($buttons)); + $buttons = null; + } + + $container->addHtml($this->renderRepeater($repeater)); + } elseif ($control->getOption('type') === 'button') { $buttons[] = $control; @@ -355,6 +372,44 @@ public function renderControls(Nette\Forms\Container|Nette\Forms\ControlGroup $p } + /** + * Renders repeater items as a static block. Client-side adding/removing of items + * is not supported by this renderer and requires Latte or manual rendering. + */ + public function renderRepeater(Nette\Forms\Repeater $repeater): string + { + $this->renderedRepeaters[spl_object_id($repeater)] = true; + + $container = $this->getWrapper('repeater container'); + foreach ($repeater->getComponents() as $item) { + assert($item instanceof Nette\Forms\Container); + $wrapper = $this->getWrapper('repeater item'); + $wrapper->setHtml($this->renderControls($item)); + $container->addHtml($wrapper); + } + + return $container->render(0); + } + + + /** + * Returns the outermost repeater the control belongs to that has not been rendered yet. + */ + private function findUnrenderedRepeater(Nette\Forms\Control $control): ?Nette\Forms\Repeater + { + $repeaters = []; + $parent = $control->getParent(); + while ($parent instanceof Nette\Forms\Container) { + if ($parent instanceof Nette\Forms\Repeater) { + $repeaters[] = $parent; + } + $parent = $parent->getParent(); + } + + return array_find(array_reverse($repeaters), fn($repeater) => !isset($this->renderedRepeaters[spl_object_id($repeater)])); + } + + /** * Renders single visual row. */ diff --git a/src/Forms/Repeater.php b/src/Forms/Repeater.php new file mode 100644 index 00000000..e6b8988a --- /dev/null +++ b/src/Forms/Repeater.php @@ -0,0 +1,370 @@ + */ + private ?array $submittedData = null; + + /** @var ?class-string */ + private ?string $itemMappedType = null; + private Html $containerPrototype; + private Html $itemPrototype; + private ?Html $addButton = null; + private ?Html $removeButton = null; + + + public function __construct( + /** @var \Closure(Container): void */ + private \Closure $factory, + ) { + $this->containerPrototype = Html::el('div'); + $this->itemPrototype = Html::el('div'); + $this->monitor(Form::class, function (Form $form): void { + if ($form->isAnchored() && $form->isSubmitted()) { + $this->loadHttpData(); + } + }); + } + + + /** + * Sets the minimum, maximum and default number of items. On a form that was not + * submitted, items are immediately created up to the default count. + */ + public function setBounds(int $min = 0, ?int $max = null, ?int $default = null): static + { + $default ??= $min; + if ($max !== null && $default > $max) { + throw new Nette\InvalidArgumentException("Default items count ($default) cannot be greater than maximum ($max)."); + } + + $this->minCount = $min; + $this->maxCount = $max; + + // submitted items are not dropped below the cap of max + reserve and missing ones are not + // padded with empty items (validate() reports the count violation instead) + if ($this->submittedCount === null) { + if ($max !== null) { + $this->ensureMaxCount($max); + } + $this->ensureMinCount($default); + } elseif ($max !== null) { + // late bounds on an already submitted form: drop the containers built beyond the cap + $this->ensureMaxCount($max + self::OverflowReserve); + } + return $this; + } + + + /** + * @param iterable|\stdClass $values + * @internal + */ + public function setValues(array|object $values, bool $erase = false, bool $onlyDisabled = false): static + { + if (!$onlyDisabled) { + $values = $values instanceof \Traversable ? iterator_to_array($values) : (array) $values; + if ($erase) { + $this->ensureMaxCount(count($values)); + } + $this->ensureMinCount(count($values)); + } + return parent::setValues($values, $erase, $onlyDisabled); + } + + + /** + * Creates child containers according to the number of submitted items. + */ + public function loadHttpData(): void + { + $data = $this->getSubmittedData(); + $this->submittedCount = count($data); + // a forged request must not invoke the (possibly expensive) factory for an unbounded + // number of items; validate() reports the violation from the raw count anyway + $build = $this->maxCount === null + ? $this->submittedCount + : min($this->submittedCount, $this->maxCount + self::OverflowReserve); + $this->ensureMaxCount($build); + $this->ensureMinCount($build); + } + + + /** + * Returns the raw submitted HTTP data with items renumbered to a continuous sequence from 0. + * Individual values are unsanitized; controls sanitize them when reading. + * @return list + */ + public function getSubmittedData(): array + { + return $this->submittedData ??= array_values(parent::getSubmittedData()); + } + + + /** + * Sets the class that individual items are mapped to when getValues() is called; + * the repeater itself then returns a list of these objects. + * @param class-string $type + */ + public function setMappedType(string $type): static + { + $this->itemMappedType = $type; + return $this; + } + + + public function getUntrustedValues(string|object|null $returnType = null, ?array $controls = null): object|array + { + if ($this->itemMappedType === null) { + return parent::getUntrustedValues($returnType, $controls); + } + + $items = []; + foreach ($this->getComponents() as $container) { + assert($container instanceof Container); + $allowed = $controls === null + || in_array($this, $controls, true) + || in_array($container, $controls, true); + $items[] = $container->getUntrustedValues($this->itemMappedType, $allowed ? null : $controls); + } + + return $items; + } + + + /** + * Performs the server side validation including the number of submitted items. + * @param (Control|Container)[]|null $controls + */ + public function validate(?array $controls = null): void + { + parent::validate($controls); + + if ($this->submittedCount === null) { + return; + } + + if ($this->submittedCount < $this->minCount) { + $this->addCountError(Validator::$messages[self::MinItems], $this->minCount); + } + if ($this->maxCount !== null && $this->submittedCount > $this->maxCount) { + $this->addCountError(Validator::$messages[self::MaxItems], $this->maxCount); + } + } + + + private function addCountError(string $message, int $count): void + { + $form = $this->getForm(); + if ($translator = $form->getTranslator()) { + $message = (string) $translator->translate($message, $count); + } + $form->addError(sprintf($message, $count), translate: false); + } + + + /** + * Only item containers can be added; controls belong to the factory closure. + */ + public function addComponent( + Nette\ComponentModel\IComponent $component, + ?string $name, + ?string $insertBefore = null, + ): static + { + if (!$component instanceof Container || $component instanceof Form) { + throw new Nette\InvalidStateException( + 'Repeater accepts only item containers, add controls in the factory passed to addRepeater().', + ); + } + + return parent::addComponent($component, $name, $insertBefore); + } + + + /** + * Creates a single repeater item container. + */ + private function createItem(int $index): Container + { + $container = new Container; + ($this->factory)($container); + $this->addComponent($container, (string) $index); + return $container; + } + + + private function ensureMinCount(int $count): void + { + for ($i = count($this->getComponents()); $i < $count; $i++) { + $this->createItem($i); + } + } + + + private function ensureMaxCount(int $count): void + { + foreach (array_slice($this->getComponents(), $count) as $component) { + $this->removeComponent($component); + } + } + + + /** + * Renders all items and the template for new ones using the given renderer, which prints the item content. + * @param \Closure(Container): void $renderer + */ + public function render(\Closure $renderer): string + { + $container = (clone $this->containerPrototype)->addAttributes($this->getContainerAttributes()); + return $container->startTag() . "\n" + . $this->renderItems($renderer) + . $container->endTag() . "\n"; + } + + + /** + * Renders the items wrapped in the item prototype and the template for new ones. + * @param \Closure(Container): void $renderer + */ + public function renderItems(\Closure $renderer): string + { + $this->prepareForRendering(); + + ob_start(); + foreach ($this->getComponents() as $index => $component) { + assert($component instanceof Container); + $item = (clone $this->itemPrototype)->data('repeater-index', (string) $index); + echo $item->startTag(); + $renderer($component); + echo $item->endTag(), "\n"; + } + + // the item wrapper is part of the template, so JS clones it including tag and attributes + $item = (clone $this->itemPrototype)->data('repeater-index', ''); + echo "\n"; + + return ob_get_clean(); + } + + + /** + * Returns the data attributes identifying the repeater for the client side. + * @return array + */ + public function getContainerAttributes(): array + { + return [ + 'data-nette-repeater' => $this->getHtmlPath(), + 'data-nette-repeater-min' => $this->minCount, + 'data-nette-repeater-max' => $this->maxCount, + ]; + } + + + /** @internal */ + public function prepareForRendering(): void + { + if ($this->submittedCount !== null) { + // re-rendering of an invalid submission shows the rows missing below the minimum + $this->ensureMinCount($this->minCount); + } + } + + + /** + * Creates a detached item container whose controls render with relative names, used for the