|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Buckaroo\Magento2\Model\Config\Backend; |
| 4 | + |
| 5 | +use Magento\Framework\App\Config\Value; |
| 6 | +use Magento\Framework\App\ResourceConnection; |
| 7 | + |
| 8 | +class EmptyToDelete extends Value |
| 9 | +{ |
| 10 | + /** |
| 11 | + * @var ResourceConnection |
| 12 | + */ |
| 13 | + protected $resourceConnection; |
| 14 | + |
| 15 | + /** |
| 16 | + * Constructor |
| 17 | + * |
| 18 | + * @param ResourceConnection $resourceConnection |
| 19 | + * @param \Magento\Framework\Model\Context $context |
| 20 | + * @param \Magento\Framework\Registry $registry |
| 21 | + * @param \Magento\Framework\App\Config\ScopeConfigInterface $config |
| 22 | + * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList |
| 23 | + * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource |
| 24 | + * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection |
| 25 | + * @param array $data |
| 26 | + */ |
| 27 | + public function __construct( |
| 28 | + ResourceConnection $resourceConnection, |
| 29 | + \Magento\Framework\Model\Context $context, |
| 30 | + \Magento\Framework\Registry $registry, |
| 31 | + \Magento\Framework\App\Config\ScopeConfigInterface $config, |
| 32 | + \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, |
| 33 | + \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, |
| 34 | + \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, |
| 35 | + array $data = [] |
| 36 | + ) { |
| 37 | + $this->resourceConnection = $resourceConnection; |
| 38 | + parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Delete row from core_config_data if value is empty |
| 43 | + * |
| 44 | + * @return $this |
| 45 | + */ |
| 46 | + public function beforeSave() |
| 47 | + { |
| 48 | + try { |
| 49 | + $value = $this->getValue(); |
| 50 | + |
| 51 | + // If the value is empty, delete the row |
| 52 | + if (empty($value)) { |
| 53 | + $connection = $this->resourceConnection->getConnection(); |
| 54 | + $tableName = $this->resourceConnection->getTableName('core_config_data'); |
| 55 | + |
| 56 | + $connection->delete( |
| 57 | + $tableName, |
| 58 | + [ |
| 59 | + 'path = ?' => $this->getPath(), |
| 60 | + 'scope = ?' => $this->getScope(), |
| 61 | + 'scope_id = ?' => $this->getScopeId() |
| 62 | + ] |
| 63 | + ); |
| 64 | + |
| 65 | + // Prevent saving an empty value |
| 66 | + $this->setValue(null); |
| 67 | + } |
| 68 | + } catch (\Exception $e) { |
| 69 | + $this->_logger->critical($e->getMessage()); |
| 70 | + } |
| 71 | + |
| 72 | + return parent::beforeSave(); |
| 73 | + } |
| 74 | +} |
0 commit comments