Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/Api/Data/AttributeSlugInterfaceFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Tweakwise\Magento2Tweakwise\Api\Data;

use Magento\Framework\ObjectManagerInterface;

class AttributeSlugInterfaceFactory
{
/**
* @param ObjectManagerInterface $objectManager
* @param string $instanceName
*/
public function __construct(
private readonly ObjectManagerInterface $objectManager,
private readonly string $instanceName = AttributeSlugInterface::class
) {
}

/**
* @param array $data
* @return AttributeSlugInterface
*/
public function create(array $data = []): AttributeSlugInterface
{
return $this->objectManager->create($this->instanceName, $data);
}
}
29 changes: 29 additions & 0 deletions src/Api/Data/AttributeSlugSearchResultsInterfaceFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Tweakwise\Magento2Tweakwise\Api\Data;

use Magento\Framework\ObjectManagerInterface;

class AttributeSlugSearchResultsInterfaceFactory
{
/**
* @param ObjectManagerInterface $objectManager
* @param string $instanceName
*/
public function __construct(
private readonly ObjectManagerInterface $objectManager,
private readonly string $instanceName = AttributeSlugSearchResultsInterface::class
) {
}

/**
* @param array $data
* @return AttributeSlugSearchResultsInterface
*/
public function create(array $data = []): AttributeSlugSearchResultsInterface
{
return $this->objectManager->create($this->instanceName, $data);
}
}
40 changes: 39 additions & 1 deletion src/Model/AttributeSlugRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,21 @@ public function save(AttributeSlugInterface $attributeSlug): AttributeSlugInterf
$baseSlug = $attributeSlug->getSlug();
$storeId = $attributeSlug->getStoreId();

// If a row for this (attribute, store_id) already exists, reuse its
// primary key so resource->save() issues an UPDATE instead of an INSERT.
try {
$existing = $this->findByAttributeAndStore((string)$attributeSlug->getAttribute(), $storeId);
$attributeSlug->setData('id', (int)$existing->getData('id')); // @phpstan-ignore-line

// The slug is already persisted correctly; nothing more to do.
if ($existing->getSlug() === $baseSlug) {
return $attributeSlug;
}
} catch (NoSuchEntityException $e) {
// No existing row — we will INSERT below.
}

// Resolve slug collisions within the same store scope.
$newSlug = $baseSlug;
$counter = 0;

Expand All @@ -90,12 +105,14 @@ public function save(AttributeSlugInterface $attributeSlug): AttributeSlugInterf
$existingSlug = $this->findBySlug($newSlug, $storeId);

if ($existingSlug->getAttribute() === $attributeSlug->getAttribute()) {
return $attributeSlug;
// Same attribute already owns this slug in this store; done.
break;
}

$counter++;
$newSlug = sprintf('%s-%s', $baseSlug, $counter);
} catch (NoSuchEntityException $e) {
// Slug is free; use it.
break;
}
}
Expand All @@ -114,6 +131,27 @@ public function save(AttributeSlugInterface $attributeSlug): AttributeSlugInterf
}
}

/**
* @param string $attribute
* @param int $storeId
* @return AttributeSlugInterface
* @throws NoSuchEntityException
*/
private function findByAttributeAndStore(string $attribute, int $storeId): AttributeSlugInterface
{
$collection = $this->collectionFactory->create()
->addFieldToFilter('attribute', $attribute)
->addFieldToFilter('store_id', (string)$storeId);

if (!$collection->getSize()) {
throw new NoSuchEntityException(__('No slug found for attribute "%1".', $attribute));
}

/** @var AttributeSlug $attributeSlug */
$attributeSlug = $collection->getFirstItem();
return $attributeSlug;
}

/**
* {@inheritdoc}
*/
Expand Down
38 changes: 30 additions & 8 deletions src/Model/Catalog/Layer/Url/Strategy/FilterSlugManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class FilterSlugManager
protected $cache;

/**
* @var array
* @var array|null
*/
protected $lookupTable;

Expand Down Expand Up @@ -108,6 +108,12 @@ public function getSlugForFilterItem(Item $filterItem): string
$attributeSlugEntity->setStoreId($storeId);

$savedSlug = $this->attributeSlugRepository->save($attributeSlugEntity);

// Update the in-memory lookup table immediately so subsequent calls in
// the same request return the cached value without hitting save() again.
$this->lookupTable[$storeId][$attribute] = $savedSlug->getSlug();

// Invalidate the shared cache so other processes pick up the new slug.
$this->cache->remove(self::CACHE_KEY);

return $savedSlug->getSlug();
Expand Down Expand Up @@ -211,7 +217,12 @@ private function saveAttributeSlugForOptionLabel(
$attributeSlugEntity->setSlug($slug);
$attributeSlugEntity->setData('attribute_code', $attributeCode); // @phpstan-ignore-line

$this->attributeSlugRepository->save($attributeSlugEntity);
$savedSlug = $this->attributeSlugRepository->save($attributeSlugEntity);

// Update the in-memory lookup table immediately so subsequent calls in
// the same request return the cached value without hitting save() again.
$this->lookupTable[$storeId][strtolower($optionLabel)] = $savedSlug->getSlug();

$this->cache->remove(self::CACHE_KEY);
}

