Skip to content

Commit

Permalink
Keep immutable
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed May 24, 2022
1 parent 3358429 commit 8d9125e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
32 changes: 20 additions & 12 deletions src/Filter/Model/FilterData.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@

namespace Sonata\AdminBundle\Filter\Model;

/**
* @psalm-immutable
*/
final class FilterData
{
private ?int $type = null;
private ?int $type;

/**
* @var mixed
Expand All @@ -24,18 +27,26 @@ final class FilterData

private bool $hasValue;

private function __construct()
/**
* @param mixed $value
*/
private function __construct(?int $type, bool $hasValue, $value = null)
{
$this->hasValue = false;
$this->type = $type;
$this->hasValue = $hasValue;

if ($hasValue) {
$this->value = $value;
}
}

/**
* @param array{type?: int|numeric-string|null, value?: mixed} $data
*
* @psalm-pure
*/
public static function fromArray(array $data): self
{
$filterData = new self();

if (isset($data['type'])) {
if (!\is_int($data['type']) && (!\is_string($data['type']) || !is_numeric($data['type']))) {
throw new \InvalidArgumentException(sprintf(
Expand All @@ -44,15 +55,12 @@ public static function fromArray(array $data): self
));
}

$filterData->type = (int) $data['type'];
}

if (\array_key_exists('value', $data)) {
$filterData->value = $data['value'];
$filterData->hasValue = true;
$type = (int) $data['type'];
} else {
$type = null;
}

return $filterData;
return new self($type, \array_key_exists('value', $data), $data['value'] ?? null);
}

/**
Expand Down
1 change: 1 addition & 0 deletions tests/Filter/Model/FilterDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public function testTypeMustBeNumericOrNull($type): void
\is_object($type) ? 'instance of "'.\get_class($type).'"' : '"'.\gettype($type).'"'
));

// @phpstan-ignore-next-line
FilterData::fromArray(['type' => $type]);
}

Expand Down

0 comments on commit 8d9125e

Please sign in to comment.