diff --git a/src/Enum/ChoicesHelper.php b/src/Enum/ChoicesHelper.php new file mode 100644 index 0000000..0fdd85a --- /dev/null +++ b/src/Enum/ChoicesHelper.php @@ -0,0 +1,43 @@ + $value) { + if (!in_array($value, $valuesToInclude, true)) { + continue; + } + + $filtered[$label] = $value; + } + + return $filtered; + } + + public static function except(array $valuesToExclude, array $choices): array + { + if (count($valuesToExclude) === 0) { + return $choices; + } + + $filtered = []; + foreach ($choices as $label => $value) { + if (in_array($value, $valuesToExclude, true)) { + continue; + } + + $filtered[$label] = $value; + } + + return $filtered; + } +} diff --git a/tests/Enum/ChoicesHelperTest.php b/tests/Enum/ChoicesHelperTest.php new file mode 100644 index 0000000..54c157a --- /dev/null +++ b/tests/Enum/ChoicesHelperTest.php @@ -0,0 +1,44 @@ +assertCount(2, $only); + + $this->assertContains(TestEnum::VALUE_1, $only); + $this->assertContains(TestEnum::VALUE_STRING, $only); + + $this->assertArrayHasKey(TestEnum::getName(TestEnum::VALUE_1), $only); + $this->assertArrayHasKey(TestEnum::getName(TestEnum::VALUE_STRING), $only); + + $only = ChoicesHelper::except([], $choices); + $this->assertEquals($choices, $only); + } + + public function testOnly() + { + $choices = TestEnum::choices(); + $only = ChoicesHelper::only([TestEnum::VALUE_1, TestEnum::VALUE_STRING], $choices); + + $this->assertCount(2, $only); + + $this->assertContains(TestEnum::VALUE_1, $only); + $this->assertContains(TestEnum::VALUE_STRING, $only); + + $this->assertArrayHasKey(TestEnum::getName(TestEnum::VALUE_1), $only); + $this->assertArrayHasKey(TestEnum::getName(TestEnum::VALUE_STRING), $only); + + $only = ChoicesHelper::only([], $choices); + $this->assertEquals([], $only);} +}