Skip to content

Commit

Permalink
valueToLabel, labelToValue 增加默认值
Browse files Browse the repository at this point in the history
  • Loading branch information
lip8up committed Mar 3, 2022
1 parent 0040a69 commit e5546cb
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,26 +212,28 @@ public static function allLabels(): array
* 获取 $value 对应的 label 或 null,若不传参数或传 null,返回整个 map,例如:[1 => '一', 2 => '二', 3 => '三']。
*
* @param mixed $value 要转换的 value
* @param mixed $default 默认的 label
*
* @return string|null|array
*/
public static function valueToLabel($value = null)
public static function valueToLabel($value = null, $default = null)
{
$map = self::columnValues(1, 0);
return $value === null ? $map : ($map[$value] ?? null);
return $value === null ? $map : ($map[$value] ?? $default);
}

/**
* 获取 $label 对应的 value 或 null,若不传参数或传 null,返回整个 map,例如:['一' => 1, '二' => 2, '三' => 3]
*
* @param string $label 要转换的 label
* @param mixed $default 默认的 value
*
* @return mixed|null|array
*/
public static function labelToValue(string $label = null)
public static function labelToValue(string $label = null, $default = null)
{
$map = self::columnValues(0, 1);
return $label === null ? $map : ($map[$label] ?? null);
return $label === null ? $map : ($map[$label] ?? $default);
}

/**
Expand Down
2 changes: 2 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ public function testValueToLabel()
$this->assertEquals(Some::valueToLabel(2), '');
$this->assertEquals(Some::valueToLabel(3), '');
$this->assertEquals(Some::valueToLabel(6), null);
$this->assertEquals(Some::valueToLabel(6, '-'), '-');

$this->assertEquals(Other::valueToLabel(), ['hh' => 'hh', 'bb' => 'bb']);
$this->assertEquals(Other::valueToLabel(null), ['hh' => 'hh', 'bb' => 'bb']);
Expand All @@ -185,6 +186,7 @@ public function testLabelToValue()
$this->assertEquals(Some::labelToValue(''), 2);
$this->assertEquals(Some::labelToValue(''), 3);
$this->assertEquals(Some::labelToValue(''), null);
$this->assertEquals(Some::labelToValue('', '-'), '-');

$this->assertEquals(Other::labelToValue(), ['hh' => 'hh', 'bb' => 'bb']);
$this->assertEquals(Other::labelToValue(null), ['hh' => 'hh', 'bb' => 'bb']);
Expand Down

0 comments on commit e5546cb

Please sign in to comment.