StockLoadRequest example



    public function loadCombinations(string $productId, SalesChannelContext $salesChannelContext): AvailableCombinationResult
    {
        $combinations = $this->getCombinations(
            $productId,
            $salesChannelContext->getContext(),
            $salesChannelContext->getSalesChannel()->getId()
        );

        $stocks = $this->stockStorage->load(
            new StockLoadRequest(array_keys($combinations)),
            $salesChannelContext
        );

        $result = new AvailableCombinationResult();
        foreach ($combinations as $id => $combination) {
            try {
                $options = json_decode((string) $combination['options'], true, 512, \JSON_THROW_ON_ERROR);
            } catch (\JsonException) {
                continue;
            }

            
use Shopware\Core\Content\Product\Stock\StockLoadRequest;

/** * @internal * * @covers \Shopware\Core\Content\Product\Stock\StockLoadRequest */
class StockLoadRequestTest extends TestCase
{
    public function testStockRequest(): void
    {
        $stockRequest = new StockLoadRequest(['product-1', 'product-2']);

        static::assertEquals(['product-1', 'product-2']$stockRequest->productIds);
    }
}
public static function getSubscribedEvents(): array
    {
        return [
            'sales_channel.' . ProductEvents::PRODUCT_LOADED_EVENT => 'salesChannelLoaded',
            'sales_channel.product.partial_loaded' => 'salesChannelLoaded',
        ];
    }

    public function salesChannelLoaded(SalesChannelEntityLoadedEvent $event): void
    {
        $stocks = $this->stockStorage->load(
            new StockLoadRequest($event->getIds()),
            $event->getSalesChannelContext()
        );

        foreach ($event->getEntities() as $product) {
            /** @var ProductEntity $product */
            $stock = $stocks->getStockForProductId($product->getId());

            if ($stock === null) {
                continue;
            }

            
$productIds = $ids->getList(['p-1', 'p-2', 'p-3']);
        $salesChannelContext = $this->createMock(SalesChannelContext::class);

        $connection = $this->createMock(Connection::class);
        $dispatcher = $this->createMock(EventDispatcherInterface::class);

        $stockStorage = new StockStorage($connection$dispatcher);

        static::assertEquals(
            [],
            $stockStorage->load(new StockLoadRequest(array_values($productIds))$salesChannelContext)->all()
        );
    }
}
Home | Imprint | This part of the site doesn't use cookies.