Search code examples
shopwareshopware6

Shopware 6 get products from product stream with currency and storefront language


i have the following variables:

$secretApiKey = $a->get('secretApiKey');
$publicApiKey = $a->get('publicApiKey');
$productStreamId = $a->get('productStreamId');
$salesChannelId = $a->get('salesChannelId');
$ruleId = $a->get('ruleId');
$currencyId = $a->get('currencyId');

how can i get the products from the product stream with the currency and the default language of the storefront given?

I have seen the following: https://github.com/shopware/core/blob/trunk/Content/Product/SalesChannel/CrossSelling/ProductCrossSellingRoute.php

But i dont have a context, cause the function can be executed by an command and scheduler.


Solution

  • You can simply construct the context yourself if you have all the necessary arguments.

    <service id="SwagBasicExample\Command\ExampleCommand">
        <argument type="service" id="product.repository"/>
        <argument type="service" id="Shopware\Core\Content\ProductStream\Service\ProductStreamBuilder"/>
        <tag name="console.command"/>
    </service>
    
    $context = new Context(
        new SystemSource(),
        [$ruleId],
        $currencyId,
        [$languageId, Defaults::LANGUAGE_SYSTEM]
    );
    
    $filters = $this->productStreamBuilder->buildFilters(
        $productStreamId,
        $context
    );
    
    $criteria = new Criteria();
    $criteria->addFilter(...$filters);
    
    $products = $this->productRepository->search($criteria, $context);
    

    Alternatively you can inject AbstractSalesChannelContextFactory to build the entire SalesChannelContext and thus also the Context from only the id of the sales channel.

    <argument type="service" id="Shopware\Core\System\SalesChannel\Context\SalesChannelContextFactory"/>
    
    // You can optionally override the options of the sales channel
    // e.g. if a sales channel has multiple languages assigned
    // and you want to use a language other than the default
    $options = [
        SalesChannelContextService::LANGUAGE_ID => $languageId,
    ];
    
    $salesChannelContext = $this->salesChannelContextFactory->create(
        Uuid::randomHex(),
        $salesChannelId,
        $options
    );
    $context = $salesChannelContext->getContext();