Api4 Explorer - enable debug by default
[civicrm-core.git] / Civi / Api4 / Generic / Result.php
CommitLineData
19b53e5b
C
1<?php
2/*
3 +--------------------------------------------------------------------+
41498ac5 4 | Copyright CiviCRM LLC. All rights reserved. |
19b53e5b 5 | |
41498ac5
TO
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 |
19b53e5b
C
9 +--------------------------------------------------------------------+
10 */
11
12namespace Civi\Api4\Generic;
13
14/**
15 * Container for api results.
16 */
17class Result extends \ArrayObject {
18 /**
19 * @var string
20 */
21 public $entity;
22 /**
23 * @var string
24 */
25 public $action;
b65fa6dc
CW
26 /**
27 * @var array
28 */
29 public $debug;
19b53e5b
C
30 /**
31 * Api version
32 * @var int
33 */
34 public $version = 4;
35
36 private $indexedBy;
37
38 /**
39 * Return first result.
40 * @return array|null
41 */
42 public function first() {
43 foreach ($this as $values) {
44 return $values;
45 }
46 return NULL;
47 }
48
49 /**
50 * Return last result.
51 * @return array|null
52 */
53 public function last() {
54 $items = $this->getArrayCopy();
55 return array_pop($items);
56 }
57
58 /**
59 * @param int $index
60 * @return array|null
61 */
62 public function itemAt($index) {
63 $length = $index < 0 ? 0 - $index : $index + 1;
64 if ($length > count($this)) {
65 return NULL;
66 }
67 return array_slice(array_values($this->getArrayCopy()), $index, 1)[0];
68 }
69
70 /**
71 * Re-index the results array (which by default is non-associative)
72 *
73 * Drops any item from the results that does not contain the specified key
74 *
75 * @param string $key
76 * @return $this
77 * @throws \API_Exception
78 */
79 public function indexBy($key) {
80 $this->indexedBy = $key;
81 if (count($this)) {
82 $newResults = [];
83 foreach ($this as $values) {
84 if (isset($values[$key])) {
85 $newResults[$values[$key]] = $values;
86 }
87 }
88 if (!$newResults) {
89 throw new \API_Exception("Key $key not found in api results");
90 }
91 $this->exchangeArray($newResults);
92 }
93 return $this;
94 }
95
96 /**
97 * Returns the number of results
98 *
99 * @return int
100 */
101 public function count() {
102 $count = parent::count();
103 if ($count == 1 && is_array($this->first()) && array_keys($this->first()) == ['row_count']) {
104 return $this->first()['row_count'];
105 }
106 return $count;
107 }
108
109 /**
110 * Reduce each result to one field
111 *
112 * @param $name
113 * @return array
114 */
115 public function column($name) {
116 return array_column($this->getArrayCopy(), $name, $this->indexedBy);
117 }
118
119}