Add sql QUARTER function
authorAndrew West <me@awest.uk>
Thu, 13 Apr 2023 18:41:26 +0000 (19:41 +0100)
committerAndrew West <me@awest.uk>
Thu, 13 Apr 2023 18:41:26 +0000 (19:41 +0100)
Civi/Api4/Query/SqlFunctionQUARTER.php [new file with mode: 0644]
tests/phpunit/api/v4/Action/SqlFunctionTest.php

diff --git a/Civi/Api4/Query/SqlFunctionQUARTER.php b/Civi/Api4/Query/SqlFunctionQUARTER.php
new file mode 100644 (file)
index 0000000..8977e39
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+/*
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC. All rights reserved.                        |
+ |                                                                    |
+ | This work is published under the GNU AGPLv3 license with some      |
+ | permitted exceptions and without any warranty. For full license    |
+ | and copyright information, see https://civicrm.org/licensing       |
+ +--------------------------------------------------------------------+
+ */
+
+namespace Civi\Api4\Query;
+
+/**
+ * Sql function
+ */
+class SqlFunctionQUARTER extends SqlFunction {
+
+  protected static $category = self::CATEGORY_DATE;
+
+  protected static $dataType = 'Integer';
+
+  protected static function params(): array {
+    return [
+      [
+        'max_expr' => 1,
+        'optional' => FALSE,
+      ],
+    ];
+  }
+
+  /**
+   * @return string
+   */
+  public static function getTitle(): string {
+    return ts('Quarter only');
+  }
+
+  /**
+   * @return string
+   */
+  public static function getDescription(): string {
+    return ts('The numeric quarter (1-4) of a date.');
+  }
+
+}
index 3304c92639f5a050701b7cfcade45bdf9ef5b26f..ec13dcaaffc0f6f9d626c39ffc00813d5af99bd1 100644 (file)
@@ -231,6 +231,7 @@ class SqlFunctionTest extends Api4TestBase implements TransactionalInterface {
     $result = Contact::get(FALSE)
       ->addSelect('DATEDIFF("2010-01-01", birth_date) AS diff')
       ->addSelect('YEAR(birth_date) AS year')
+      ->addSelect('QUARTER(birth_date) AS quarter')
       ->addSelect('MONTH(birth_date) AS month')
       ->addSelect('EXTRACT(YEAR_MONTH FROM birth_date) AS year_month')
       ->addWhere('last_name', '=', $lastName)
@@ -239,11 +240,13 @@ class SqlFunctionTest extends Api4TestBase implements TransactionalInterface {
 
     $this->assertEquals(51, $result[0]['diff']);
     $this->assertEquals(2009, $result[0]['year']);
+    $this->assertEquals(4, $result[0]['quarter']);
     $this->assertEquals(11, $result[0]['month']);
     $this->assertEquals('200911', $result[0]['year_month']);
 
     $this->assertEquals(0, $result[1]['diff']);
     $this->assertEquals(2010, $result[1]['year']);
+    $this->assertEquals(1, $result[1]['quarter']);
     $this->assertEquals(1, $result[1]['month']);
     $this->assertEquals('201001', $result[1]['year_month']);
   }