yaroslavbr
8/5/2016 - 3:38 PM

PaymentTransactionListener.php

<?php

namespace OroB2B\Bundle\OrderBundle\EventListener\ORM;

use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\Common\Collections\ArrayCollection;
use OroB2B\Bundle\OrderBundle\Entity\Order;
use OroB2B\Bundle\PaymentBundle\Entity\PaymentTransaction;
use OroB2B\Bundle\PaymentBundle\Provider\PaymentStatusProvider;

class PaymentTransactionListener
{
    /** @var PaymentStatusProvider */
    protected $statusProvider;

    /** @var Order */
    protected $order;

    /**
     * PaymentTransactionListener constructor.
     * @param PaymentStatusProvider $provider
     */
    public function __construct(PaymentStatusProvider $provider)
    {
        $this->statusProvider = $provider;
    }

    /**
     * @param OnFlushEventArgs $args
     */
    public function onFlush(OnFlushEventArgs $args)
    {
        $entityManager = $args->getEntityManager();
        $unitOfWork = $entityManager->getUnitOfWork();
        $insertions = $unitOfWork->getScheduledEntityInsertions();
        foreach ($insertions as $entity) {
            if ($entity instanceof PaymentTransaction && $this->order->getId() == $entity->getEntityIdentifier()) {
                $transactions = new ArrayCollection($this->statusProvider->getSavedTransactions($entity));
                $transactions->add($entity);

                $paymentStatus = $this->statusProvider->computeActualStatus($entity, $transactions);
                $paymentMethods = $this->statusProvider->getPaymentMethodsString($transactions);
                $changeSet = [
                    'paymentStatus' => [null, $paymentStatus],
                    'paymentMethods' => [null, $paymentMethods],
                ];
                $unitOfWork->scheduleExtraUpdate($this->order, $changeSet);
            } elseif ($entity instanceof Order) {
                $this->order = $entity;
            }
        }
    }
}