Skip to content

Instantly share code, notes, and snippets.

@mehdichaouch
Created January 23, 2025 12:08
Show Gist options
  • Save mehdichaouch/664afae335e28be9628c1f1a97a38a4a to your computer and use it in GitHub Desktop.
Save mehdichaouch/664afae335e28be9628c1f1a97a38a4a to your computer and use it in GitHub Desktop.
Magento 2 Store View Deletion Setup Patch - A Magento 2 data patch script to safely delete a store view and clean up related data. This patch handles the removal of store-specific configurations, URL rewrites, CMS data, catalog data, and store associations. Uses direct database operations to avoid area restrictions while maintaining referential …
<?php
declare(strict_types=1);
namespace Vendor\Module\Setup\Patch\Data;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Store\Model\StoreManagerInterface;
class DeleteStorePatch implements DataPatchInterface
{
public const STORE_TO_DELETE = 'en_ch';
public function __construct(
private readonly ModuleDataSetupInterface $moduleDataSetup,
private readonly StoreManagerInterface $storeManager
) {
}
public function apply(): DeleteEnChStorePatch
{
$this->moduleDataSetup->startSetup();
try {
$store = $this->storeManager->getStore(self::STORE_TO_DELETE);
$storeId = $store->getId();
if (!$store->isDefault()) {
$connection = $this->moduleDataSetup->getConnection();
// Delete store-specific configuration
$configTable = $this->moduleDataSetup->getTable('core_config_data');
if ($connection->isTableExists($configTable)) {
$connection->delete(
$configTable,
[
'scope = ?' => 'stores',
'scope_id = ?' => $storeId
]
);
}
// Delete from related tables
$tables = [
'url_rewrite',
'cms_page_store',
'cms_block_store',
'catalog_product_entity_int',
'catalog_category_entity_int',
'store_website_store',
'store_group_store',
'store'
];
foreach ($tables as $tableName) {
$table = $this->moduleDataSetup->getTable($tableName);
if ($connection->isTableExists($table)) {
$connection->delete(
$table,
['store_id = ?' => $storeId]
);
}
}
} else {
throw new \Exception('Cannot delete default store view.');
}
} catch (\Exception $e) {
throw new \Exception('Error deleting store: ' . $e->getMessage());
}
$this->moduleDataSetup->endSetup();
return $this;
}
public static function getDependencies(): array
{
return [];
}
public function getAliases(): array
{
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment