CRM-15855 - Allow mailings to be saved (but not sent) without name+subject.
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
index ffa3495f8e24a93d50f1ab40a509e9e0c31b66ee..0fdbf562baf07545b4b72555143f13d2a47d3d85 100755 (executable)
@@ -135,6 +135,23 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    */
   private $tx = NULL;
 
+  /**
+   * @var CRM_Utils_Hook_UnitTests hookClass
+   * example of setting a method for a hook
+   * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
+   */
+  public $hookClass = NULL;
+
+  /**
+   * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
+   */
+  protected $_params = array();
+
+  /**
+   * @var CRM_Extension_System
+   */
+  protected $origExtensionSystem;
+
   /**
    *  Constructor
    *
@@ -145,9 +162,9 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *  ReflectionClass of the Test class and checks the constructor
    *  of that class to decide how to set up the test.
    *
-   * @param  string $name
-   * @param  array  $data
-   * @param  string $dataName
+   * @param string $name
+   * @param array $data
+   * @param string $dataName
    */
   public function __construct($name = NULL, array$data = array(), $dataName = '') {
     parent::__construct($name, $data, $dataName);
@@ -172,15 +189,24 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     // also load the class loader
     require_once 'CRM/Core/ClassLoader.php';
     CRM_Core_ClassLoader::singleton()->register();
-    if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
+    if (function_exists('_civix_phpunit_setUp')) {
+      // FIXME: loosen coupling
       _civix_phpunit_setUp();
     }
   }
 
+  /**
+   * Override to run the test and assert its state.
+   * @return mixed
+   * @throws \Exception
+   * @throws \PHPUnit_Framework_IncompleteTest
+   * @throws \PHPUnit_Framework_SkippedTest
+   */
   protected function runTest() {
     try {
       return parent::runTest();
-    } catch (PEAR_Exception $e) {
+    }
+    catch (PEAR_Exception $e) {
       // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
       throw new Exception(\CRM_Core_Error::formatTextException($e), $e->getCode());
     }
@@ -232,7 +258,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * @param bool $perClass
    * @param null $object
-   * @return bool TRUE if the populate logic runs; FALSE if it is skipped
+   * @return bool
+   *   TRUE if the populate logic runs; FALSE if it is skipped
    */
   protected static function _populateDB($perClass = FALSE, &$object = NULL) {
 
@@ -330,7 +357,12 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
 
     CRM_Core_BAO_ConfigSetting::setEnabledComponents(array(
-      'CiviEvent', 'CiviContribute', 'CiviMember', 'CiviMail', 'CiviReport', 'CiviPledge'
+      'CiviEvent',
+      'CiviContribute',
+      'CiviMember',
+      'CiviMail',
+      'CiviReport',
+      'CiviPledge',
     ));
 
     return TRUE;
@@ -353,7 +385,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $session = CRM_Core_Session::singleton();
     $session->set('userID', NULL);
 
-    CRM_Utils_Hook::singleton(TRUE);
     $this->errorScope = CRM_Core_TemporaryErrorScope::useException(); // REVERT
     //  Use a temporary file for STDIN
     $GLOBALS['stdin'] = tmpfile();
@@ -377,7 +408,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
     // when running unit tests, use mockup user framework
     $config->setUserFramework('UnitTests');
-
+    $this->hookClass = CRM_Utils_Hook::singleton(TRUE);
     // also fix the fatal error handler to throw exceptions,
     // rather than exit
     $config->fatalErrorHandler = 'CiviUnitTestCase_fatalErrorHandler';
@@ -474,6 +505,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    */
   protected function tearDown() {
     error_reporting(E_ALL & ~E_NOTICE);
+    CRM_Utils_Hook::singleton()->reset();
+    $this->hookClass->reset();
     $session = CRM_Core_Session::singleton();
     $session->set('userID', NULL);
 
@@ -483,7 +516,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
       CRM_Core_Transaction::forceRollbackIfEnabled();
       \Civi\Core\Transaction\Manager::singleton(TRUE);
-    } else {
+    }
+    else {
       CRM_Core_Transaction::forceRollbackIfEnabled();
       \Civi\Core\Transaction\Manager::singleton(TRUE);
 
@@ -529,6 +563,11 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @match    array    Associative array of field name => expected value. Empty if asserting
    *                      that a DELETE occurred
    * @delete   boolean  True if we're checking that a DELETE action occurred.
+   * @param $daoName
+   * @param $id
+   * @param $match
+   * @param bool $delete
+   * @throws \PHPUnit_Framework_AssertionFailedError
    */
   public function assertDBState($daoName, $id, $match, $delete = FALSE) {
     if (empty($id)) {
@@ -551,7 +590,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
     // Otherwise check matches of DAO field values against expected values in $match.
     if ($object->find(TRUE)) {
-      $fields = & $object->fields();
+      $fields = &$object->fields();
       foreach ($fields as $name => $value) {
         $dbName = $value['name'];
         if (isset($match[$name])) {
@@ -574,8 +613,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     }
   }
 
-  // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
   /**
+   * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
    * @param string $daoName
    * @param $searchValue
    * @param $returnColumn
@@ -595,8 +634,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     return $value;
   }
 
-  // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
   /**
+   * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
    * @param string $daoName
    * @param $searchValue
    * @param $returnColumn
@@ -608,8 +647,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $this->assertNull($value, $message);
   }
 
-  // Request a record from the DB by id. Success if row not found.
   /**
+   * Request a record from the DB by id. Success if row not found.
    * @param string $daoName
    * @param int $id
    * @param null $message
@@ -620,8 +659,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $this->assertNull($value, $message);
   }
 
-  // Request a record from the DB by id. Success if row not found.
   /**
+   * Request a record from the DB by id. Success if row not found.
    * @param string $daoName
    * @param int $id
    * @param null $message
@@ -632,8 +671,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $this->assertEquals($id, $value, $message);
   }
 
-  // Compare a single column value in a retrieved DB record to an expected value
   /**
+   * Compare a single column value in a retrieved DB record to an expected value
    * @param string $daoName
    * @param $searchValue
    * @param $returnColumn
@@ -641,15 +680,16 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @param $expectedValue
    * @param $message
    */
-  function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
-                                $expectedValue, $message
+  public function assertDBCompareValue(
+    $daoName, $searchValue, $returnColumn, $searchColumn,
+    $expectedValue, $message
   ) {
     $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
     $this->assertEquals($value, $expectedValue, $message);
   }
 
-  // Compare all values in a single retrieved DB record to an array of expected values
   /**
+   * Compare all values in a single retrieved DB record to an array of expected values
    * @param string $daoName
    * @param array $searchParams
    * @param $expectedValues
@@ -671,9 +711,15 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *
    * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
    * array(1 => array("Whiz", "String")));
+   * @param $expected
+   * @param $query
+   * @param array $params
+   * @param string $message
    */
   public function assertDBQuery($expected, $query, $params = array(), $message = '') {
-    if ($message) $message .= ': ';
+    if ($message) {
+      $message .= ': ';
+    }
     $actual = CRM_Core_DAO::singleValueQuery($query, $params);
     $this->assertEquals($expected, $actual,
       sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
@@ -725,7 +771,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
     foreach ($expectedValues as $paramName => $paramValue) {
       if (isset($actualValues[$paramName])) {
-        $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . "  value 2 is " . print_r($actualValues[$paramName], TRUE) );
+        $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . "  value 2 is " . print_r($actualValues[$paramName], TRUE));
       }
       else {
         $this->fail("Attribute '$paramName' not present in actual array.");
@@ -762,8 +808,10 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Check that api returned 'is_error' => 0
    * else provide full message
-   * @param array $apiResult api result
-   * @param string $prefix extra test to add to message
+   * @param array $apiResult
+   *   Api result.
+   * @param string $prefix
+   *   Extra test to add to message.
    */
   public function assertAPISuccess($apiResult, $prefix = '') {
     if (!empty($prefix)) {
@@ -771,10 +819,10 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     }
     $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message'];
 
-    if(!empty($apiResult['debug_information'])) {
+    if (!empty($apiResult['debug_information'])) {
       $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
     }
-    if(!empty($apiResult['trace'])){
+    if (!empty($apiResult['trace'])) {
       $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
     }
     $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
@@ -784,16 +832,18 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Check that api returned 'is_error' => 1
    * else provide full message
    *
-   * @param array $apiResult api result
-   * @param string $prefix extra test to add to message
+   * @param array $apiResult
+   *   Api result.
+   * @param string $prefix
+   *   Extra test to add to message.
    * @param null $expectedError
    */
   public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
     if (!empty($prefix)) {
       $prefix .= ': ';
     }
-    if($expectedError && !empty($apiResult['is_error'])){
-      $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
+    if ($expectedError && !empty($apiResult['is_error'])) {
+      $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
     }
     $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
     $this->assertNotEmpty($apiResult['error_message']);
@@ -810,6 +860,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
   /**
    * Check that a deleted item has been deleted
+   * @param $entity
+   * @param $id
    */
   public function assertAPIDeleted($entity, $id) {
     $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
@@ -822,15 +874,16 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @param array $result
    * @param $expected
    * @param array $valuesToExclude
-   * @param string $prefix extra test to add to message
+   * @param string $prefix
+   *   Extra test to add to message.
    */
   public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
     $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
     foreach ($valuesToExclude as $value) {
-      if(isset($result[$value])) {
+      if (isset($result[$value])) {
         unset($result[$value]);
       }
-      if(isset($expected[$value])) {
+      if (isset($expected[$value])) {
         unset($expected[$value]);
       }
     }
@@ -850,13 +903,14 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   }
 
   /**
-   * This function exists to wrap api functions
+   * wrap api functions
    * so we can ensure they succeed & throw exceptions without litterering the test with checks
    *
    * @param string $entity
    * @param string $action
    * @param array $params
-   * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
+   * @param mixed $checkAgainst
+   *   Optional value to check result against, implemented for getvalue,.
    *   getcount, getsingle. Note that for getvalue the type is checked rather than the value
    *   for getsingle the array is compared against an array passed in - the id is not compared (for
    *   better or worse )
@@ -871,12 +925,14 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       $params
     );
     switch (strtolower($action)) {
-      case 'getvalue' :
+      case 'getvalue':
         return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
-      case 'getsingle' :
+
+      case 'getsingle':
         return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
-      case 'getcount' :
-          return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
+
+      case 'getcount':
+        return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
     }
     $result = $this->civicrm_api($entity, $action, $params);
     $this->assertAPISuccess($result, "Failure in api call for $entity $action");
@@ -890,13 +946,14 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *
    * @param string $entity
    * @param array $params
-   * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
-   * - boolean
-   * - integer
-   * - double
-   * - string
-   * - array
-   * - object
+   * @param string $type
+   *   Per http://php.net/manual/en/function.gettype.php possible types.
+   *   - boolean
+   *   - integer
+   *   - double
+   *   - string
+   *   - array
+   *   - object
    *
    * @return array|int
    */
@@ -906,13 +963,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       'debug' => 1,
     );
     $result = $this->civicrm_api($entity, 'getvalue', $params);
-    if($type){
-      if($type == 'integer'){
+    if ($type) {
+      if ($type == 'integer') {
         // api seems to return integers as strings
         $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
       }
-      else{
-        $this->assertType($type, $result, "returned result should have been of type $type but was " );
+      else {
+        $this->assertType($type, $result, "returned result should have been of type $type but was ");
       }
     }
     return $result;
@@ -924,13 +981,14 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *
    * @param string $entity
    * @param array $params
-   * @param array $checkAgainst - array to compare result against
-   * - boolean
-   * - integer
-   * - double
-   * - string
-   * - array
-   * - object
+   * @param array $checkAgainst
+   *   Array to compare result against.
+   *   - boolean
+   *   - integer
+   *   - double
+   *   - string
+   *   - array
+   *   - object
    *
    * @throws Exception
    * @return array|int
@@ -941,10 +999,10 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       'debug' => 1,
     );
     $result = $this->civicrm_api($entity, 'getsingle', $params);
-    if(!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
+    if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
       throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
     }
-    if($checkAgainst){
+    if ($checkAgainst) {
       // @todo - have gone with the fn that unsets id? should we check id?
       $this->checkArrayEquals($result, $checkAgainst);
     }
@@ -960,13 +1018,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @param null $count
    * @throws Exception
    * @return array|int
-   * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
-   * - boolean
-   * - integer
-   * - double
-   * - string
-   * - array
-   * - object
    */
   public function callAPISuccessGetCount($entity, $params, $count = NULL) {
     $params += array(
@@ -974,10 +1025,10 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       'debug' => 1,
     );
     $result = $this->civicrm_api($entity, 'getcount', $params);
-    if(!is_integer($result) || !empty($result['is_error']) || isset($result['values'])) {
+    if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) {
       throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
     }
-    if(is_int($count)){
+    if (is_int($count)) {
       $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
     }
     return $result;
@@ -990,14 +1041,16 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @param string $entity
    * @param string $action
    * @param array $params
-   * @param string $function - pass this in to create a generated example
-   * @param string $file - pass this in to create a generated example
+   * @param string $function
+   *   Pass this in to create a generated example.
+   * @param string $file
+   *   Pass this in to create a generated example.
    * @param string $description
    * @param string|null $subfile
    * @param string|null $actionName
    * @return array|int
    */
-  public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
+  public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL) {
     $params['version'] = $this->_apiversion;
     $result = $this->callAPISuccess($entity, $action, $params);
     $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
@@ -1010,7 +1063,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @param string $entity
    * @param string $action
    * @param array $params
-   * @param string $expectedErrorMessage error
+   * @param string $expectedErrorMessage
+   *   Error.
    * @param null $extraOutput
    * @return array|int
    */
@@ -1031,19 +1085,23 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * so the distinction between set
    * up & tested functions is clearer
    *
-   *  @return array api Result
+   * @return array
+   *   api Result
    */
-  public function createTestEntity(){
+  public function createTestEntity() {
     return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
   }
 
   /**
    * Generic function to create Organisation, to be used in test cases
    *
-   * @param array   parameters for civicrm_contact_add api function call
-   * @param int     sequence number if creating multiple organizations
+   * @param array $params
+   *   parameters for civicrm_contact_add api function call
+   * @param int $seq
+   *   sequence number if creating multiple organizations
    *
-   * @return int    id of Organisation created
+   * @return int
+   *   id of Organisation created
    */
   public function organizationCreate($params = array(), $seq = 0) {
     if (!$params) {
@@ -1056,10 +1114,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Generic function to create Individual, to be used in test cases
    *
-   * @param array   parameters for civicrm_contact_add api function call
-   * @param int     sequence number if creating multiple individuals
+   * @param array $params
+   *   parameters for civicrm_contact_add api function call
+   * @param int $seq
+   *   sequence number if creating multiple individuals
    *
-   * @return int    id of Individual created
+   * @return int
+   *   id of Individual created
    */
   public function individualCreate($params = array(), $seq = 0) {
     $params = array_merge($this->sampleContact('Individual', $seq), $params);
@@ -1069,10 +1130,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Generic function to create Household, to be used in test cases
    *
-   * @param array   parameters for civicrm_contact_add api function call
-   * @param int     sequence number if creating multiple households
+   * @param array $params
+   *   parameters for civicrm_contact_add api function call
+   * @param int $seq
+   *   sequence number if creating multiple households
    *
-   * @return int    id of Household created
+   * @return int
+   *   id of Household created
    */
   public function householdCreate($params = array(), $seq = 0) {
     $params = array_merge($this->sampleContact('Household', $seq), $params);
@@ -1082,10 +1146,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Helper function for getting sample contact properties
    *
-   * @param enum     contact type: Individual, Organization
-   * @param int      sequence number for the values of this type
+   * @param string $contact_type
+   *   enum contact type: Individual, Organization
+   * @param int $seq
+   *   sequence number for the values of this type
    *
-   * @return array   properties of sample contact (ie. $params for API call)
+   * @return array
+   *   properties of sample contact (ie. $params for API call)
    */
   public function sampleContact($contact_type, $seq = 0) {
     $samples = array(
@@ -1096,7 +1163,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
         'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
       ),
       'Organization' => array(
-        'organization_name' => array('Unit Test Organization', 'Acme', 'Roberts and Sons', 'Cryo Space Labs', 'Sharper Pens'),
+        'organization_name' => array(
+          'Unit Test Organization',
+          'Acme',
+          'Roberts and Sons',
+          'Cryo Space Labs',
+          'Sharper Pens',
+        ),
       ),
       'Household' => array(
         'household_name' => array('Unit Test household'),
@@ -1104,14 +1177,14 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     );
     $params = array('contact_type' => $contact_type);
     foreach ($samples[$contact_type] as $key => $values) {
-      $params[$key] = $values[$seq % sizeof($values)];
+      $params[$key] = $values[$seq % count($values)];
     }
-    if ($contact_type == 'Individual' ) {
-        $params['email'] = strtolower(
-          $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
-        );
-        $params['prefix_id'] = 3;
-        $params['suffix_id'] = 3;
+    if ($contact_type == 'Individual') {
+      $params['email'] = strtolower(
+        $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
+      );
+      $params['prefix_id'] = 3;
+      $params['suffix_id'] = 3;
     }
     return $params;
   }
@@ -1119,11 +1192,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Private helper function for calling civicrm_contact_add
    *
-   * @param array $params for civicrm_contact_add api function call
+   * @param array $params
+   *   For civicrm_contact_add api function call.
    *
    * @throws Exception
    *
-   * @return int    id of Household created
+   * @return int
+   *   id of Household created
    */
   private function _contactCreate($params) {
     $result = $this->callAPISuccess('contact', 'create', $params);
@@ -1134,25 +1209,20 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   }
 
   /**
-   * @param int $contactID
+   * Delete contact, ensuring it is not the domain contact
    *
-   * @return array|int
+   * @param int $contactID
+   *   Contact ID to delete
    */
   public function contactDelete($contactID) {
-    $params = array(
-      'id' => $contactID,
-      'skip_undelete' => 1,
-      'debug' => 1,
-    );
-    $domain = new CRM_Core_BAO_Domain;
+    $domain = new CRM_Core_BAO_Domain();
     $domain->contact_id = $contactID;
-    if ($domain->find(TRUE)) {
-      // we are finding tests trying to delete the domain contact in cleanup
-      //since this is mainly for cleanup lets put a safeguard here
-      return;
+    if (!$domain->find(TRUE)) {
+      $this->callAPISuccess('contact', 'delete', array(
+        'id' => $contactID,
+        'skip_undelete' => 1,
+      ));
     }
-    $result = $this->callAPISuccess('contact', 'delete', $params);
-    return  $result;
   }
 
   /**
@@ -1161,7 +1231,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * @throws Exception
    */
   public function contactTypeDelete($contactTypeId) {
-    require_once 'CRM/Contact/BAO/ContactType.php';
     $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
     if (!$result) {
       throw new Exception('Could not delete contact type');
@@ -1236,7 +1305,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   public function membershipDelete($membershipID) {
     $deleteParams = array('id' => $membershipID);
     $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
-    return;
   }
 
   /**
@@ -1264,7 +1332,6 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       return;
     }
     $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
-    return;
   }
 
   /**
@@ -1281,7 +1348,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
         'is_reserved' => 1,
         'is_active' => 1,
       ),
-       $params
+      $params
     );
 
     $result = $this->callAPISuccess('relationship_type', 'create', $params);
@@ -1327,15 +1394,17 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create Participant
    *
-   * @param array $params  array of contact id and event id values
+   * @param array $params
+   *   Array of contact id and event id values.
    *
-   * @return int $id of participant created
+   * @return int
+   *   $id of participant created
    */
   public function participantCreate($params) {
-    if(empty($params['contact_id'])){
+    if (empty($params['contact_id'])) {
       $params['contact_id'] = $this->individualCreate();
     }
-    if(empty($params['event_id'])){
+    if (empty($params['event_id'])) {
       $event = $this->eventCreate();
       $params['event_id'] = $event['id'];
     }
@@ -1356,7 +1425,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create Payment Processor
    *
-   * @return object of Payment Processsor
+   * @return CRM_Financial_DAO_PaymentProcessor
+   *   instance of Payment Processsor
    */
   public function processorCreate() {
     $processorParams = array(
@@ -1378,7 +1448,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Create contribution page
    *
    * @param array $params
-   * @return object of contribution page
+   * @return array
+   *   Array of contribution page
    */
   public function contributionPageCreate($params) {
     $this->_pageParams = array(
@@ -1400,7 +1471,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Create Tag
    *
    * @param array $params
-   * @return array result of created tag
+   * @return array
+   *   result of created tag
    */
   public function tagCreate($params = array()) {
     $defaults = array(
@@ -1409,14 +1481,17 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       'domain_id' => '1',
     );
     $params = array_merge($defaults, $params);
-    $result =  $this->callAPISuccess('Tag', 'create', $params);
+    $result = $this->callAPISuccess('Tag', 'create', $params);
     return $result['values'][$result['id']];
   }
 
   /**
    * Delete Tag
    *
-   * @param  int $tagId   id of the tag to be deleted
+   * @param int $tagId
+   *   Id of the tag to be deleted.
+   *
+   * @return int
    */
   public function tagDelete($tagId) {
     require_once 'api/api.php';
@@ -1430,7 +1505,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Add entity(s) to the tag
    *
-   * @param  array $params
+   * @param array $params
    *
    * @return bool
    */
@@ -1442,9 +1517,11 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create contribution
    *
-   * @param int $cID contact_id
+   * @param int $cID
+   *   Contact_id.
    *
-   * @return int id of created contribution
+   * @return int
+   *   id of created contribution
    */
   public function pledgeCreate($cID) {
     $params = array(
@@ -1481,14 +1558,17 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create contribution
    *
-   * @param int $cID contact_id
-   * @param int $cTypeID id of financial type
-   *
+   * @param int $cID
+   *   Contact_id.
+   * @param int $cTypeID
+   *   Id of financial type.
    * @param int $invoiceID
    * @param int $trxnID
    * @param int $paymentInstrumentID
    * @param bool $isFee
-   * @return int id of created contribution
+   *
+   * @return int
+   *   id of created contribution
    */
   public function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
     $params = array(
@@ -1519,11 +1599,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Create online contribution
    *
    * @param array $params
-   * @param int $financialType id of financial type
-   *
+   * @param int $financialType
+   *   Id of financial type.
    * @param int $invoiceID
    * @param int $trxnID
-   * @return int id of created contribution
+   *
+   * @return int
+   *   id of created contribution
    */
   public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
     $contribParams = array(
@@ -1560,9 +1642,10 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create an Event
    *
-   * @param array $params  name-value pair for an event
+   * @param array $params
+   *   Name-value pair for an event.
    *
-   * @return array $event
+   * @return array
    */
   public function eventCreate($params = array()) {
     // if no contact was passed, make up a dummy event creator
@@ -1599,7 +1682,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Delete event
    *
-   * @param int $id ID of the event
+   * @param int $id
+   *   ID of the event.
    *
    * @return array|int
    */
@@ -1629,7 +1713,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    *
    * @param int $participantID
    * @param int $contributionID
-   * @return int $id of created payment
+   * @return int
+   *   $id of created payment
    */
   public function participantPaymentCreate($participantID, $contributionID = NULL) {
     //Create Participant Payment record With Values
@@ -1658,7 +1743,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Add a Location
    *
    * @param int $contactID
-   * @return int location id of created location
+   * @return int
+   *   location id of created location
    */
   public function locationAdd($contactID) {
     $address = array(
@@ -1671,7 +1757,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
         'state_province' => 'Michigan',
         'supplemental_address_1' => 'Hallmark Ct',
         'supplemental_address_2' => 'Jersey Village',
-      )
+      ),
     );
 
     $params = array(
@@ -1688,7 +1774,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Delete Locations of contact
    *
-   * @param array $params parameters
+   * @param array $params
+   *   Parameters.
    */
   public function locationDelete($params) {
     $this->callAPISuccess('Location', 'delete', $params);
@@ -1698,7 +1785,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Add a Location Type
    *
    * @param array $params
-   * @return int location id of created location
+   * @return CRM_Core_DAO_LocationType
+   *   location id of created location
    */
   public function locationTypeCreate($params = NULL) {
     if ($params === NULL) {
@@ -1722,7 +1810,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Delete a Location Type
    *
-   * @param int location type id
+   * @param int $locationTypeId
    */
   public function locationTypeDelete($locationTypeId) {
     $locationType = new CRM_Core_DAO_LocationType();
@@ -1734,38 +1822,41 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Add a Group
    *
    * @param array $params
-   * @return int groupId of created group
+   * @return int
+   *   groupId of created group
    */
   public function groupCreate($params = array()) {
     $params = array_merge(array(
-        'name' => 'Test Group 1',
-        'domain_id' => 1,
-        'title' => 'New Test Group Created',
-        'description' => 'New Test Group Created',
-        'is_active' => 1,
-        'visibility' => 'Public Pages',
-        'group_type' => array(
-          '1' => 1,
-          '2' => 1,
-        ),
-      ), $params);
+      'name' => 'Test Group 1',
+      'domain_id' => 1,
+      'title' => 'New Test Group Created',
+      'description' => 'New Test Group Created',
+      'is_active' => 1,
+      'visibility' => 'Public Pages',
+      'group_type' => array(
+        '1' => 1,
+        '2' => 1,
+      ),
+    ), $params);
 
     $result = $this->callAPISuccess('Group', 'create', $params);
     return $result['id'];
   }
 
 
- /**
 /**
    * Function to add a Group
    *
    * @params array to add group
    *
-   * @param array $params
-   * @return int groupId of created group
+   * @param int $groupID
+   * @param int $totalCount
+   * @return int
+   *    groupId of created group
    */
   public function groupContactCreate($groupID, $totalCount = 10) {
     $params = array('group_id' => $groupID);
-    for ($i=1; $i <= $totalCount; $i++) {
+    for ($i = 1; $i <= $totalCount; $i++) {
       $contactID = $this->individualCreate();
       if ($i == 1) {
         $params += array('contact_id' => $contactID);
@@ -1816,7 +1907,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Add a UF Join Entry
    *
    * @param array $params
-   * @return int $id of created UF Join
+   * @return int
+   *   $id of created UF Join
    */
   public function ufjoinCreate($params = NULL) {
     if ($params === NULL) {
@@ -1836,7 +1928,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Delete a UF Join Entry
    *
-   * @param array with missing uf_group_id
+   * @param array $params
+   *   with missing uf_group_id
    */
   public function ufjoinDelete($params = NULL) {
     if ($params === NULL) {
@@ -1926,22 +2019,24 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create an activity type
    *
-   * @param array $params parameters
+   * @param array $params
+   *   Parameters.
+   * @return array
    */
   public function activityTypeCreate($params) {
-    $result = $this->callAPISuccess('ActivityType', 'create', $params);
-    return $result;
+    return $this->callAPISuccess('ActivityType', 'create', $params);
   }
 
   /**
    * Delete activity type
    *
-   * @param int $activityTypeId id of the activity type
+   * @param int $activityTypeId
+   *   Id of the activity type.
+   * @return array
    */
   public function activityTypeDelete($activityTypeId) {
     $params['activity_type_id'] = $activityTypeId;
-    $result = $this->callAPISuccess('ActivityType', 'delete', $params);
-    return $result;
+    return $this->callAPISuccess('ActivityType', 'delete', $params);
   }
 
   /**
@@ -1962,11 +2057,14 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $params = array_merge($defaults, $params);
 
     if (strlen($params['title']) > 13) {
-      $params['title'] =  substr($params['title'], 0, 13);
+      $params['title'] = substr($params['title'], 0, 13);
     }
 
     //have a crack @ deleting it first in the hope this will prevent derailing our tests
-    $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
+    $this->callAPISuccess('custom_group', 'get', array(
+      'title' => $params['title'],
+      array('api.custom_group.delete' => 1),
+    ));
 
     return $this->callAPISuccess('custom_group', 'create', $params);
   }
@@ -1974,6 +2072,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Existing function doesn't allow params to be over-ridden so need a new one
    * this one allows you to only pass in the params you want to change
+   * @param array $params
+   * @return array|int
    */
   public function CustomGroupCreateByParams($params = array()) {
     $defaults = array(
@@ -1989,6 +2089,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
   /**
    * Create custom group with multi fields
+   * @param array $params
+   * @return array|int
    */
   public function CustomGroupMultipleCreateByParams($params = array()) {
     $defaults = array(
@@ -2001,6 +2103,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
 
   /**
    * Create custom group with multi fields
+   * @param array $params
+   * @return array
    */
   public function CustomGroupMultipleCreateWithFields($params = array()) {
     // also need to pass on $params['custom_field'] if not set but not in place yet
@@ -2008,14 +2112,25 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     $customGroup = $this->CustomGroupMultipleCreateByParams($params);
     $ids['custom_group_id'] = $customGroup['id'];
 
-    $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
+    $customField = $this->customFieldCreate(array(
+      'custom_group_id' => $ids['custom_group_id'],
+      'label' => 'field_1' . $ids['custom_group_id'],
+    ));
 
     $ids['custom_field_id'][] = $customField['id'];
 
-    $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
+    $customField = $this->customFieldCreate(array(
+      'custom_group_id' => $ids['custom_group_id'],
+      'default_value' => '',
+      'label' => 'field_2' . $ids['custom_group_id'],
+    ));
     $ids['custom_field_id'][] = $customField['id'];
 
-    $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
+    $customField = $this->customFieldCreate(array(
+      'custom_group_id' => $ids['custom_group_id'],
+      'default_value' => '',
+      'label' => 'field_3' . $ids['custom_group_id'],
+    ));
     $ids['custom_field_id'][] = $customField['id'];
 
     return $ids;
@@ -2025,15 +2140,18 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Create a custom group with a single text custom field.  See
    * participant:testCreateWithCustom for how to use this
    *
-   * @param string $function __FUNCTION__
-   * @param $filename string $file __FILE__
+   * @param string $function
+   *   __FUNCTION__.
+   * @param string $filename
+   *   $file __FILE__.
    *
-   * @return array $ids ids of created objects
+   * @return array
+   *   ids of created objects
    */
   public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
     $params = array('title' => $function);
     $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
-    $params['extends'] =  $entity ? $entity : 'Contact';
+    $params['extends'] = $entity ? $entity : 'Contact';
     $customGroup = $this->CustomGroupCreate($params);
     $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
     CRM_Core_PseudoConstant::flush();
@@ -2056,8 +2174,9 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
   /**
    * Create custom field
    *
-   * @param array $params (custom_group_id) is required
-   * @return array|int
+   * @param array $params
+   *   (custom_group_id) is required.
+   * @return array
    */
   public function customFieldCreate($params) {
     $params = array_merge(array(
@@ -2070,13 +2189,10 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     ), $params);
 
     $result = $this->callAPISuccess('custom_field', 'create', $params);
-
-    if ($result['is_error'] == 0 && isset($result['id'])) {
-      CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
-      // force reset of enabled components to help grab custom fields
-      CRM_Core_Component::getEnabledComponents(1);
-      return $result;
-    }
+    // these 2 functions are called with force to flush static caches
+    CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
+    CRM_Core_Component::getEnabledComponents(1);
+    return $result;
   }
 
   /**
@@ -2096,7 +2212,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Create note
    *
    * @param int $cId
-   * @return array $note
+   * @return array
    */
   public function noteCreate($cId) {
     $params = array(
@@ -2127,13 +2243,20 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * To turn this off (e.g. on the server) set
    * define(DONT_DOCUMENT_TEST_CONFIG ,1);
    * in your settings file
-   * @param array $params array as passed to civicrm_api function
-   * @param array $result array as received from the civicrm_api function
-   * @param string $function calling function - generally __FUNCTION__
-   * @param string $filename called from file - generally __FILE__
-   * @param string $description descriptive text for the example file
-   * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
-   * @param string $action - optional action - otherwise taken from function name
+   * @param array $params
+   *   Array as passed to civicrm_api function.
+   * @param array $result
+   *   Array as received from the civicrm_api function.
+   * @param string $function
+   *   Calling function - generally __FUNCTION__.
+   * @param string $filename
+   *   Called from file - generally __FILE__.
+   * @param string $description
+   *   Descriptive text for the example file.
+   * @param string $subfile
+   *   Name for subfile - if this is completed the example will be put in a subfolder (named by the entity).
+   * @param string $action
+   *   Optional action - otherwise taken from function name.
    */
   public function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
     if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG) {
@@ -2204,7 +2327,7 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     }
 
     $this->tidyExampleResult($result);
-    if(isset($params['version'])) {
+    if (isset($params['version'])) {
       unset($params['version']);
     }
     // a cleverer person than me would do it in a single regex
@@ -2244,10 +2367,9 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * and debug related fields are unset
    *
    * @param array $result
-   *
    */
-  public function tidyExampleResult(&$result){
-    if(!is_array($result)) {
+  public function tidyExampleResult(&$result) {
+    if (!is_array($result)) {
       return;
     }
     $fieldsToChange = array(
@@ -2267,19 +2389,19 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
       'decision_date' => '20130805000000',
     );
 
-    $keysToUnset = array('xdebug', 'undefined_fields',);
+    $keysToUnset = array('xdebug', 'undefined_fields');
     foreach ($keysToUnset as $unwantedKey) {
-      if(isset($result[$unwantedKey])) {
+      if (isset($result[$unwantedKey])) {
         unset($result[$unwantedKey]);
       }
     }
     if (isset($result['values'])) {
-      if(!is_array($result['values'])) {
+      if (!is_array($result['values'])) {
         return;
       }
       $resultArray = &$result['values'];
     }
-    elseif(is_array($result)) {
+    elseif (is_array($result)) {
       $resultArray = &$result;
     }
     else {
@@ -2287,33 +2409,33 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
     }
 
     foreach ($resultArray as $index => &$values) {
-        if(!is_array($values)) {
-          continue;
-        }
-        foreach($values as $key => &$value) {
-          if(substr($key, 0, 3)  == 'api' && is_array($value)) {
-            if(isset($value['is_error'])) {
-              // we have a std nested result format
-              $this->tidyExampleResult($value);
-            }
-            else{
-              foreach ($value as &$nestedResult) {
-                // this is an alternative syntax for nested results a keyed array of results
-                $this->tidyExampleResult($nestedResult);
-              }
-            }
-          }
-          if(in_array($key, $keysToUnset)) {
-            unset($values[$key]);
-            break;
-          }
-          if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
-            $value = $fieldsToChange[$key];
+      if (!is_array($values)) {
+        continue;
+      }
+      foreach ($values as $key => &$value) {
+        if (substr($key, 0, 3) == 'api' && is_array($value)) {
+          if (isset($value['is_error'])) {
+            // we have a std nested result format
+            $this->tidyExampleResult($value);
           }
-          if(is_string($value)) {
-            $value =  addslashes($value);
+          else {
+            foreach ($value as &$nestedResult) {
+              // this is an alternative syntax for nested results a keyed array of results
+              $this->tidyExampleResult($nestedResult);
+            }
           }
         }
+        if (in_array($key, $keysToUnset)) {
+          unset($values[$key]);
+          break;
+        }
+        if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
+          $value = $fieldsToChange[$key];
+        }
+        if (is_string($value)) {
+          $value = addslashes($value);
+        }
+      }
     }
   }
 
@@ -2332,7 +2454,8 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
    * Create custom field with Option Values
    *
    * @param array $customGroup
-   * @param string $name name of custom field
+   * @param string $name
+   *   Name of custom field.
    *
    * @return array|int
    */
@@ -2382,11 +2505,13 @@ class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
         return TRUE;
       }
     }
+    return FALSE;
   }
 
   /**
    * @param $tablesToTruncate
    * @param bool $dropCustomValueTables
+   * @throws \Exception
    */
   public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
     if ($this->tx) {
@@ -2464,12 +2589,16 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
   /*
    * Function does a 'Get' on the entity & compares the fields in the Params with those returned
    * Default behaviour is to also delete the entity
-   * @param array $params params array to check agains
-   * @param int  $id id of the entity concerned
-   * @param string $entity name of entity concerned (e.g. membership)
-   * @param bool $delete should the entity be deleted as part of this check
-   * @param string $errorText text to print on error
-   *
+   * @param array $params
+   *   Params array to check agains.
+   * @param int $id
+   *   Id of the entity concerned.
+   * @param string $entity
+   *   Name of entity concerned (e.g. membership).
+   * @param bool $delete
+   *   Should the entity be deleted as part of this check.
+   * @param string $errorText
+   *   Text to print on error.
    */
   /**
    * @param array $params
@@ -2504,14 +2633,14 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
       if ($type == CRM_Utils_Type::T_DATE) {
         $dateFields[] = $settings['name'];
         // we should identify both real names & unique names as dates
-        if($field != $settings['name']) {
+        if ($field != $settings['name']) {
           $dateFields[] = $field;
         }
       }
-      if($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
+      if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
         $dateTimeFields[] = $settings['name'];
         // we should identify both real names & unique names as dates
-        if($field != $settings['name']) {
+        if ($field != $settings['name']) {
           $dateTimeFields[] = $field;
         }
       }
@@ -2543,9 +2672,10 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
 
   /**
    * Get formatted values in  the actual and expected result
-   * @param array $actual actual calculated values
-   * @param array $expected expected values
-   *
+   * @param array $actual
+   *   Actual calculated values.
+   * @param array $expected
+   *   Expected values.
    */
   public function checkArrayEquals(&$actual, &$expected) {
     self::unsetId($actual);
@@ -2555,8 +2685,8 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
 
   /**
    * Unset the key 'id' from the array
-   * @param array $unformattedArray The array from which the 'id' has to be unset
-   *
+   * @param array $unformattedArray
+   *   The array from which the 'id' has to be unset.
    */
   public static function unsetId(&$unformattedArray) {
     $formattedArray = array();
@@ -2565,7 +2695,7 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
     }
     if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
       foreach ($unformattedArray['values'] as $key => $value) {
-        if (is_Array($value)) {
+        if (is_array($value)) {
           foreach ($value as $k => $v) {
             if ($k == 'id') {
               unset($value[$k]);
@@ -2584,7 +2714,8 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
   /**
    *  Helper to enable/disable custom directory support
    *
-   * @param array $customDirs with members:
+   * @param array $customDirs
+   *   With members:.
    *   'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
    *   'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
    */
@@ -2617,7 +2748,7 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
    * Generate a temporary folder
    *
    * @param string $prefix
-   * @return string $string
+   * @return string
    */
   public function createTempDir($prefix = 'test-') {
     $tempDir = CRM_Utils_File::tempdir($prefix);
@@ -2639,6 +2770,7 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
 
   /**
    * Temporarily replace the singleton extension with a different one
+   * @param \CRM_Extension_System $system
    */
   public function setExtensionSystem(CRM_Extension_System $system) {
     if ($this->origExtensionSystem == NULL) {
@@ -2664,12 +2796,13 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
    */
   public function setMockSettingsMetaData($extras) {
     CRM_Core_BAO_Setting::$_cache = array();
-    $this->callAPISuccess('system','flush', array());
+    $this->callAPISuccess('system', 'flush', array());
     CRM_Core_BAO_Setting::$_cache = array();
 
-    CRM_Utils_Hook::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
-      $metadata = array_merge($metadata, $extras);
-    });
+    CRM_Utils_Hook::singleton()
+      ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
+        $metadata = array_merge($metadata, $extras);
+      });
 
     $fields = $this->callAPISuccess('setting', 'getfields', array());
     foreach ($extras as $key => $spec) {
@@ -2684,7 +2817,7 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
   public function financialAccountDelete($name) {
     $financialAccount = new CRM_Financial_DAO_FinancialAccount();
     $financialAccount->name = $name;
-    if($financialAccount->find(TRUE)) {
+    if ($financialAccount->find(TRUE)) {
       $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
       $entityFinancialType->financial_account_id = $financialAccount->id;
       $entityFinancialType->delete();
@@ -2700,167 +2833,167 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
     $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
       'required' => array(
         'html_quickform_rule_required',
-        'HTML/QuickForm/Rule/Required.php'
+        'HTML/QuickForm/Rule/Required.php',
       ),
       'maxlength' => array(
         'html_quickform_rule_range',
-        'HTML/QuickForm/Rule/Range.php'
+        'HTML/QuickForm/Rule/Range.php',
       ),
       'minlength' => array(
         'html_quickform_rule_range',
-        'HTML/QuickForm/Rule/Range.php'
+        'HTML/QuickForm/Rule/Range.php',
       ),
       'rangelength' => array(
         'html_quickform_rule_range',
-        'HTML/QuickForm/Rule/Range.php'
+        'HTML/QuickForm/Rule/Range.php',
       ),
       'email' => array(
         'html_quickform_rule_email',
-        'HTML/QuickForm/Rule/Email.php'
+        'HTML/QuickForm/Rule/Email.php',
       ),
       'regex' => array(
         'html_quickform_rule_regex',
-        'HTML/QuickForm/Rule/Regex.php'
+        'HTML/QuickForm/Rule/Regex.php',
       ),
       'lettersonly' => array(
         'html_quickform_rule_regex',
-        'HTML/QuickForm/Rule/Regex.php'
+        'HTML/QuickForm/Rule/Regex.php',
       ),
       'alphanumeric' => array(
         'html_quickform_rule_regex',
-        'HTML/QuickForm/Rule/Regex.php'
+        'HTML/QuickForm/Rule/Regex.php',
       ),
       'numeric' => array(
         'html_quickform_rule_regex',
-        'HTML/QuickForm/Rule/Regex.php'
+        'HTML/QuickForm/Rule/Regex.php',
       ),
       'nopunctuation' => array(
         'html_quickform_rule_regex',
-        'HTML/QuickForm/Rule/Regex.php'
+        'HTML/QuickForm/Rule/Regex.php',
       ),
       'nonzero' => array(
         'html_quickform_rule_regex',
-        'HTML/QuickForm/Rule/Regex.php'
+        'HTML/QuickForm/Rule/Regex.php',
       ),
       'callback' => array(
         'html_quickform_rule_callback',
-        'HTML/QuickForm/Rule/Callback.php'
+        'HTML/QuickForm/Rule/Callback.php',
       ),
       'compare' => array(
         'html_quickform_rule_compare',
-        'HTML/QuickForm/Rule/Compare.php'
-      )
+        'HTML/QuickForm/Rule/Compare.php',
+      ),
     );
     // FIXME: â€¦ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
     $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
       'group' => array(
         'HTML/QuickForm/group.php',
-        'HTML_QuickForm_group'
+        'HTML_QuickForm_group',
       ),
       'hidden' => array(
         'HTML/QuickForm/hidden.php',
-        'HTML_QuickForm_hidden'
+        'HTML_QuickForm_hidden',
       ),
       'reset' => array(
         'HTML/QuickForm/reset.php',
-        'HTML_QuickForm_reset'
+        'HTML_QuickForm_reset',
       ),
       'checkbox' => array(
         'HTML/QuickForm/checkbox.php',
-        'HTML_QuickForm_checkbox'
+        'HTML_QuickForm_checkbox',
       ),
       'file' => array(
         'HTML/QuickForm/file.php',
-        'HTML_QuickForm_file'
+        'HTML_QuickForm_file',
       ),
       'image' => array(
         'HTML/QuickForm/image.php',
-        'HTML_QuickForm_image'
+        'HTML_QuickForm_image',
       ),
       'password' => array(
         'HTML/QuickForm/password.php',
-        'HTML_QuickForm_password'
+        'HTML_QuickForm_password',
       ),
       'radio' => array(
         'HTML/QuickForm/radio.php',
-        'HTML_QuickForm_radio'
+        'HTML_QuickForm_radio',
       ),
       'button' => array(
         'HTML/QuickForm/button.php',
-        'HTML_QuickForm_button'
+        'HTML_QuickForm_button',
       ),
       'submit' => array(
         'HTML/QuickForm/submit.php',
-        'HTML_QuickForm_submit'
+        'HTML_QuickForm_submit',
       ),
       'select' => array(
         'HTML/QuickForm/select.php',
-        'HTML_QuickForm_select'
+        'HTML_QuickForm_select',
       ),
       'hiddenselect' => array(
         'HTML/QuickForm/hiddenselect.php',
-        'HTML_QuickForm_hiddenselect'
+        'HTML_QuickForm_hiddenselect',
       ),
       'text' => array(
         'HTML/QuickForm/text.php',
-        'HTML_QuickForm_text'
+        'HTML_QuickForm_text',
       ),
       'textarea' => array(
         'HTML/QuickForm/textarea.php',
-        'HTML_QuickForm_textarea'
+        'HTML_QuickForm_textarea',
       ),
       'fckeditor' => array(
         'HTML/QuickForm/fckeditor.php',
-        'HTML_QuickForm_FCKEditor'
+        'HTML_QuickForm_FCKEditor',
       ),
       'tinymce' => array(
         'HTML/QuickForm/tinymce.php',
-        'HTML_QuickForm_TinyMCE'
+        'HTML_QuickForm_TinyMCE',
       ),
       'dojoeditor' => array(
         'HTML/QuickForm/dojoeditor.php',
-        'HTML_QuickForm_dojoeditor'
+        'HTML_QuickForm_dojoeditor',
       ),
       'link' => array(
         'HTML/QuickForm/link.php',
-        'HTML_QuickForm_link'
+        'HTML_QuickForm_link',
       ),
       'advcheckbox' => array(
         'HTML/QuickForm/advcheckbox.php',
-        'HTML_QuickForm_advcheckbox'
+        'HTML_QuickForm_advcheckbox',
       ),
       'date' => array(
         'HTML/QuickForm/date.php',
-        'HTML_QuickForm_date'
+        'HTML_QuickForm_date',
       ),
       'static' => array(
         'HTML/QuickForm/static.php',
-        'HTML_QuickForm_static'
+        'HTML_QuickForm_static',
       ),
       'header' => array(
         'HTML/QuickForm/header.php',
-        'HTML_QuickForm_header'
+        'HTML_QuickForm_header',
       ),
       'html' => array(
         'HTML/QuickForm/html.php',
-        'HTML_QuickForm_html'
+        'HTML_QuickForm_html',
       ),
       'hierselect' => array(
         'HTML/QuickForm/hierselect.php',
-        'HTML_QuickForm_hierselect'
+        'HTML_QuickForm_hierselect',
       ),
       'autocomplete' => array(
         'HTML/QuickForm/autocomplete.php',
-        'HTML_QuickForm_autocomplete'
+        'HTML_QuickForm_autocomplete',
       ),
       'xbutton' => array(
         'HTML/QuickForm/xbutton.php',
-        'HTML_QuickForm_xbutton'
+        'HTML_QuickForm_xbutton',
       ),
       'advmultiselect' => array(
         'HTML/QuickForm/advmultiselect.php',
-        'HTML_QuickForm_advmultiselect'
-      )
+        'HTML_QuickForm_advmultiselect',
+      ),
     );
   }
 
@@ -2872,7 +3005,6 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
    *  $this->createLoggedInUser();
    *   $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
    *   $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
-   *
    */
   public function setupACL() {
     global $_REQUEST;
@@ -2880,12 +3012,12 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
 
     CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
     $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
-    $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
+    $optionValue = $this->callAPISuccess('option_value', 'create', array(
+      'option_group_id' => $optionGroupID,
       'label' => 'pick me',
       'value' => 55,
     ));
 
-
     CRM_Core_DAO::executeQuery("
       TRUNCATE civicrm_acl_cache
     ");
@@ -2894,7 +3026,6 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
       TRUNCATE civicrm_acl_contact_cache
     ");
 
-
     CRM_Core_DAO::executeQuery("
     INSERT INTO civicrm_acl_entity_role (
     `acl_role_id`, `entity_table`, `entity_id`
@@ -2935,14 +3066,25 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
   public function offsetDefaultPriceSet() {
     $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
     $firstID = $contributionPriceSet['id'];
-    $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
+    $this->callAPISuccess('price_set', 'create', array(
+      'id' => $contributionPriceSet['id'],
+      'is_active' => 0,
+      'name' => 'old',
+    ));
     unset($contributionPriceSet['id']);
     $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
-    $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
+    $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
+      'price_set_id' => $firstID,
+      'options' => array('limit' => 1),
+    ));
     unset($priceField['id']);
     $priceField['price_set_id'] = $newPriceSet['id'];
     $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
-    $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
+    $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
+      'price_set_id' => $firstID,
+      'sequential' => 1,
+      'options' => array('limit' => 1),
+    ));
 
     unset($priceFieldValue['id']);
     //create some padding to use up ids
@@ -2957,27 +3099,29 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
    * this parent class & we don't have a structure for that yet
    * There is another function to this effect on the PaypalPro test but it appears to be silently failing
    * & the best protection agains that is the functions this class affords
+   * @param array $params
+   * @return int $result['id'] payment processor id
    */
   public function paymentProcessorCreate($params = array()) {
     $params = array_merge(array(
-      'name' => 'demo',
-      'domain_id' => CRM_Core_Config::domainID(),
-      'payment_processor_type_id' => 'PayPal',
-      'is_active' => 1,
-      'is_default' => 0,
-      'is_test' => 1,
-      'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
-      'password' => '1183377788',
-      'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
-      'url_site' => 'https://www.sandbox.paypal.com/',
-      'url_api' => 'https://api-3t.sandbox.paypal.com/',
-      'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
-      'class_name' => 'Payment_PayPalImpl',
-      'billing_mode' => 3,
-      'financial_type_id' => 1,
-    ),
-    $params);
-    if(!is_numeric($params['payment_processor_type_id'])) {
+        'name' => 'demo',
+        'domain_id' => CRM_Core_Config::domainID(),
+        'payment_processor_type_id' => 'PayPal',
+        'is_active' => 1,
+        'is_default' => 0,
+        'is_test' => 1,
+        'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
+        'password' => '1183377788',
+        'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
+        'url_site' => 'https://www.sandbox.paypal.com/',
+        'url_api' => 'https://api-3t.sandbox.paypal.com/',
+        'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
+        'class_name' => 'Payment_PayPalImpl',
+        'billing_mode' => 3,
+        'financial_type_id' => 1,
+      ),
+      $params);
+    if (!is_numeric($params['payment_processor_type_id'])) {
       // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
       //here
       $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
@@ -3011,7 +3155,7 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
         'contact_id' => $this->_contactID,
         'contribution_page_id' => $this->_contributionPageID,
         'payment_processor_id' => $this->_paymentProcessorID,
-      )
+      ),
     ));
     $this->_contributionRecurID = $contributionRecur['id'];
     $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
@@ -3044,10 +3188,19 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
       'unit_price' => 200,
       'line_total' => 200,
       'financial_type_id' => 1,
-      'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array('return' => 'id', 'label' => 'Membership Amount')),
-      'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array('return' => 'id', 'label' => 'General')),
+      'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
+        'return' => 'id',
+        'label' => 'Membership Amount',
+      )),
+      'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
+        'return' => 'id',
+        'label' => 'General',
+      )),
+    ));
+    $this->callAPISuccess('membership_payment', 'create', array(
+      'contribution_id' => $this->_contributionID,
+      'membership_id' => $this->ids['membership'],
     ));
-    $this->callAPISuccess('membership_payment', 'create', array('contribution_id' => $this->_contributionID, 'membership_id' => $this->ids['membership']));
   }
 
   /**
@@ -3101,7 +3254,8 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
    * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
    * if TRUNCATE or ALTER is called while using a transaction.
    *
-   * @param bool $nest whether to use nesting or reference-counting
+   * @param bool $nest
+   *   Whether to use nesting or reference-counting.
    */
   public function useTransaction($nest = TRUE) {
     if (!$this->tx) {
@@ -3115,4 +3269,5 @@ AND    ( TABLE_NAME LIKE 'civicrm_value_%' )
       ob_end_clean();
     }
   }
+
 }