Created
October 7, 2017 08:33
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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