Skip to content

Instantly share code, notes, and snippets.

@meshenka
Created July 19, 2019 15:56
Show Gist options
  • Save meshenka/182339d95aa439e1d0a84c63ec398083 to your computer and use it in GitHub Desktop.
Save meshenka/182339d95aa439e1d0a84c63ec398083 to your computer and use it in GitHub Desktop.
onFlush v2
<?php
declare(strict_types=1);
namespace App\Accounting\Entity;
use App\Application\Annotation\Legacy;
use App\Application\Entity\Replicable;
use App\Accounting\Model\PaymentMeanInterface;
use App\Accounting\PaymentMeans;
use App\Membership\Entity\Member;
use DateTime;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="collect", indexes={
* @ORM\Index(name="business_id", columns={"business_id"}),
* @ORM\Index(name="alias", columns={"alias"}),
* @ORM\Index(name="member_id_fk", columns={"member_id_fk"}),
* @ORM\Index(name="member_id", columns={"member_id"}),
* @ORM\Index(name="slug", columns={"slug"}),
* })
* @ORM\Entity(repositoryClass="App\Accounting\Repository\CollectRepository")
*/
class Collect implements PaymentMeanInterface, Replicable
{
//...
/**
* @Legacy
*/
public function replicate(): void
{
if ($member = $this->getMember()) {
$this->memberId = $member->getId();
}
}
}
<?php
declare(strict_types=1);
namespace App\Application\Entity;
use App\Application\Annotation\Legacy;
/**
* @Legacy
*/
interface Replicable
{
public function replicate(): void;
}
<?php
declare(strict_types=1);
namespace App\Application\Legacy;
use App\Application\Annotation\Legacy;
use App\Application\Entity\Replicable;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\UnitOfWork;
/**
* @Legacy
*/
class ReplicableFkSubscriber implements EventSubscriber
{
public function onFlush(OnFlushEventArgs $event)
{
$entityManager = $event->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
foreach ($unitOfWork->getScheduledEntityInsertions() as $entity) {
$this->replicate($entity, $entityManager, $unitOfWork);
}
foreach ($unitOfWork->getScheduledEntityUpdates() as $entity) {
$this->replicate($entity, $entityManager, $unitOfWork);
}
}
public function getSubscribedEvents()
{
return [
Events::onFlush,
];
}
private function replicate(object $entity, EntityManager $entityManager, UnitOfWork $unitOfWork): void
{
/** @var Replicable $entity */
if ($entity instanceof Replicable) {
$fqnClass = get_class($entity);
$entity->replicate();
$classMetadata = $entityManager->getClassMetadata($fqnClass);
$unitOfWork->recomputeSingleEntityChangeSet($classMetadata, $entity);
}
}
}
App\Application\Legacy\ReplicableFkSubscriber:
autowire: true
tags:
- { name: doctrine.event_subscriber }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment