From dd546164fb5b319ec43daf046ade98555cf73efd Mon Sep 17 00:00:00 2001 From: Alex Tselegidis Date: Fri, 29 Oct 2021 12:39:49 +0200 Subject: [PATCH] Common type casting functionality --- application/core/EA_Model.php | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/application/core/EA_Model.php b/application/core/EA_Model.php index 9bc1745b..386115c2 100644 --- a/application/core/EA_Model.php +++ b/application/core/EA_Model.php @@ -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); + } + } + } }