avoid crash with one column and blank lines
[civicrm-core.git] / Civi / Api4 / Query / SqlFunctionGROUP_CONCAT.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 namespace Civi\Api4\Query;
13
14 /**
15 * Sql function
16 */
17 class SqlFunctionGROUP_CONCAT extends SqlFunction {
18
19 public $supportsExpansion = TRUE;
20
21 protected static $category = self::CATEGORY_AGGREGATE;
22
23 protected static function params(): array {
24 return [
25 [
26 'flag_before' => ['DISTINCT' => ts('Distinct')],
27 'max_expr' => 1,
28 'must_be' => ['SqlField', 'SqlFunction'],
29 'optional' => FALSE,
30 ],
31 [
32 'prefix' => 'ORDER BY',
33 'max_expr' => 1,
34 'flag_after' => ['ASC' => ts('Ascending'), 'DESC' => ts('Descending')],
35 'must_be' => ['SqlField'],
36 'optional' => TRUE,
37 ],
38 [
39 'prefix' => 'SEPARATOR',
40 'max_expr' => 1,
41 'must_be' => ['SqlString'],
42 'optional' => TRUE,
43 // @see self::formatOutput()
44 'api_default' => [
45 'expr' => ['"' . \CRM_Core_DAO::VALUE_SEPARATOR . '"'],
46 ],
47 ],
48 ];
49 }
50
51 /**
52 * Reformat result as array if using default separator
53 *
54 * @see \Civi\Api4\Utils\FormattingUtil::formatOutputValues
55 * @param string $value
56 * @param string $dataType
57 * @return string|array
58 */
59 public function formatOutputValue($value, &$dataType) {
60 $exprArgs = $this->getArgs();
61 // By default, values are split into an array and formatted according to the field's dataType
62 if (isset($exprArgs[2]['expr'][0]->expr) && $exprArgs[2]['expr'][0]->expr === \CRM_Core_DAO::VALUE_SEPARATOR) {
63 $value = explode(\CRM_Core_DAO::VALUE_SEPARATOR, $value);
64 // If the first expression is another sqlFunction, allow it to control the dataType
65 if ($exprArgs[0]['expr'][0] instanceof SqlFunction) {
66 $exprArgs[0]['expr'][0]->formatOutputValue(NULL, $dataType);
67 }
68 }
69 // If using custom separator, preserve raw string
70 else {
71 $dataType = 'String';
72 }
73 return $value;
74 }
75
76 /**
77 * @return string
78 */
79 public static function getTitle(): string {
80 return ts('List');
81 }
82
83 }