From e7c1f8abd619049dc198918e3c02c0a2bddac6a6 Mon Sep 17 00:00:00 2001 From: Unay Santisteban Date: Sat, 16 Mar 2024 17:01:23 +1000 Subject: [PATCH] Feature/Add map values functionality (#14) --- src/Traits/HasAttributes.php | 12 ++++++++++-- tests/ModelTest.php | 13 +++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 tests/ModelTest.php diff --git a/src/Traits/HasAttributes.php b/src/Traits/HasAttributes.php index 32d2428..cdaeef2 100644 --- a/src/Traits/HasAttributes.php +++ b/src/Traits/HasAttributes.php @@ -4,6 +4,8 @@ namespace ComplexHeart\Domain\Model\Traits; +use Closure; + use function Lambdish\Phunctional\map; /** @@ -34,14 +36,20 @@ final public static function attributes(): array * * @return array */ - final public function values(): array + final public function values(Closure $fn = null): array { $allowed = static::attributes(); - return array_intersect_key( + $attributes = array_intersect_key( get_object_vars($this), array_combine($allowed, $allowed) ); + + if (is_callable($fn)) { + return map($fn, $attributes); + } + + return $attributes; } /** diff --git a/tests/ModelTest.php b/tests/ModelTest.php new file mode 100644 index 0000000..2b8d6b5 --- /dev/null +++ b/tests/ModelTest.php @@ -0,0 +1,13 @@ +values(fn($attribute) => "-->$attribute"); + + expect($values['amount'])->toStartWith('-->'); + expect($values['currency'])->toStartWith('-->'); +}) + ->group('Unit');