Created
November 8, 2017 14:23
-
-
Save ianhawes/e34a39ccc41eee6cf53bbc7536ebc670 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 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