-
-
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.
This file contains hidden or 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)); | |
} | |
} |
This file contains hidden or 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; | |
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