/** * @covers ::process * @covers ::processCallback */ public function testProcess() { $cache_contexts = Cache::mergeContexts(['baz', 'qux']); $cache_tags = Cache::mergeTags(['foo', 'bar']); $currency_code_from = 'EUR'; $currency_code_to = 'NLG'; $rate = '2.20371'; $exchange_rate_provider_id = 'foo_bar'; $exchange_rate = new ExchangeRate($currency_code_from, $currency_code_to, $rate, $exchange_rate_provider_id); $exchange_rate->addCacheContexts($cache_contexts); $exchange_rate->addCacheTags($cache_tags); $this->input->expects($this->any())->method('parseAmount')->will($this->returnArgument(0)); $this->exchangeRateProvider->expects($this->any())->method('load')->with($currency_code_from, $currency_code_to)->willReturn($exchange_rate); $langcode = $this->randomMachineName(2); $tokens_valid = ['[currency:EUR:NLG]' => '2.20371', '[currency:EUR:NLG:1]' => '2.20371', '[currency:EUR:NLG:2]' => '4.40742']; $tokens_invalid = ['[currency]', '[currency:]', '[currency::]', '[currency:EUR]', '[currency:EUR:123]', '[currency:123:EUR]', '[currency:123]']; foreach ($tokens_valid as $token => $replacement) { $result = $this->sut->process($token, $langcode); $this->assertInstanceOf(FilterProcessResult::class, $result); $this->assertSame($replacement, $result->getProcessedText()); $this->assertSame($cache_contexts, $result->getCacheContexts()); $this->assertSame($cache_tags, $result->getCacheTags()); } foreach ($tokens_invalid as $token) { $result = $this->sut->process($token, $langcode); $this->assertInstanceOf(FilterProcessResult::class, $result); $this->assertSame($token, $result->getProcessedText()); $this->assertEmpty($result->getCacheContexts()); $this->assertEmpty($result->getCacheTags()); } }
/** * Implements preg_replace_callback() callback. * * @see self::process() */ 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); // The amount is invalid, so return the token. 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); } // No exchange rate could be loaded, so return the token. return $matches[0]; }