Skip to content
This repository has been archived by the owner on Jul 28, 2024. It is now read-only.

Commit

Permalink
Add Objects::toArray function
Browse files Browse the repository at this point in the history
  • Loading branch information
jfilla committed Oct 29, 2019
1 parent 14626df commit ef59001
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Utils/Objects.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,26 @@ public static function set(object $object, string $property, $value)
return $object->{self::name('set', $property)}($value);
}

/**
* @param array<mixed> $keys
* @param array<mixed> $extra
* @return array<mixed>
*/
public static function toArray(object $object, array $keys, array $extra = []): array
{
$values = [];
foreach ($keys as $name) {
$values[$name] = self::get($object, $name);
}
foreach ($extra as $key => $value) {
$values[$key] = is_callable($value) ? $value(self::get($object, $key)) : $value;
}
return $values;
}

private static function name(string $prefix, string $name): string
{
return $prefix . ucfirst($name);
}

}
26 changes: 26 additions & 0 deletions tests/UtilsTests/ObjectsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,30 @@ public function testSet(): void
$this->assertSame($mock, Objects::set($mock, 'yoMama', null));
}

public function testToArray(): void
{
$mock = $this->getMockBuilder(\stdClass::class)
->addMethods(['getYoMama', 'getYo'])
->getMock();
$mock->method('getYoMama')->willReturn('chewbacca');
$mock->method('getYo')->willReturn('yo');
$this->assertEquals(
[
'yoMama' => 'chewbacca',
'yoPapa' => 'kenobi',
'yo' => 'yo',
],
Objects::toArray(
$mock,
['yoMama'],
[
'yoPapa' => 'kenobi',
'yo' => function ($yo) {
return $yo;
},
]
)
);
}

}

0 comments on commit ef59001

Please sign in to comment.