FixedRates.php in Currency 8.3
File
src/Plugin/Currency/ExchangeRateProvider/FixedRates.php
View source
<?php
namespace Drupal\currency\Plugin\Currency\ExchangeRateProvider;
use Commercie\CurrencyExchange\FixedExchangeRateProviderTrait;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FixedRates extends PluginBase implements ExchangeRateProviderInterface, ContainerFactoryPluginInterface {
use FixedExchangeRateProviderTrait;
protected $configFactory;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, ConfigFactoryInterface $config_factory) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->configFactory = $config_factory;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('config.factory'));
}
public function loadAll() {
$rates_data = $this->configFactory
->get('currency.exchanger.fixed_rates')
->get('rates');
$rates = array();
foreach ($rates_data as $rate_data) {
$rates[$rate_data['currency_code_from']][$rate_data['currency_code_to']] = $rate_data['rate'];
}
return $rates;
}
public function save($currency_code_from, $currency_code_to, $rate) {
$config = $this->configFactory
->getEditable('currency.exchanger.fixed_rates');
$rates = $this
->loadAll();
$rates[$currency_code_from][$currency_code_to] = $rate;
$rates_data = array();
foreach ($rates as $currency_code_from => $currency_code_from_rates) {
foreach ($currency_code_from_rates as $currency_code_to => $rate) {
$rates_data[] = array(
'currency_code_from' => $currency_code_from,
'currency_code_to' => $currency_code_to,
'rate' => $rate,
);
}
}
$config
->set('rates', $rates_data);
$config
->save();
return $this;
}
public function delete($currency_code_from, $currency_code_to) {
$config = $this->configFactory
->getEditable('currency.exchanger.fixed_rates');
$rates = $config
->get('rates');
foreach ($rates as $i => $rate) {
if ($rate['currency_code_from'] == $currency_code_from && $rate['currency_code_to'] == $currency_code_to) {
unset($rates[$i]);
}
}
$config
->set('rates', $rates);
$config
->save();
}
}