3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
14 * @package CiviCRM_Hook
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Utils_Hook_UnitTests
extends CRM_Utils_Hook
{
19 protected $mockObject;
24 protected $adhocHooks;
25 protected $civiModules = NULL;
28 * Call this in CiviUnitTestCase::setUp()
30 public function reset() {
31 $this->mockObject
= NULL;
32 $this->adhocHooks
= [];
36 * Use a unit-testing mock object to handle hook invocations.
38 * e.g. hook_civicrm_foo === $mockObject->foo()
39 * Mocks with a magic `__call()` method are called for every hook invokation.
41 * @param object $mockObject
43 public function setMock($mockObject) {
44 $this->mockObject
= $mockObject;
48 * Register a function to run when invoking a specific hook.
50 * Hook name, e.g civicrm_pre.
51 * @param array $callable
52 * Function to call ie array(class, method).
53 * eg. array($this, mymethod)
55 public function setHook($hook, $callable) {
56 $this->adhocHooks
[$hook] = $callable;
60 * Invoke standard, mock and ad hoc hooks.
62 * @param int $numParams
63 * Number of parameters to pass to the hook.
65 * Parameter to be passed to the hook.
67 * Parameter to be passed to the hook.
69 * Parameter to be passed to the hook.
71 * Parameter to be passed to the hook.
73 * Parameter to be passed to the hook.
75 * Parameter to be passed to the hook.
76 * @param string $fnSuffix
77 * Function suffix, this is effectively the hook name.
81 public function invokeViaUF(
83 &$arg1, &$arg2, &$arg3, &$arg4, &$arg5, &$arg6,
85 $params = array(&$arg1, &$arg2, &$arg3, &$arg4, &$arg5, &$arg6);
87 $fResult1 = $fResult2 = $fResult3 = NULL;
90 if ($this->civiModules
=== NULL) {
91 $this->civiModules
= [];
92 $this->requireCiviModules($this->civiModules
);
94 $fResult1 = $this->runHooks($this->civiModules
, $fnSuffix, $numParams, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
96 // run mock object hooks
97 if ($this->mockObject
&& is_callable([$this->mockObject
, $fnSuffix])) {
98 $fResult2 = call_user_func([$this->mockObject
, $fnSuffix], $arg1, $arg2, $arg3, $arg4, $arg5, $arg6);
102 if (!empty($this->adhocHooks
[$fnSuffix])) {
103 $fResult3 = call_user_func_array($this->adhocHooks
[$fnSuffix], $params);
107 foreach ([$fResult1, $fResult2, $fResult3] as $fResult) {
108 if (!empty($fResult) && is_array($fResult)) {
109 $result = array_merge($result, $fResult);
113 return empty($result) ?
TRUE : $result;