|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\Directory\Model\Config\Backend; |
| 9 | + |
| 10 | +use Magento\Directory\Model\Config\Source\WeightUnit as Source; |
| 11 | +use Magento\Framework\App\Cache\TypeListInterface; |
| 12 | +use Magento\Framework\App\Config\ScopeConfigInterface; |
| 13 | +use Magento\Framework\App\Config\Value; |
| 14 | +use Magento\Framework\Data\Collection\AbstractDb; |
| 15 | +use Magento\Framework\Exception\LocalizedException; |
| 16 | +use Magento\Framework\Model\Context; |
| 17 | +use Magento\Framework\Model\ResourceModel\AbstractResource; |
| 18 | +use Magento\Framework\Registry; |
| 19 | + |
| 20 | +/** |
| 21 | + * Backend source for weight unit configuration field |
| 22 | + */ |
| 23 | +class WeightUnit extends Value |
| 24 | +{ |
| 25 | + /** |
| 26 | + * @var Source |
| 27 | + */ |
| 28 | + private $source; |
| 29 | + |
| 30 | + /** |
| 31 | + * @param Source $source |
| 32 | + * @param Context $context |
| 33 | + * @param Registry $registry |
| 34 | + * @param ScopeConfigInterface $config |
| 35 | + * @param TypeListInterface $cacheTypeList |
| 36 | + * @param AbstractResource $resource |
| 37 | + * @param AbstractDb $resourceCollection |
| 38 | + * @param array $data |
| 39 | + * |
| 40 | + * @codeCoverageIgnore |
| 41 | + */ |
| 42 | + public function __construct( |
| 43 | + Source $source, |
| 44 | + Context $context, |
| 45 | + Registry $registry, |
| 46 | + ScopeConfigInterface $config, |
| 47 | + TypeListInterface $cacheTypeList, |
| 48 | + AbstractResource $resource = null, |
| 49 | + AbstractDb $resourceCollection = null, |
| 50 | + array $data = [] |
| 51 | + ) { |
| 52 | + $this->source = $source; |
| 53 | + parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Check whether weight unit value is acceptable or not |
| 58 | + * |
| 59 | + * @return $this |
| 60 | + */ |
| 61 | + public function beforeSave() |
| 62 | + { |
| 63 | + if ($this->isValueChanged()) { |
| 64 | + $weightUnit = $this->getData('value'); |
| 65 | + if (!in_array($weightUnit, $this->getOptions())) { |
| 66 | + throw new LocalizedException(__('There was an error save new configuration value.')); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return parent::beforeSave(); |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Get available options for weight unit |
| 75 | + * |
| 76 | + * @return array |
| 77 | + */ |
| 78 | + private function getOptions() |
| 79 | + { |
| 80 | + $options = $this->source->toOptionArray(); |
| 81 | + |
| 82 | + return array_column($options, 'value'); |
| 83 | + } |
| 84 | +} |
0 commit comments