<?php
namespace LoyxxSeminar\Subscriber;
use LoyxxSeminar\Core\Checkout\Order\OrderParticipant\OrderParticipantCollection;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemCollection;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderLoadedEventSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
protected $orderParticipantsRepository;
/**
* StorefrontRenderEventSubscriber constructor.
* @param EntityRepositoryInterface $orderParticipantsRepository
*/
public function __construct(EntityRepositoryInterface $orderParticipantsRepository)
{
$this->orderParticipantsRepository = $orderParticipantsRepository;
}
public static function getSubscribedEvents()
{
return [
OrderEvents::ORDER_LOADED_EVENT => "addParticipantsToOderLineItems",
];
}
public function addParticipantsToOderLineItems(EntityLoadedEvent $event)
{
// Load participants to current order line items
// Take all line item keys and the search participants for this keys
// Add participant to line item by filtering by line item key through the result
$lineItems = [];
foreach ($event->getEntities() as $order) {
/**@var OrderEntity $order */
if ($order->getLineItems() === null) {
continue;
}
// $lineItems += $this->filterByType($order->getLineItems(),LineItem::PRODUCT_LINE_ITEM_TYPE)->getElements();
$lineItems += $order->getLineItems()->filterByType(LineItem::PRODUCT_LINE_ITEM_TYPE)->getElements();
}
if (count($lineItems) === 0) {
return;
}
$lineItemsCollection = new OrderLineItemCollection($lineItems);
$lineItemsKeys = $lineItemsCollection->getKeys();
$criteria = (new Criteria())
->addFilter(new EqualsAnyFilter('orderLineItemId', $lineItemsKeys));
/** @var OrderParticipantCollection $participantsCollection */
$participantsCollection = $this->orderParticipantsRepository->search(
$criteria,
$event->getContext()
)->getEntities();
foreach ($lineItemsCollection as $lineItem) {
/** @var OrderLineItemEntity $lineItem */
$participants = $participantsCollection->filterByProperty('orderLineItemId', $lineItem->getId());
if ($participants->count()) {
$lineItem->addExtension('participants', $participants);
}
}
}
private function filterByType($elements, $type)
{
return $elements->filter(function (OrderLineItemEntity $lineItem) use ($type) {
return $lineItem->getType() === $type;
});
}
}