Created
November 14, 2020 12:08
-
-
Save wazum/0f9eb3d33618012eeecd0d9409fdba9a to your computer and use it in GitHub Desktop.
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 | |
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