82fd42fe28d04096ad4707d34d22ac7302c10aec
3 namespace Civi\Api4\Generic
;
6 * Base class for all actions that need to fetch records (Get, Update, Delete, etc)
8 * @package Civi\Api4\Generic
10 * @method $this setWhere(array $wheres)
11 * @method array getWhere()
12 * @method $this setOrderBy(array $order)
13 * @method array getOrderBy()
14 * @method $this setLimit(int $limit)
15 * @method int getLimit()
16 * @method $this setOffset(int $offset)
17 * @method int getOffset()
19 abstract class AbstractQueryAction
extends AbstractAction
{
22 * Criteria for selecting items.
24 * $example->addWhere('contact_type', 'IN', array('Individual', 'Household'))
28 protected $where = [];
31 * Array of field(s) to use in ordering the results
35 * $example->addOrderBy('sort_name', 'ASC')
39 protected $orderBy = [];
42 * Maximum number of results to return.
44 * Defaults to unlimited.
46 * Note: the Api Explorer sets this to 25 by default to avoid timeouts.
47 * Change or remove this default for your application code.
54 * Zero-based index of first result to return.
56 * Defaults to "0" - first record.
60 protected $offset = 0;
63 * @param string $field
67 * @throws \API_Exception
69 public function addWhere($field, $op, $value = NULL) {
70 if (!in_array($op, \CRM_Core_DAO
::acceptedSQLOperators())) {
71 throw new \
API_Exception('Unsupported operator');
73 $this->where
[] = [$field, $op, $value];
78 * Adds one or more AND/OR/NOT clause groups
80 * @param string $operator
81 * @param mixed $condition1 ... $conditionN
82 * Either a nested array of arguments, or a variable number of arguments passed to this function.
85 * @throws \API_Exception
87 public function addClause($operator, $condition1) {
88 if (!is_array($condition1[0])) {
89 $condition1 = array_slice(func_get_args(), 1);
91 $this->where
[] = [$operator, $condition1];
96 * @param string $field
97 * @param string $direction
100 public function addOrderBy($field, $direction = 'ASC') {
101 $this->orderBy
[$field] = $direction;
106 * A human-readable where clause, for the reading enjoyment of you humans.
108 * @param array $whereClause
112 protected function whereClauseToString($whereClause = NULL, $op = 'AND') {
113 if ($whereClause === NULL) {
114 $whereClause = $this->where
;
117 if (!is_array($whereClause) ||
!$whereClause) {
120 if (in_array($whereClause[0], ['AND', 'OR', 'NOT'])) {
121 $op = array_shift($whereClause);
126 return $output . '(' . $this->whereClauseToString($whereClause, $op) . ')';
128 elseif (isset($whereClause[1]) && in_array($whereClause[1], \CRM_Core_DAO
::acceptedSQLOperators())) {
129 $output = $whereClause[0] . ' ' . $whereClause[1] . ' ';
130 if (isset($whereClause[2])) {
131 $output .= is_array($whereClause[2]) ?
'[' . implode(', ', $whereClause[2]) . ']' : $whereClause[2];
136 foreach (array_filter($whereClause) as $clause) {
137 $clauses[] = $this->whereClauseToString($clause, $op);
139 $output = implode(" $op ", $clauses);