Created
March 24, 2022 08:25
-
-
Save jlambe/da062e717c391d423a139186e410fc02 to your computer and use it in GitHub Desktop.
Flatten data objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class PostContentData { | |
public function __construct( | |
public string $excerpt, | |
public string $content, | |
) {} | |
} | |
class SettingsData { | |
public function __construct( | |
public string $name, | |
public string $title, | |
public PostContentData $post, | |
) | |
{} | |
} | |
/* | |
* Given the following objects, calling the `toArray()` method will produce this array: | |
*/ | |
[ | |
'name' => 'John', | |
'title' => 'The Hero', | |
'post' => [ | |
'excerpt' => 'Story summary', | |
'content' => 'A long time ago...' | |
], | |
] | |
/* | |
* I would have liked a native method to flatten the transformed data where for each nested data objects, | |
* we only get their properties like so, putting them all at the same level: | |
*/ | |
[ | |
'name' => 'John', | |
'title' => 'The Hero', | |
'excerpt' => 'Story summary', | |
'content' => 'A long time ago...' | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment