Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinandersen3d/665e6eca5876ac92e2bfcfaeda028b29 to your computer and use it in GitHub Desktop.
Save martinandersen3d/665e6eca5876ac92e2bfcfaeda028b29 to your computer and use it in GitHub Desktop.
A trait for converting numbers to and from integers/floats for display and storage.
<?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));
}
}
<?php
namespace App;
use App\Traits\ConvertsNumbers;
class MyClassName {
use ConvertsNumbers;
protected $convertable = [
'one_attribute',
'another_attribute',
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment