3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 namespace Civi\Api4\Generic
;
15 * Container for api results.
17 * The Result object has three functions:
19 * 1. Store the results of the API call (accessible via ArrayAccess).
20 * 2. Store metadata like the Entity & Action names.
21 * - Note: some actions extend the Result object to store extra metadata.
22 * For example, BasicReplaceAction returns ReplaceResult which includes the additional $deleted property to list any items deleted by the operation.
23 * 3. Provide convenience methods like `$result->first()` and `$result->indexBy($field)`.
25 class Result
extends \ArrayObject
{
47 * Return first result.
50 public function first() {
51 foreach ($this as $values) {
61 public function last() {
62 $items = $this->getArrayCopy();
63 return array_pop($items);
70 public function itemAt($index) {
71 $length = $index < 0 ?
0 - $index : $index +
1;
72 if ($length > count($this)) {
75 return array_slice(array_values($this->getArrayCopy()), $index, 1)[0];
79 * Re-index the results array (which by default is non-associative)
81 * Drops any item from the results that does not contain the specified key
85 * @throws \API_Exception
87 public function indexBy($key) {
88 $this->indexedBy
= $key;
91 foreach ($this as $values) {
92 if (isset($values[$key])) {
93 $newResults[$values[$key]] = $values;
97 throw new \
API_Exception("Key $key not found in api results");
99 $this->exchangeArray($newResults);
105 * Returns the number of results
109 public function count() {
110 $count = parent
::count();
111 if ($count == 1 && is_array($this->first()) && array_keys($this->first()) == ['row_count']) {
112 return $this->first()['row_count'];
118 * Reduce each result to one field
123 public function column($name) {
124 return array_column($this->getArrayCopy(), $name, $this->indexedBy
);