Skip to content

Loading Stock Information from a Different Source

Loading Stock Information from a Different Source

Overview

If Shopware is not the source of truth for your stock data, you can customize the stock loading process and provide your data from a third-party source.

Prerequisites

Here again, you will be decorating a service; therefore, it will be helpful to familiarise yourself with the Adjusting a Service guide.

Add a decorator to load the stock

For example, to load stock from a third-party API, you need to decorate \Shopware\Core\Content\Product\Stock\AbstractStockStorage and implement the load method. When products are loaded in Shopware the load method will be invoked with the loaded product IDs.

In your load method, you can access the product IDs from the StockLoadRequest instance and perform a request to your system to retrieve the data.

You then construct and return a StockDataCollection full of StockData instances. Each StockData instance represents a product.

You can use the static method Shopware\Core\Content\Product\Stock::fromArray() to construct an instance, passing in an array of the stock attributes.

There are several required values and some optional values.

AttributeTypeDescriptionOptional/Required
productIdstringThe product IDRequired
stockintThe stock amountRequired
availablebooleanWhether the product is considered availableRequired
minPurchaseintThe minimum purchase value for this productOptional
maxPurchaseintThe maximum purchase value for this productOptional
isCloseoutbooleanWhether the product can be ordered if there is not enough stockOptional

For example:

php
$stockData = \Shopware\Core\Content\Product\Stock\StockData::fromArray([
    'productId' => 'product-1',
    'stock' => 5,
    'available' => true,
    'minPurchase' => 1,
    'maxPurchase' => 10,
    'isCloseout' => false,
]);

It is also possible to provide arbitrary data via extensions:

php
$stockData = \Shopware\Core\Content\Product\Stock\StockData::fromArray([
    'productId' => 'product-1',
    'stock' => 5,
    'available' => true,
]);

$stockData->addArrayExtension('extraData', ['foo' => 'bar']);

The values in the StockData instance will be used to update the loaded product instance. Furthermore, fetching the StockData instance from the product via the stock_data extension is possible. For example:

php
$stockData = $product->getExtension('stock_data');