Common type casting functionality

This commit is contained in:
Alex Tselegidis 2021-10-29 12:39:49 +02:00
parent b7305be038
commit dd546164fb
1 changed files with 38 additions and 0 deletions

View File

@ -61,6 +61,11 @@
* @property Timezones $timezones
*/
class EA_Model extends CI_Model {
/**
* @var array
*/
protected $casts = [];
/**
* EA_Model constructor.
*/
@ -130,4 +135,37 @@ class EA_Model extends CI_Model {
{
return $this->save($record);
}
public function cast(array &$record)
{
foreach ($this->casts as $attribute => $cast)
{
if ( ! isset($record[$attribute]))
{
continue;
}
switch ($cast)
{
case 'integer':
$record[$attribute] = (int)$record[$attribute];
break;
case 'float':
$record[$attribute] = (float)$record[$attribute];
break;
case 'boolean':
$record[$attribute] = (bool)$record[$attribute];
break;
case 'string':
$record[$attribute] = (string)$record[$attribute];
break;
default:
throw new RuntimeException('Unsupported cast type provided: ' . $cast);
}
}
}
}