From ab2f8a0920840546f18340c08a806e0db526750b Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Fri, 10 Jan 2020 17:06:37 -0500 Subject: [PATCH] Api4 - Convert field values to correct data type --- .../Subscriber/PostSelectQuerySubscriber.php | 46 +++++++++++++++---- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/Civi/Api4/Event/Subscriber/PostSelectQuerySubscriber.php b/Civi/Api4/Event/Subscriber/PostSelectQuerySubscriber.php index e9522b31dce0..ad8c834010f5 100644 --- a/Civi/Api4/Event/Subscriber/PostSelectQuerySubscriber.php +++ b/Civi/Api4/Event/Subscriber/PostSelectQuerySubscriber.php @@ -60,8 +60,7 @@ protected function postRun(array $results, Api4SelectQuery $query) { return $results; } - $fieldSpec = $query->getApiFieldSpec(); - $this->unserializeFields($results, $query->getEntity(), $fieldSpec); + $this->formatFieldValues($results, $query->getApiFieldSpec()); // Group the selects to avoid queries for each field $groupedSelects = $this->getNtoManyJoinSelects($query); @@ -98,26 +97,55 @@ private function formatJoinResults(&$joinResults, $query, $alias) { $fields[array_pop($name)] = $field->toArray(); } if ($fields) { - $this->unserializeFields($joinResults, NULL, $fields); + $this->formatFieldValues($joinResults, $fields); } } /** - * Unserialize values + * Unserialize values and convert to correct type * * @param array $results - * @param string $entity * @param array $fields */ - protected function unserializeFields(&$results, $entity, $fields = []) { + protected function formatFieldValues(&$results, $fields = []) { foreach ($results as &$result) { foreach ($result as $field => &$value) { - if (!empty($fields[$field]['serialize']) && is_string($value)) { - $serializationType = $fields[$field]['serialize']; - $value = \CRM_Core_DAO::unSerializeField($value, $serializationType); + $dataType = $fields[$field]['data_type'] ?? NULL; + if (!empty($fields[$field]['serialize'])) { + if (is_string($value)) { + $value = \CRM_Core_DAO::unSerializeField($value, $fields[$field]['serialize']); + foreach ($value as $key => $val) { + $value[$key] = $this->convertDataType($val, $dataType); + } + } } + else { + $value = $this->convertDataType($value, $dataType); + } + } + } + } + + /** + * @param mixed $value + * @param string $dataType + * @return mixed + */ + protected function convertDataType($value, $dataType) { + if (isset($value)) { + switch ($dataType) { + case 'Boolean': + return (bool) $value; + + case 'Integer': + return (int) $value; + + case 'Money': + case 'Float': + return (float) $value; } } + return $value; } /**