Skip to content

Commit

Permalink
patch
Browse files Browse the repository at this point in the history
  • Loading branch information
AnourValar committed Aug 24, 2023
1 parent b683a09 commit bddc762
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,25 @@ public function toArray(): array
return $this->resolveToArray((array) $this, static::getRules(new \ReflectionClass(static::class)));
}

/**
* Get data (filtered)
*
* @param array|string $keys
* @return array
*/
public function only(array|string $keys): array
{
$keys = (array) $keys;

return array_filter(
$this->toArray(),
function ($key) use ($keys) {
return in_array($key, $keys);
},
ARRAY_FILTER_USE_KEY
);
}

/**
* @see \JsonSerializable
*
Expand Down Expand Up @@ -191,7 +210,7 @@ protected static function getRules(\ReflectionClass $class): array
* @param array $rule
* @param \ReflectionAttribute $attribute
* @throws \RuntimeException
* @return string
* @return array
*/
protected static function handleAttribute(array $rule, \ReflectionAttribute $attribute): array
{
Expand Down
3 changes: 3 additions & 0 deletions tests/MapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ public function test_simple()
$mapper->toArray()
);

$this->assertSame(['a' => '1'], $mapper->only('a'));
$this->assertSame(['a' => '1', 'b' => null], $mapper->only(['a', 'b']));

$this->assertSame(
json_encode([
'a' => '1',
Expand Down

0 comments on commit bddc762

Please sign in to comment.