Skip to content

Instantly share code, notes, and snippets.

@wazum
Created November 14, 2020 12:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wazum/0f9eb3d33618012eeecd0d9409fdba9a to your computer and use it in GitHub Desktop.
Save wazum/0f9eb3d33618012eeecd0d9409fdba9a to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\Something\Infrastructure\Doctrine\EventSubscriber;
use App\Something\Domain\Contracts\ContainsNullableEmbeddable;
use App\Something\Domain\Contracts\NullableEmbeddable as NullableEmbeddableInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use ReflectionObject;
final class NullableEmbeddable implements EventSubscriber
{
public function getSubscribedEvents(): array
{
return [
Events::postLoad
];
}
public function postLoad(LifecycleEventArgs $args): void
{
$entity = $args->getObject();
if ($entity instanceof ContainsNullableEmbeddable) {
$objectReflection = new ReflectionObject($entity);
foreach ($objectReflection->getProperties() as $property) {
if (preg_match('/@.*?Embedded\(/', $property->getDocComment())) {
$property->setAccessible(true);
$value = $property->getValue($entity);
if (($value instanceof NullableEmbeddableInterface) && $this->allPropertiesAreNull($value)) {
$property->setValue($entity, null);
}
}
}
}
}
private function allPropertiesAreNull(NullableEmbeddableInterface $object): bool
{
$objectReflection = new ReflectionObject($object);
foreach ($objectReflection->getProperties() as $property) {
$property->setAccessible(true);
if (null !== $property->getValue($object)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment