Skip to content

Instantly share code, notes, and snippets.

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