Skip to content

Instantly share code, notes, and snippets.

@ianhawes
Created November 8, 2017 14:23
Show Gist options
  • Save ianhawes/e34a39ccc41eee6cf53bbc7536ebc670 to your computer and use it in GitHub Desktop.
Save ianhawes/e34a39ccc41eee6cf53bbc7536ebc670 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
trait ConvertsNumbers
{
public function isConvertable($key)
{
if (!isset($this->convertable)) {
return false;
}
return in_array($key, $this->convertable);
}
public function convertToInt($value)
{
return round($value, 2) * 100;
}
public function convertToFloat($value)
{
return number_format($value/100, 2, '.', '');
}
public function setAttribute($key, $value)
{
if (!$this->isConvertable($key)) {
return parent::setAttribute($key, $value);
}
return parent::setAttribute($key, $this->convertToInt($value));
}
public function getAttribute($key)
{
if (!$this->isConvertable($key)) {
return parent::getAttribute($key);
}
return $this->convertToFloat(parent::getAttribute($key));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment