Resolve dev/core#2768 Reinstate code into APIv4 that handled magic functions
authorSeamus Lee <seamuslee001@gmail.com>
Tue, 24 Aug 2021 00:12:12 +0000 (10:12 +1000)
committerSeamus Lee <seamuslee001@gmail.com>
Tue, 24 Aug 2021 01:01:29 +0000 (11:01 +1000)
Add in test to assert Exception type and exception message that is thrown

Civi/Api4/Generic/AbstractAction.php
tests/phpunit/api/v4/Action/AbstractActionFunctionTest.php [new file with mode: 0644]

index cd6283c8fa4987fb796f1032c800e8e952198d34..fcc6001ab750a3d3a66afb6bd40a278aafb46775 100644 (file)
@@ -191,6 +191,33 @@ abstract class AbstractAction implements \ArrayAccess {
     return $this;
   }
 
+  /**
+   * Magic function to provide automatic getter/setter for params.
+   *
+   * @param $name
+   * @param $arguments
+   * @return static|mixed
+   * @throws \API_Exception
+   */
+  public function __call($name, $arguments) {
+    $param = lcfirst(substr($name, 3));
+    if (!$param || $param[0] == '_') {
+      throw new \API_Exception('Unknown api parameter: ' . $name);
+    }
+    $mode = substr($name, 0, 3);
+    if ($this->paramExists($param)) {
+      switch ($mode) {
+        case 'get':
+          return $this->$param;
+
+        case 'set':
+          $this->$param = $arguments[0];
+          return $this;
+      }
+    }
+    throw new \API_Exception('Unknown api parameter: ' . $name);
+  }
+
   /**
    * Invoke api call.
    *
diff --git a/tests/phpunit/api/v4/Action/AbstractActionFunctionTest.php b/tests/phpunit/api/v4/Action/AbstractActionFunctionTest.php
new file mode 100644 (file)
index 0000000..3eaae01
--- /dev/null
@@ -0,0 +1,34 @@
+<?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       |
+ +--------------------------------------------------------------------+
+ */
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC https://civicrm.org/licensing
+ */
+
+namespace api\v4\Action;
+
+use api\v4\UnitTestCase;
+
+/**
+ * @group headless
+ */
+class AbstractActionFunctionTest extends UnitTestCase {
+
+  public function testUndefinedParamException(): void {
+    $this->expectException('API_Exception');
+    $this->expectExceptionMessage('Unknown api parameter: getLanguage');
+    \Civi\Api4\System::flush(FALSE)->getLanguage();
+  }
+
+}