Skip to content

Instantly share code, notes, and snippets.

@malarzm
Created May 11, 2020 14:31
Show Gist options
  • Save malarzm/acd5113c90ad26e4e0e05c2af84137c3 to your computer and use it in GitHub Desktop.
Save malarzm/acd5113c90ad26e4e0e05c2af84137c3 to your computer and use it in GitHub Desktop.
ORM InsertIgnore
<?php
declare(strict_types=1);
namespace App\Shop\Extension\Doctrine\Execution;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
class InsertIgnore
{
private static $hackMe = [YoEntity::class];
/**
* @var \ReflectionProperty[]
*/
private $reflections = [];
public function prePersist(LifecycleEventArgs $event): void
{
if (!$this->needsHacking($event->getEntity())) {
return;
}
$em = $event->getEntityManager();
$metadata = $em->getClassMetadata(get_class($event->getEntity()));
$persister = $event->getEntityManager()->getUnitOfWork()->getEntityPersister($metadata->name);
$sql = $persister->getInsertSQL();
if (0 === strpos($sql, 'INSERT IGNORE')) {
return;
}
$sql = str_replace('INSERT', 'INSERT IGNORE', $sql);
$this->getReflection($persister)->setValue($persister, $sql);
}
private function getReflection(EntityPersister $entityPersister): \ReflectionProperty
{
$class = \get_class($entityPersister);
if (isset($this->reflections[$class])) {
return $this->reflections[$class];
}
$reflection = (new \ReflectionClass($class))->getProperty('insertSql');
$reflection->setAccessible(true);
return $this->reflections[$class] = $reflection;
}
private function needsHacking(object $entity): bool
{
foreach (self::$hackMe as $fqcn) {
if (is_a($entity, $fqcn)) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment