<?php declare(strict_types=1);
namespace Nd\Theme\Subscriber;
use Shopware\Core\Checkout\Order\SalesChannel\AbstractOrderRoute;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Event\RouteRequest\OrderRouteRequestEvent;
use Shopware\Storefront\Page\Account\Overview\AccountOverviewPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\HttpFoundation\Request;
class AccountOverviewSubscriber implements EventSubscriberInterface
{
private EventDispatcherInterface $eventDispatcher;
private AbstractOrderRoute $orderRoute;
public function __construct(EventDispatcherInterface $eventDispatcher, AbstractOrderRoute $orderRoute)
{
$this->eventDispatcher = $eventDispatcher;
$this->orderRoute = $orderRoute;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
AccountOverviewPageLoadedEvent::class => 'addData',
];
}
public function addData(AccountOverviewPageLoadedEvent $event)
{
$page = $event->getPage();
$newestOrders = new ArrayStruct();
$newestOrders->set('newest_orders', $this->getNewestOrders($event->getSalesChannelContext(), $event->getRequest()));
//dump($this->getNewestOrders($event->getSalesChannelContext(), $event->getRequest()));
$page->addExtension('newest_orders', $newestOrders);
}
public function getNewestOrders(SalesChannelContext $context, Request $request ){
$criteria = (new Criteria())
->addSorting(new FieldSorting('orderDateTime', FieldSorting::DESCENDING))
->addAssociation('lineItems')
->addAssociation('lineItems.cover')
->addAssociation('transactions.paymentMethod')
->addAssociation('deliveries.shippingMethod')
->addAssociation('addresses')
->addAssociation('currency')
->addAssociation('documents.documentType')
->setLimit(4)
->addAssociation('orderCustomer');
$criteria->getAssociation('transactions')
->addSorting(new FieldSorting('createdAt'));
$apiRequest = new Request();
$event = new OrderRouteRequestEvent($request, $apiRequest, $context, $criteria);
$this->eventDispatcher->dispatch($event);
$responseStruct = $this->orderRoute
->load($event->getStoreApiRequest(), $context, $criteria);
return $responseStruct->getOrders()->getEntities();
}
}