Skip to content

Commit

Permalink
add ChoicesHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
Mickael GOETZ committed Nov 24, 2019
1 parent b5906af commit 78e2439
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/Enum/ChoicesHelper.php
@@ -0,0 +1,43 @@
<?php

namespace Mesavolt\Enum;


abstract class ChoicesHelper
{
public static function only(array $valuesToInclude, array $choices): array
{
if (count($valuesToInclude) === 0) {
return [];
}

$filtered = [];
foreach ($choices as $label => $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;
}
}
44 changes: 44 additions & 0 deletions tests/Enum/ChoicesHelperTest.php
@@ -0,0 +1,44 @@
<?php

namespace Mesavolt\Tests\Enum;


use Mesavolt\Enum\ChoicesHelper;
use Mesavolt\Tests\Fixture\TestEnum;
use PHPUnit\Framework\TestCase;

class ChoicesHelperTest extends TestCase
{
public function testExcept()
{
$choices = TestEnum::choices();
$only = ChoicesHelper::except([TestEnum::VALUE_2], $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::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);}
}

0 comments on commit 78e2439

Please sign in to comment.