CurrencyLocalize.php in Currency 8.3
File
src/Plugin/Filter/CurrencyLocalize.php
View source
<?php
namespace Drupal\currency\Plugin\Filter;
use Commercie\Currency\InputInterface;
use Drupal\Core\Entity\EntityStorageInterface;
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 CurrencyLocalize extends FilterBase implements ContainerFactoryPluginInterface {
protected $currencyStorage;
protected $currentFilterProcessResult;
protected $input;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, TranslationInterface $string_translation, EntityStorageInterface $currency_storage, InputInterface $input) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currencyStorage = $currency_storage;
$this->input = $input;
$this->stringTranslation = $string_translation;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$entity_type_manager = $container
->get('entity_type.manager');
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('string_translation'), $entity_type_manager
->getStorage('currency'), $container
->get('currency.input'));
}
public function process($text, $langcode) {
$this->currentFilterProcessResult = new FilterProcessResult($text);
$this->currentFilterProcessResult
->setProcessedText(preg_replace_callback('/\\[currency-localize:([a-z]{3}):(.+?)\\]/i', [
$this,
'processCallback',
], $text));
$result = $this->currentFilterProcessResult;
unset($this->currentFilterProcessResult);
return $result;
}
function processCallback(array $matches) {
$currency_code = $matches[1];
$amount = $this->input
->parseAmount($matches[2]);
if (!$amount) {
return $matches[0];
}
$currency = $this->currencyStorage
->load($currency_code);
$this->currentFilterProcessResult
->addCacheableDependency($currency);
if ($currency) {
return $currency
->formatAmount($amount);
}
return $matches[0];
}
public function tips($long = FALSE) {
return $this
->t('Use <code>[currency-localize:<strong>currency-code</strong>:<strong>amount</strong>]</code> to localize an amount of money. The <code>currency-code</code> and <code>amount</code> parameters are the ISO 4217 currency code and the actual amount to display. Example: <code>[currency-localize:EUR:99.95]</code>.');
}
}