From 4a7dc83a548f738d97264e1870a1ccacfd8a3601 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Wed, 8 Jan 2020 22:13:57 -0500 Subject: [PATCH] civicrm_api4 - Extend functionality of index param Passing an array allows you to return a single result column, with automatic handling of the select clause. --- api/api.php | 18 +++++++++++++++++- tests/phpunit/api/v4/Action/IndexTest.php | 10 ++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/api/api.php b/api/api.php index 307ea930bb..b1da77ed72 100644 --- a/api/api.php +++ b/api/api.php @@ -29,9 +29,10 @@ function civicrm_api(string $entity = NULL, string $action, array $params, $extr * @param string $entity * @param string $action * @param array $params - * @param string|int $index + * @param string|int|array $index * If $index is a string, the results array will be indexed by that key. * If $index is an integer, only the result at that index will be returned. + * $index can also be a single-item array representing key|value pairs to be returned ex ['id' => 'title']. * * @return \Civi\Api4\Generic\Result * @throws \API_Exception @@ -51,6 +52,18 @@ function civicrm_api4(string $entity, string $action, array $params = [], $index $setter = 'set' . ucfirst($name); $apiCall->$setter($param); } + + if ($index && is_array($index)) { + $indexCol = reset($index); + $indexField = key($index); + if (property_exists($apiCall, 'select')) { + $apiCall->setSelect([$indexCol]); + if ($indexField && $indexField != $indexCol) { + $apiCall->addSelect($indexField); + } + } + } + $result = $apiCall->execute(); // Index results by key @@ -74,6 +87,9 @@ function civicrm_api4(string $entity, string $action, array $params = [], $index } $result->exchangeArray($item); } + if (!empty($indexCol)) { + $result->exchangeArray($result->column($indexCol)); + } return $result; } diff --git a/tests/phpunit/api/v4/Action/IndexTest.php b/tests/phpunit/api/v4/Action/IndexTest.php index be72582d85..bd8bed5f3b 100644 --- a/tests/phpunit/api/v4/Action/IndexTest.php +++ b/tests/phpunit/api/v4/Action/IndexTest.php @@ -69,4 +69,14 @@ class IndexTest extends UnitTestCase { $this->assertEquals(['subject' => ['title' => 'Subject']], (array) $result); } + public function testArrayIndex() { + // Non-associative + $result = civicrm_api4('Activity', 'getFields', ['where' => [['name', '=', 'subject']]], ['name' => 'title']); + $this->assertEquals(['subject' => 'Subject'], (array) $result); + + // Associative + $result = civicrm_api4('Activity', 'getFields', ['where' => [['name', '=', 'subject']]], ['title']); + $this->assertEquals(['Subject'], (array) $result); + } + } -- 2.25.1