CurrencyExchange.php in Currency 8.3
File
src/Plugin/Filter/CurrencyExchange.php
View source
<?php
namespace Drupal\currency\Plugin\Filter;
use Commercie\Currency\InputInterface;
use Commercie\CurrencyExchange\ExchangeRateProviderInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CurrencyExchange extends FilterBase implements ContainerFactoryPluginInterface {
protected $currentFilterProcessResult;
protected $exchangeRateProvider;
protected $input;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, TranslationInterface $string_translation, ExchangeRateProviderInterface $exchange_rate_provider, InputInterface $input) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->exchangeRateProvider = $exchange_rate_provider;
$this->input = $input;
$this->stringTranslation = $string_translation;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('string_translation'), $container
->get('currency.exchange_rate_provider'), $container
->get('currency.input'));
}
public function process($text, $langcode) {
$this->currentFilterProcessResult = new FilterProcessResult($text);
$this->currentFilterProcessResult
->setProcessedText(preg_replace_callback('/\\[currency:([a-z]{3}):([a-z]{3})(.*?)\\]/i', [
$this,
'processCallback',
], $text));
$result = $this->currentFilterProcessResult;
unset($this->currentFilterProcessResult);
return $result;
}
function processCallback(array $matches) {
$currency_code_from = $matches[1];
$currency_code_to = $matches[2];
$amount = str_replace(':', '', $matches[3]);
if (strlen($amount) !== 0) {
$amount = $this->input
->parseAmount($amount);
if (!$amount) {
return $matches[0];
}
}
else {
$amount = 1;
}
$exchange_rate = $this->exchangeRateProvider
->load($currency_code_from, $currency_code_to);
$this->currentFilterProcessResult
->addCacheableDependency($exchange_rate);
if ($exchange_rate) {
return bcmul($amount, $exchange_rate
->getRate(), 6);
}
return $matches[0];
}
public function tips($long = FALSE) {
return $this
->t('Use <code>[currency:from:to:amount]</code> to convert an amount of money from one currency to another. The <code>amount</code> parameter is optional and defaults to <code>1</code>. Example: <code>[currency:EUR:USD:100]</code>.');
}
}