Skip to content

Commit

Permalink
Feature/Add map values functionality (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
othercodes authored Mar 16, 2024
1 parent e60a69f commit e7c1f8a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Traits/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace ComplexHeart\Domain\Model\Traits;

use Closure;

use function Lambdish\Phunctional\map;

/**
Expand Down Expand Up @@ -34,14 +36,20 @@ final public static function attributes(): array
*
* @return array<string, mixed>
*/
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;
}

/**
Expand Down
13 changes: 13 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

use ComplexHeart\Domain\Model\Test\OrderManagement\Domain\Price;

test('Model values should be mapped by custom function sucessfully', function() {
$price = new Price(10, 'AUD');

$values = $price->values(fn($attribute) => "-->$attribute");

expect($values['amount'])->toStartWith('-->');
expect($values['currency'])->toStartWith('-->');
})
->group('Unit');

0 comments on commit e7c1f8a

Please sign in to comment.