Skip to content

Instantly share code, notes, and snippets.

@florinel-chis
Created January 22, 2025 21:13
Show Gist options
  • Save florinel-chis/9e33919a0ffdd799de5a28fcfeee04eb to your computer and use it in GitHub Desktop.
Save florinel-chis/9e33919a0ffdd799de5a28fcfeee04eb to your computer and use it in GitHub Desktop.
<?php
use Magento\Framework\App\Bootstrap;
// Validate input parameters
if ($argc < 3) {
die("Usage: php remove_attributes.php <attribute_set_id> <attribute_code1> [attribute_code2] ...\n");
}
$attributeSetId = (int)$argv[1];
$attributeCodes = array_slice($argv, 2);
// Initialize Magento
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
try {
// Get resource connection
$resource = $objectManager->get(\Magento\Framework\App\ResourceConnection::class);
$connection = $resource->getConnection();
// Get table names
$eavAttributeTable = $resource->getTableName('eav_attribute');
$eavAttributeSetTable = $resource->getTableName('eav_attribute_set');
$eavEntityAttributeTable = $resource->getTableName('eav_entity_attribute');
// Validate attribute set exists
$attributeSetCheck = "SELECT attribute_set_id, attribute_set_name
FROM {$eavAttributeSetTable}
WHERE attribute_set_id = ?";
$attributeSet = $connection->fetchRow($attributeSetCheck, [$attributeSetId]);
if (!$attributeSet) {
throw new \Exception("Attribute set ID {$attributeSetId} does not exist!");
}
// Get entity type ID for catalog_product
$entityTypeCode = 'catalog_product';
$entityTypeTable = $resource->getTableName('eav_entity_type');
$entityTypeId = $connection->fetchOne(
"SELECT entity_type_id FROM {$entityTypeTable} WHERE entity_type_code = ?",
[$entityTypeCode]
);
// Validate attributes exist and get their IDs
$placeholders = str_repeat('?,', count($attributeCodes) - 1) . '?';
$attributeQuery = "SELECT attribute_id, attribute_code, frontend_label
FROM {$eavAttributeTable}
WHERE attribute_code IN ({$placeholders})
AND entity_type_id = ?";
$params = array_merge($attributeCodes, [$entityTypeId]);
$attributes = $connection->fetchAll($attributeQuery, $params);
if (count($attributes) !== count($attributeCodes)) {
$foundCodes = array_column($attributes, 'attribute_code');
$missingCodes = array_diff($attributeCodes, $foundCodes);
throw new \Exception("Some attributes not found: " . implode(', ', $missingCodes));
}
// Preview the changes
echo "About to remove the following attributes from set '{$attributeSet['attribute_set_name']}':\n";
echo str_repeat("-", 80) . "\n";
echo sprintf("%-40s %-20s %s\n", "Attribute Code", "Attribute ID", "Frontend Label");
echo str_repeat("-", 80) . "\n";
foreach ($attributes as $attribute) {
echo sprintf("%-40s %-20s %s\n",
$attribute['attribute_code'],
$attribute['attribute_id'],
$attribute['frontend_label']
);
}
echo "\nDo you want to proceed? (y/n): ";
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
if (trim(strtolower($line)) != 'y') {
echo "Operation cancelled.\n";
exit;
}
// Start transaction
$connection->beginTransaction();
try {
$attributeIds = array_column($attributes, 'attribute_id');
$placeholders = str_repeat('?,', count($attributeIds) - 1) . '?';
// Remove from eav_entity_attribute
$deleteQuery = "DELETE FROM {$eavEntityAttributeTable}
WHERE attribute_id IN ({$placeholders})
AND attribute_set_id = ?";
$params = array_merge($attributeIds, [$attributeSetId]);
$result = $connection->query($deleteQuery, $params);
$affectedRows = $result->rowCount();
// Create log
$logFile = BP . '/var/log/attribute_removal_' . date('Y-m-d_H-i-s') . '.log';
$logContent = "Attribute removal performed at: " . date('Y-m-d H:i:s') . "\n";
$logContent .= "Attribute Set: {$attributeSet['attribute_set_name']} (ID: {$attributeSetId})\n";
$logContent .= "Removed Attributes:\n";
foreach ($attributes as $attribute) {
$logContent .= sprintf("- %s (ID: %d, Label: %s)\n",
$attribute['attribute_code'],
$attribute['attribute_id'],
$attribute['frontend_label']
);
}
file_put_contents($logFile, $logContent);
$connection->commit();
echo "\nSuccessfully removed {$affectedRows} attribute-set relations.\n";
echo "Log file created at: $logFile\n";
} catch (\Exception $e) {
$connection->rollBack();
throw $e;
}
} catch (\Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment