Skip to content

Instantly share code, notes, and snippets.

@joomdonation
Last active June 4, 2018 08:30
Show Gist options
  • Save joomdonation/f570281566f1a81879f9002b69afefeb to your computer and use it in GitHub Desktop.
Save joomdonation/f570281566f1a81879f9002b69afefeb to your computer and use it in GitHub Desktop.
<?php
class EventbookingHelper
{
/**
* Convert payment amount to USD currency in case the currency is not supported by the payment gateway
*
* @param $amount
* @param $currency
*
* @return float
*/
public static function convertAmountToUSD($amount, $currency)
{
if (EventbookingHelper::isMethodOverridden('EventbookingHelperOverrideHelper', 'convertAmountToUSD'))
{
return EventbookingHelperOverrideHelper::convertAmountToUSD($amount, $currency);
}
$url = sprintf('https://www.google.com/search?q=1+%s+to+%s', 'USD', $currency);
$headers = [
'Accept' => 'text/html',
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
];
$http = JHttpFactory::getHttp();
$response = $http->get($url, $headers);
if (302 == $response->code && isset($response->headers['Location']))
{
$response = $http->get($response->headers['Location'], $headers);
}
$body = $response->body;
try
{
$rate = static::buildExchangeRate($body);
if ($rate > 0)
{
$amount = $amount / $rate;
}
}
catch (Exception $e)
{
}
return round($amount, 2);
}
/**
* Builds an exchange rate from the response content.
*
* @param string $content
*
* @return float
*
* @throws \Exception
*/
protected static function buildExchangeRate($content)
{
$document = new \DOMDocument();
if (false === @$document->loadHTML('<?xml encoding="utf-8" ?>' . $content))
{
throw new Exception('The page content is not loadable');
}
$xpath = new \DOMXPath($document);
$nodes = $xpath->query('//span[@id="knowledge-currency__tgt-amount"]');
if (1 !== $nodes->length)
{
$nodes = $xpath->query('//div[@class="vk_ans vk_bk" or @class="dDoNo vk_bk"]');
}
if (1 !== $nodes->length)
{
throw new Exception('The currency is not supported or Google changed the response format');
}
$nodeContent = $nodes->item(0)->textContent;
// Beware of "3 417.36111 Colombian pesos", with a non breaking space
$bid = strtr($nodeContent, ["\xc2\xa0" => '']);
if (false !== strpos($bid, ' '))
{
$bid = strstr($bid, ' ', true);
}
// Does it have thousands separator?
if (strpos($bid, ',') && strpos($bid, '.'))
{
$bid = str_replace(',', '', $bid);
}
if (!is_numeric($bid))
{
throw new Exception('The currency is not supported or Google changed the response format');
}
return $bid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment