Merge pull request #16899 from mlutfy/mailingReportView
[civicrm-core.git] / tests / phpunit / api / v4 / Query / SqlExpressionParserTest.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 * $Id$
18 *
19 */
20
21
22 namespace api\v4\Query;
23
24 use api\v4\UnitTestCase;
25 use Civi\Api4\Query\SqlExpression;
26
27 /**
28 * @group headless
29 */
30 class SqlExpressionParserTest extends UnitTestCase {
31
32 public function aggregateFunctions() {
33 return [
34 ['AVG'],
35 ['COUNT'],
36 ['MAX'],
37 ['MIN'],
38 ['SUM'],
39 ];
40 }
41
42 /**
43 * @param string|\Civi\Api4\Query\SqlFunction $fnName
44 * @dataProvider aggregateFunctions
45 */
46 public function testAggregateFuncitons($fnName) {
47 $className = 'Civi\Api4\Query\SqlFunction' . $fnName;
48 $params = $className::getParams();
49 $this->assertNotEmpty($params[0]['prefix']);
50 $this->assertEmpty($params[0]['suffix']);
51
52 $sqlFn = new $className('total');
53 $this->assertEquals($fnName, $sqlFn->getName());
54 $this->assertEquals(['total'], $sqlFn->getFields());
55 $this->assertCount(1, $this->getArgs($sqlFn));
56
57 $sqlFn = SqlExpression::convert($fnName . '(DISTINCT stuff)');
58 $this->assertEquals($fnName, $sqlFn->getName());
59 $this->assertEquals("Civi\Api4\Query\SqlFunction$fnName", get_class($sqlFn));
60 $this->assertEquals($params, $sqlFn->getParams());
61 $this->assertEquals(['stuff'], $sqlFn->getFields());
62 $this->assertCount(2, $this->getArgs($sqlFn));
63
64 try {
65 $sqlFn = SqlExpression::convert($fnName . '(*)');
66 if ($fnName === 'COUNT') {
67 $this->assertTrue(is_a($this->getArgs($sqlFn)[0], 'Civi\Api4\Query\SqlWild'));
68 }
69 else {
70 $this->fail('SqlWild should only be allowed in COUNT.');
71 }
72 }
73 catch (\API_Exception $e) {
74 $this->assertContains('Illegal', $e->getMessage());
75 }
76 }
77
78 /**
79 * @param \Civi\Api4\Query\SqlFunction $fn
80 * @return array
81 * @throws \ReflectionException
82 */
83 private function getArgs($fn) {
84 $ref = new \ReflectionClass($fn);
85 $args = $ref->getProperty('args');
86 $args->setAccessible(TRUE);
87 return $args->getValue($fn);
88 }
89
90 }