<?php declare(strict_types=1);
namespace GlobusSW6\Subscriber\StoreLocator;
use GlobusSW6\Service\App\AppFromRequestIdentifier;
use GlobusSW6\Service\App\AppIdentifier;
use GlobusSW6\Service\App\AppService;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
use Shopware\Core\Content\Product\ProductCollection;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use GlobusSW6\Service\IaneoBusinessExtension;
class CurrentStoreStockSubscriber implements EventSubscriberInterface
{
/** @var SessionInterface */
private $session;
/** @var IaneoBusinessExtension */
private $ianeoBusinessExtensionService;
/** @var AppService */
private $appService;
/**
* @param SessionInterface $session
* @param IaneoBusinessExtension $ianeoBusinessExtensionService
* @param AppService $appService
*/
public function __construct(SessionInterface $session, IaneoBusinessExtension $ianeoBusinessExtensionService, AppService $appService)
{
$this->session = $session;
$this->ianeoBusinessExtensionService = $ianeoBusinessExtensionService;
$this->appService = $appService;
}
public static function getSubscribedEvents()
{
return [
'product.search.result.loaded' => 'appendCurrentStoreStock'
];
}
public function appendCurrentStoreStock(EntitySearchResultLoadedEvent $event)
{
// do not fire event in backend context
if ($event->getContext()->getSource() instanceof AdminApiSource) {
if ($event->getContext()->getSource()->isAdmin()) {
return;
}
}
// get products
/** @var ProductCollection $products */
$products = $event->getResult()->getEntities();
if ($products === null) {
return;
}
// get current store
$currentStore = $this->session->get('ianeoCurrentStore');
$currentStores = $this->createFakeArray($products->getIds(), $currentStore);
// Take max quantity in store from checkoutInfos, as it's already calculated there
// TODO-NGS: having the $maxQuantityInStore information in two places is redundant
$stocks = [];
/** @var ProductEntity $product */
foreach ($products as $product){
if(array_key_exists('ianeoExtensions', $product->getExtensions())){
if($product->getExtensions()['ianeoExtensions']->has('checkoutInfos')){
$maxQuantityInStore = $product->getExtensions()['ianeoExtensions']['checkoutInfos']->getMaxQuantityInStore();
$stocks[$product->getId()] = (is_null($maxQuantityInStore)) ? null : $maxQuantityInStore ;
}
}
}
// insert stock in ianeoExtension
$this->ianeoBusinessExtensionService->addAttributes($products, $currentStores, 'currentStore');
$this->ianeoBusinessExtensionService->addAttributes($products, $stocks, 'storeStock');
}
// TODO-NGS: Just for testing, remove this later on
private function createFakeArray(array $ids, $value)
{
$arr = [];
foreach ($ids as $id) {
$arr[$id] = $value;
}
return $arr;
}
}