diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e291fb7..789e268f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Enh #261: Enhance `RadioList::addRadioWrapClass()` method for cleaner class addition (@vjik) - Enh #263: Explicitly import classes and constants in "use" section (@mspirkov) - Chg #243: Deprecate static constructors such as `TagName::tag()` in favor of `new TagName()` (@razvbir) +- Chg #221: Throw `LogicException` in `Tag::id()` when id is empty string (@razvbir) ## 3.12.0 December 13, 2025 diff --git a/src/Tag/Base/Tag.php b/src/Tag/Base/Tag.php index 942da0eb..f8dc389c 100644 --- a/src/Tag/Base/Tag.php +++ b/src/Tag/Base/Tag.php @@ -5,6 +5,7 @@ namespace Yiisoft\Html\Tag\Base; use BackedEnum; +use LogicException; use Yiisoft\Html\Html; use Yiisoft\Html\NoEncodeStringableInterface; @@ -75,10 +76,14 @@ final public function attribute(string $name, mixed $value): static * * @param string|null $id Tag ID. * - * @psalm-param non-empty-string|null $id + * @throws LogicException */ final public function id(?string $id): static { + if ($id === '') { + throw new LogicException('The tag id cannot be an empty string.'); + } + $new = clone $this; $new->attributes['id'] = $id; return $new; diff --git a/tests/Tag/Base/TagTest.php b/tests/Tag/Base/TagTest.php index e0a3416f..62ca4310 100644 --- a/tests/Tag/Base/TagTest.php +++ b/tests/Tag/Base/TagTest.php @@ -4,6 +4,7 @@ namespace Yiisoft\Html\Tests\Tag\Base; +use LogicException; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Yiisoft\Html\Tests\Objects\TestTag; @@ -132,6 +133,13 @@ public function testId(string $expected, ?string $id): void $this->assertSame($expected, (string) (new TestTag())->id($id)); } + public function testIdEmptyString(): void + { + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The tag id cannot be an empty string.'); + (new TestTag())->id(''); + } + public static function dataAddClass(): array { return [