From ec5db954fea14b165a85387a7cfe6d2f44da25a7 Mon Sep 17 00:00:00 2001 From: mscherer Date: Thu, 2 Nov 2023 15:16:04 +0100 Subject: [PATCH] Add Interface for enum labels. --- src/Database/Type/EnumLabelInterface.php | 31 +++++++++++++++++++ src/View/Helper/FormHelper.php | 4 ++- tests/TestCase/View/Helper/FormHelperTest.php | 26 ++++++++++++++++ .../Enum/ArticleStatusLabelInterface.php | 31 +++++++++++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 src/Database/Type/EnumLabelInterface.php create mode 100644 tests/test_app/TestApp/Model/Enum/ArticleStatusLabelInterface.php diff --git a/src/Database/Type/EnumLabelInterface.php b/src/Database/Type/EnumLabelInterface.php new file mode 100644 index 00000000000..ca5feb3f19b --- /dev/null +++ b/src/Database/Type/EnumLabelInterface.php @@ -0,0 +1,31 @@ +value] = method_exists($case, 'label') ? $case->label() : $case->name; + $hasLabel = $case instanceof EnumLabelInterface || method_exists($case, 'label'); + $values[$case->value] = $hasLabel ? $case->label() : $case->name; } return $values; diff --git a/tests/TestCase/View/Helper/FormHelperTest.php b/tests/TestCase/View/Helper/FormHelperTest.php index a9d3bc39deb..d504cf67a72 100644 --- a/tests/TestCase/View/Helper/FormHelperTest.php +++ b/tests/TestCase/View/Helper/FormHelperTest.php @@ -41,6 +41,7 @@ use TestApp\Model\Entity\Article; use TestApp\Model\Enum\ArticleStatus; use TestApp\Model\Enum\ArticleStatusLabel; +use TestApp\Model\Enum\ArticleStatusLabelInterface; use TestApp\Model\Table\ContactsTable; use TestApp\Model\Table\ValidateUsersTable; use TestApp\View\Form\StubContext; @@ -3671,6 +3672,31 @@ public function testControlSelectType(): void '/div', ]; $this->assertHtml($expected, $result); + + $articlesTable->getSchema()->setColumnType( + 'published', + EnumType::from(ArticleStatusLabelInterface::class) + ); + + $article = $articlesTable->newEmptyEntity(); + $this->Form->create($article); + $result = $this->Form->control('published'); + $expected = [ + 'div' => ['class' => 'input select'], + 'label' => ['for' => 'published'], + 'Published', + '/label', + 'select' => ['name' => 'published', 'id' => 'published'], + ['option' => ['value' => 'Y']], + 'Is published', + '/option', + ['option' => ['value' => 'N', 'selected' => 'selected']], + 'Is unpublished', + '/option', + '/select', + '/div', + ]; + $this->assertHtml($expected, $result); } /** diff --git a/tests/test_app/TestApp/Model/Enum/ArticleStatusLabelInterface.php b/tests/test_app/TestApp/Model/Enum/ArticleStatusLabelInterface.php new file mode 100644 index 00000000000..0c3f127a171 --- /dev/null +++ b/tests/test_app/TestApp/Model/Enum/ArticleStatusLabelInterface.php @@ -0,0 +1,31 @@ +name); + } +}