Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Created February 2, 2022 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevilopers/6641aeebb410aa7aad2a5c00813f8c2e to your computer and use it in GitHub Desktop.
Save webdevilopers/6641aeebb410aa7aad2a5c00813f8c2e to your computer and use it in GitHub Desktop.
Automatically populate PHP object from Array
<?php declare(strict_types=1);
namespace Acme\Shared\Application\Service;
trait PayloadMessage
{
private function __construct()
{}
/**
* @param array $payload
*
* @return static
* @todo Return static.
* @see https://stitcher.io/blog/php-8-before-and-after#static-instead-of-doc-blocks
*/
public static function fromPayload(array $payload)
{
$self = new static();
foreach (get_class_vars(get_class($self)) as $varName => $varValue) {
if (array_key_exists($varName, $payload)) {
$self->$varName = $payload[$varName];
}
}
return $self;
}
}
@webdevilopers
Copy link
Author

The current solution does not work e.g. for arrays.

use Symfony\Component\Validator\Constraints as Assert;

final class AddPerson
{
    use PayloadMessage;
    
    #[Assert\NotNull]
    #[Assert\Type('array')]
    private array $biographicInformation;
}
$command = AddPerson::fromPayload(
    [
	"biographicInformation": "a"
    ]
);

Cannot assign string to property AddPerson::$biographicInformation of type array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment