Last active
October 22, 2022 08:33
-
-
Save kconde2/0767efeddfb352ccb37a06ca557c1dbe to your computer and use it in GitHub Desktop.
nullable embeddable subscriber
This file contains 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 | |
/* | |
in config/services.yml | |
add # Doctrine listenes | |
App\EventSubscriber\NullableEmbeddableSubscriber: | |
tags: | |
- name: 'doctrine.event_subscriber' | |
*/ | |
namespace App\EventSubscriber; | |
use App\Contracts\ContainsNullableEmbeddableInterface; | |
use App\Contracts\NullableEmbeddableInterface; | |
use App\Entity\Address; | |
use Doctrine\Common\EventSubscriber; | |
use Doctrine\ORM\Event\LifecycleEventArgs; | |
use Doctrine\ORM\Events; | |
use ReflectionObject; | |
/** | |
* class NullableEmbeddableSubscriber | |
*/ | |
final class NullableEmbeddableSubscriber implements EventSubscriber | |
{ | |
/** | |
* @return array | |
*/ | |
public function getSubscribedEvents(): array | |
{ | |
return [ | |
Events::postLoad | |
]; | |
} | |
/** | |
* @param LifecycleEventArgs $args | |
* @return void | |
*/ | |
public function postLoad(LifecycleEventArgs $args): void | |
{ | |
$entity = $args->getObject(); | |
if ($entity instanceof ContainsNullableEmbeddableInterface) { | |
$objectReflection = new ReflectionObject($entity); | |
foreach ($objectReflection->getProperties() as $property) { | |
$attributes = $property->getAttributes(); | |
foreach ($attributes as $attribute) { | |
if (str_contains($attribute->getName(), 'Embedded')) { | |
$property->setAccessible(true); | |
$value = $property->getValue($entity); | |
if (($value instanceof NullableEmbeddableInterface) && $this->allPropertiesAreNull($value)) { | |
$property->setValue($entity, null); | |
} | |
} | |
} | |
} | |
} | |
} | |
/** | |
* @param NullableEmbeddableInterface $object | |
* @return bool | |
*/ | |
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