Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jissereitsma/75de17356d33c75550d23bdb730a8d9a to your computer and use it in GitHub Desktop.
Save jissereitsma/75de17356d33c75550d23bdb730a8d9a to your computer and use it in GitHub Desktop.
Magento 1 script to reset attribute models if model can not be instantiated (because module is uninstalled)
<?php
require_once 'app/Mage.php';
Mage::app();
$autoFix = true;
class Clean_Attribute_Source_Models
{
private $autofix;
private $modelFields = ['backend_model', 'frontend_model', 'source_model'];
/**
* @var Mage_Core_Model_Resource
*/
private $resource;
public function __construct($autofix = false)
{
$this->autofix = $autofix;
$this->resource = Mage::getSingleton('core/resource');
}
public function run()
{
foreach ($this->getAttributeRows() as $attributeRow) {
$this->handleAttributeRow($attributeRow);
}
}
private function handleAttributeRow($attributeRow)
{
foreach ($this->modelFields as $modelField) {
if (!empty($attributeRow[$modelField]) && !$this->instantiateModel($attributeRow[$modelField])) {
echo "$modelField '" . $attributeRow[$modelField] . "' [".$attributeRow['attribute_id']."] could not be resolved\n";
$this->fixAttributeRowModelField($attributeRow['attribute_id'], $modelField);
}
}
}
private function fixAttributeRowModelField($attributeId, $modelField)
{
$eavAttributeTableName = $this->resource->getTableName('eav_attribute');
$query = 'UPDATE '.$eavAttributeTableName.' SET `'.$modelField.'`="" WHERE `attribute_id`='.$attributeId;
$this->getWriteConnection()->query($query);
}
private function instantiateModel($modelName)
{
try {
$model = Mage::getModel($modelName);
} catch (Exception $e) {
return false;
}
if (empty($model)) {
return false;
}
return true;
}
private function getAttributeRows()
{
$eavAttributeTableName = $this->resource->getTableName('eav_attribute');
$query = 'SELECT attribute_id,' . implode(',', $this->modelFields) . ' FROM ' . $eavAttributeTableName;
return $this->getReadConnection()->fetchAll($query);
}
private function getReadConnection()
{
return $this->resource->getConnection('core_write');
}
private function getWriteConnection()
{
return $this->resource->getConnection('core_write');
}
}
(new Clean_Attribute_Source_Models($autoFix))->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment