Skip to content

Commit

Permalink
Merge pull request #4 from wavevision/feature/nested-to-array
Browse files Browse the repository at this point in the history
Add nested getter for Objects::toArray
  • Loading branch information
jfilla committed May 6, 2020
2 parents eff24fa + 0d90658 commit c00374c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
22 changes: 20 additions & 2 deletions src/Utils/Objects.php
Expand Up @@ -17,6 +17,20 @@ public static function get(object $object, string $property)
return $object->{self::name('get', $property)}();
}

/**
* @return mixed
*/
public static function getNested(object $object, string ...$properties)
{
foreach ($properties as $property) {
$object = self::get($object, $property);
if (!is_object($object)) {
return $object;
}
}
return $object;
}

public static function getClassName(object $object): string
{
return Strings::getClassName(get_class($object));
Expand Down Expand Up @@ -75,8 +89,12 @@ public static function set(object $object, string $property, $value)
public static function toArray(object $object, array $keys, array $extra = []): array
{
$values = [];
foreach ($keys as $name) {
$values[$name] = self::get($object, $name);
foreach ($keys as $key => $name) {
if (is_array($name)) {
$values[is_string($key) ? $key : implode('.', $name)] = self::getNested($object, ...$name);
} else {
$values[$name] = self::get($object, $name);
}
}
foreach ($extra as $key => $value) {
$values[$key] = is_callable($value) ? $value(self::get($object, $key)) : $value;
Expand Down
19 changes: 17 additions & 2 deletions tests/UtilsTests/ObjectsTest.php
Expand Up @@ -73,19 +73,28 @@ public function testSet(): void
public function testToArray(): void
{
$mock = $this->getMockBuilder(stdClass::class)
->addMethods(['getYoMama', 'getYo'])
->addMethods(['getYoMama', 'getYo', 'getN1', 'getPope'])
->getMock();
$n2Mock = $this->getMockBuilder(stdClass::class)
->addMethods(['getN2'])
->getMock();
$n2Mock->method('getN2')->willReturn('42');
$mock->method('getYoMama')->willReturn('chewbacca');
$mock->method('getYo')->willReturn('yo');
$mock->method('getN1')->willReturn($n2Mock);
$mock->method('getPope')->willReturn(null);
$this->assertEquals(
[
'yoMama' => 'chewbacca',
'yoPapa' => 'kenobi',
'yo' => 'yo',
'n1.n2' => '42',
'n12' => '42',
'pope.of.nope' => null,
],
Objects::toArray(
$mock,
['yoMama'],
['yoMama', ['n1', 'n2'], 'n12' => ['n1', 'n2'], ['pope', 'of', 'nope']],
[
'yoPapa' => 'kenobi',
'yo' => function ($yo) {
Expand All @@ -96,6 +105,12 @@ public function testToArray(): void
);
}

public function testGetNested(): void
{
$object = new stdClass();
$this->assertEquals($object, Objects::getNested($object));
}

public function testCopyAttributes(): void
{
$source = $this->getMockBuilder(stdClass::class)
Expand Down

0 comments on commit c00374c

Please sign in to comment.