From d2c6d5a5714f18433feb0289e6bce5ca7e4cc069 Mon Sep 17 00:00:00 2001 From: Alex Tselegidis Date: Mon, 26 Dec 2022 10:22:22 +0100 Subject: [PATCH] Add helper method for optional fields --- application/core/EA_Model.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/application/core/EA_Model.php b/application/core/EA_Model.php index 5280516c..73583186 100644 --- a/application/core/EA_Model.php +++ b/application/core/EA_Model.php @@ -187,6 +187,31 @@ class EA_Model extends CI_Model { } } + /** + * Ensure a field exists in an array by using its value or NULL. + * + * @param array $record Record data (single or multiple records). + * @param array $fields Requested field names. + */ + public function optional(array &$record, array $fields) + { + $sanitize = function ($field) use (&$record) { + return $record[$field] ?? NULL; + }; + + if (is_assoc($record)) + { + $record = array_map($sanitize, $fields); + } + else + { + foreach ($record as &$record_item) + { + $record_item = array_map($sanitize, $fields); + } + } + } + /** * Get the DB field name based on an API field name. *