<?php declare(strict_types=1);
/**
* gb media
* All Rights Reserved.
*
* Unauthorized copying of this file, via any medium is strictly prohibited.
* The content of this file is proprietary and confidential.
*
* @category Shopware
* @package Shopware_Plugins
* @subpackage GbmedEnev
* @copyright Copyright (c) 2019, gb media
* @license proprietary
* @author Giuseppe Bottino
* @link http://www.gb-media.biz
*/
namespace Gbmed\Enev\Subscriber;
use Exception;
use Gbmed\Enev\Core\Content\Enev\EnevDefinition;
use Gbmed\Enev\Service\Product as ProductService;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class LineItemAdded implements EventSubscriberInterface
{
/** @var ProductService */
private $productService;
/**
* Product constructor.
*
* @param ProductService $productService
*/
public function __construct(
ProductService $productService
) {
$this->productService = $productService;
}
public static function getSubscribedEvents()
{
return [
BeforeLineItemAddedEvent::class => 'onBeforeLineItemAddedEvent',
];
}
public function onBeforeLineItemAddedEvent(BeforeLineItemAddedEvent $event)
{
$request = Request::createFromGlobals();
$requestLineItems = $request->request->get('lineItems');
/** @var LineItem $lineItem */
foreach ($event->getCart()->getLineItems() as $key => $lineItem) {
if (empty($requestLineItems[$lineItem->getId()]) || $lineItem->hasExtension(EnevDefinition::propertyName())) {
continue;
}
$result = $this->findEnevByProduct($lineItem, $event->getSalesChannelContext());
$lineItem->addExtension(EnevDefinition::propertyName(), $result);
$lineItem->markModified();
$event->getCart()->markModified();
}
}
/**
* helper to find enev
*
* @param LineItem $lineItem
* @param SalesChannelContext $salesChannelContext
* @return EntityCollection|null
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function findEnevByProduct(
LineItem $lineItem,
SalesChannelContext $salesChannelContext
): ?EntityCollection {
try {
$result = $this->productService->findEnevByProductId(
$lineItem->getId(),
$salesChannelContext->getContext()
);
$collection = $result->getTotal()
? $this->productService->prepareEprel($result->getEntities(), $salesChannelContext)
: null;
} catch (Exception $e) {
$collection = null;
}
return $collection;
}
}