Shopware: Configuration does NOT default to current sales channel!

I just had a nice call with Bruno, one of our developers. He added a small snippet in one of our plugins:

$configKey = 'WinkelwagenRestrictAccess.config.active';
$salesChannelId = $event->getRequest()->attributes->get('sw-sales-channel-id');
if (!$this->systemConfigService->getBool($configKey, $salesChannelId)) {
    return;
}

I told him, he can omit the salesChannelId, because Shopware takes the current, if no is passed.

He disagreed, so I dig down – and he is right! Deep down in the call stack, we can find this:

// \Shopware\Core\System\SystemConfig\SystemConfigLoader::load
public function load(?string $salesChannelId): array
{
    $query = $this->connection->createQueryBuilder();

    $query->from('system_config');
    $query->select(['configuration_key', 'configuration_value']);

    if ($salesChannelId === null) {
        $query
            ->andWhere('sales_channel_id IS NULL');
    } else {
        $query->andWhere('sales_channel_id = :salesChannelId OR system_config.sales_channel_id IS NULL');
        $query->setParameter('salesChannelId', Uuid::fromHexToBytes($salesChannelId));
    }

$query->addOrderBy('sales_channel_id', 'ASC');
[...]

Culture of failure and hierarchy

I’m so used to the old Magento days, that I didn’t even think about it. And I’m very grateful, that he not only knew better, but has the courage to disagree with his boss. This is something we give our best to cultivate and I hope and think we are good with it.

The good old days: Magento

In Magento we were used to not pass the current context, because Magento took care of that. But when we have a look into the code above, we see, Shopware is not. I think this is good, because I’m a big fan of being explicit. If we don’t pass a sales context, we get the default value (which is determined by sales_channel_id IS NULL.

If we pass a $salesChannelId the query filters by both: either NULL or the $salesChannelId and after that, we order by salesChannelId ASC.

Order by <int> ASC makes NULL first

Due to the ordering, the entries with the salesChannelId comes last, so in the build lookup array the default value is written first and the sales channel specific array later. This way only one SQL query is needed and even if we write a query which returns the right config, be it default or specific it would most likely be slower than this write and update.

One thought on “Shopware: Configuration does NOT default to current sales channel!

Leave a Reply