Skip to content

Instantly share code, notes, and snippets.

@frederikbosch
Last active February 7, 2016 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frederikbosch/639490d541069605d4e8 to your computer and use it in GitHub Desktop.
Save frederikbosch/639490d541069605d4e8 to your computer and use it in GitHub Desktop.
<?php
namespace Omnipay\Common;
class Money {
private $value;
private $currencyCode;
private function __construct ($value, $currencyCode) {
$this->value = $value;
$this->currencyCode = $currencyCode;
}
public function isCurrencyAvailableWithin(array $currencies) {
return in_array($this->currencyCode, $currencies);
}
public function toInteger() {
return $this->value;
}
public function toDecimalString() {
return substr($value, 0, -2) . '.' . substr($value, -2);
}
public function toFloat() {
return (float) $this->toDecimalString();
}
public static function fromInteger($amount, $currencyCode) {
if (filter_var($amount, FILTER_VALIDATE_INT) === false) {
throw new InvalidRequestException('Amount must be a valid integer');
}
return new self($amount, $currencyCode);
}
public static function fromFloat($amount, $currencyCode) {
if (is_float($amount) === false) {
throw new InvalidRequestException('Amount must be a floating point');
}
return new self(str_replace('.', '', sprintf('%.8g', $amount)), $currencyCode);
}
public static function fromDecimalString($amount, $currencyCode) {
if (is_string($amount) === false || strpos($amount, '.') === false || filter_var(str_replace('.', '', $amount), FILTER_VALIDATE_INT) === false) {
throw new InvalidRequestException('Amount must be a floating point');
}
return new self(str_replace('.', '', sprintf('%.8g', $amount)), $currencyCode);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment