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
implements \JsonSerializable
{
51 * Return first result.
54 public function first() {
55 foreach ($this as $values) {
65 public function last() {
66 $items = $this->getArrayCopy();
67 return array_pop($items);
74 public function itemAt($index) {
75 $length = $index < 0 ?
0 - $index : $index +
1;
76 if ($length > count($this)) {
79 return array_slice(array_values($this->getArrayCopy()), $index, 1)[0];
83 * Re-index the results array (which by default is non-associative)
85 * Drops any item from the results that does not contain the specified key
89 * @throws \API_Exception
91 public function indexBy($key) {
92 $this->indexedBy
= $key;
95 foreach ($this as $values) {
96 if (isset($values[$key])) {
97 $newResults[$values[$key]] = $values;
101 throw new \
API_Exception("Key $key not found in api results");
103 $this->exchangeArray($newResults);
109 * Returns the number of results
113 public function count() {
114 return $this->rowCount ?? parent
::count();
118 * Reduce each result to one field
123 public function column($name) {
124 return array_column($this->getArrayCopy(), $name, $this->indexedBy
);
130 public function jsonSerialize() {
131 return $this->getArrayCopy();