Last active
February 7, 2016 20:18
-
-
Save frederikbosch/639490d541069605d4e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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