Expand Down Expand Up @@ -289,6 +300,7 @@ protected function loadLookupTable(): array
public function truncateSlugTable(): void
{
$this->attributeSlugRepository->truncateSlugTable();
$this->lookupTable = null;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$this->lookupTable = null; or $this->lookupTable = [];?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getLookupTable() has a if ($this->lookupTable === null) guard (line 267) that triggers a DB reload
Setting it to [] would skip that check and return an empty array on the next call, meaning the in-memory cache would never be reloaded after a truncate

$this->cache->remove(self::CACHE_KEY);
}

Expand All @@ -304,11 +316,21 @@ public function createFilterSlugByOption(Option $option, int $storeId, ?string $
return;
}

$attributeSlugEntity = $this->attributeSlugFactory->create();
$attributeSlugEntity->setAttribute($option['label']);
$attributeSlugEntity->setStoreId((int)$storeId);
$attributeSlugEntity->setSlug($this->translitUrl->filter($option['label']));
$attributeSlugEntity->setData('attribute_code', $attributeCode ? $attributeCode : null); // @phpstan-ignore-line
$this->attributeSlugRepository->save($attributeSlugEntity);
// Ensure the in-memory table is initialised before we write to it.
$this->getLookupTable();

$attributeSlugEntity = $this->attributeSlugFactory->create();
$attributeSlugEntity->setAttribute($option['label']);
$attributeSlugEntity->setStoreId((int)$storeId);
$attributeSlugEntity->setSlug($this->translitUrl->filter($option['label']));
$attributeSlugEntity->setData('attribute_code', $attributeCode ? $attributeCode : null); // @phpstan-ignore-line

$savedSlug = $this->attributeSlugRepository->save($attributeSlugEntity);

// Update the in-memory lookup table immediately so subsequent calls in
// the same request return the cached value without hitting save() again.
$this->lookupTable[(int)$storeId][strtolower($option['label'])] = $savedSlug->getSlug();

$this->cache->remove(self::CACHE_KEY);
}
}
29 changes: 29 additions & 0 deletions src/Model/ResourceModel/AttributeSlug/CollectionFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Tweakwise\Magento2Tweakwise\Model\ResourceModel\AttributeSlug;

use Magento\Framework\ObjectManagerInterface;

class CollectionFactory
{
/**
* @param ObjectManagerInterface $objectManager
* @param string $instanceName
*/
public function __construct(
private readonly ObjectManagerInterface $objectManager,
private readonly string $instanceName = Collection::class
) {
}

/**
* @param array $data
* @return Collection
*/
public function create(array $data = []): Collection
{
return $this->objectManager->create($this->instanceName, $data);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

declare(strict_types=1);

namespace Tweakwise\Magento2Tweakwise\Setup\Patch\Schema;

use Magento\Framework\Setup\Patch\SchemaPatchInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class FixSlugUniqueIndexOnTweakwiseAttributeSlugTable implements SchemaPatchInterface
{
/**
* @param SchemaSetupInterface $schemaSetup
*/
public function __construct(private readonly SchemaSetupInterface $schemaSetup)
{
}

/**
* @return $this
*/
public function apply()
{
$setup = $this->schemaSetup;
$setup->startSetup();
$connection = $setup->getConnection();
$tableName = $setup->getTable('tweakwise_attribute_slug');

if ($connection->isTableExists($tableName)) {
$this->dropGlobalSlugIndex($tableName);
$this->addCompositeSlugStoreIndex($tableName);
}

$setup->endSetup();

return $this;
}

/**
* Drops the global unique index on `slug` that was created by InstallSchema.
*
* @param string $tableName
* @return void
*/
private function dropGlobalSlugIndex(string $tableName): void
{
$connection = $this->schemaSetup->getConnection();

foreach ($connection->getIndexList($tableName) as $indexName => $indexData) {
$columns = array_map('strtolower', $indexData['COLUMNS_LIST'] ?? []);
if ($columns === ['slug'] && strtoupper($indexData['INDEX_TYPE'] ?? '') === 'UNIQUE') {
$connection->dropIndex($tableName, $indexName);
break;
}
}
}

/**
* Adds a composite unique index on `(slug, store_id)` if it does not exist yet.
*
* @param string $tableName
* @return void
*/
private function addCompositeSlugStoreIndex(string $tableName): void
{
$setup = $this->schemaSetup;
$connection = $setup->getConnection();

foreach ($connection->getIndexList($tableName) as $indexData) {
$columns = array_map('strtolower', $indexData['COLUMNS_LIST'] ?? []);
sort($columns);
if ($columns === ['slug', 'store_id'] && strtoupper($indexData['INDEX_TYPE'] ?? '') === 'UNIQUE') {
return;
}
}

$connection->addIndex(
$tableName,
$setup->getIdxName($tableName, ['slug', 'store_id'], 'unique'),
['slug', 'store_id'],
'unique'
);
}

/**
* @return class-string[]
*/
public static function getDependencies()
{
return [
ChangePrimaryKeyTweakwiseAttributeSlugTable::class,
];
}

/**
* @return string[]
*/
public function getAliases()
{
return [];
}
}
Loading