Created
February 14, 2018 20:22
-
-
Save aozisik/82807874da879ffca5a5b2e80834abc9 to your computer and use it in GitHub Desktop.
If you are using moneyphp in Laravel, you may find this trait useful for your Eloquent models.
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 App\Concerns; | |
use Money\Money; | |
use Money\Currency; | |
trait HasMoneyFields | |
{ | |
public function getAttributeValue($key) | |
{ | |
if (in_array($key, $this->moneyFields)) { | |
return $this->asMoney($this->getAttributeFromArray($key)); | |
} | |
return parent::getAttributeValue($key); | |
} | |
public function setAttribute($key, $value) | |
{ | |
if (!in_array($key, $this->moneyFields)) { | |
return parent::setAttribute($key, $value); | |
} | |
$this->attributes[$key] = $this->fromMoney($value); | |
return $this; | |
} | |
private function fromMoney($value) | |
{ | |
if ($value instanceof Money) { | |
return intval($value->getAmount()); | |
} | |
return $value; | |
} | |
private function asMoney($value) | |
{ | |
if (is_null($value)) { | |
return null; | |
} | |
if ($value instanceof Money) { | |
return $value; | |
} | |
return new Money($value, new Currency($this->currency ?? 'TRY')); | |
} | |
public function attributesToArray() | |
{ | |
$attributes = parent::attributesToArray(); | |
foreach ($this->moneyFields as $field) { | |
$value = $this->$field; | |
if (!is_null($value)) { | |
$value = [ | |
'amount' => $value->getAmount(), | |
'currency' => $value->getCurrency(), | |
'formatted' => $this->formatMoney($value) | |
]; | |
} | |
$attributes[$field] = $value; | |
} | |
return $attributes; | |
} | |
private function formatMoney($money) | |
{ | |
// This is where you go frorm Money object to "$50" | |
return $money->getCurrency()->getCode() . ' ' . ($money->getAmount() / 100); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment