codespell: CRM/*
[civicrm-core.git] / CRM / Core / DAO.php
index 91bcb936514ed12556c0dac610b887909d79a41c..17a94514120af33e0f0359946c7d569d59a09dbd 100644 (file)
@@ -3,7 +3,7 @@
   +--------------------------------------------------------------------+
   | CiviCRM version 4.6                                                |
   +--------------------------------------------------------------------+
-  | Copyright CiviCRM LLC (c) 2004-2014                                |
+  | Copyright CiviCRM LLC (c) 2004-2015                                |
   +--------------------------------------------------------------------+
   | This file is a part of CiviCRM.                                    |
   |                                                                    |
   | GNU Affero General Public License or the licensing of CiviCRM,     |
   | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
   +--------------------------------------------------------------------+
-*/
+ */
 
 /**
  * Our base DAO class. All DAO classes should inherit from this class.
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2014
+ * @copyright CiviCRM LLC (c) 2004-2015
  * $Id$
  *
  */
@@ -63,13 +63,14 @@ class CRM_Core_DAO extends DB_DataObject {
     QUERY_FORMAT_WILDCARD = 1,
     QUERY_FORMAT_NO_QUOTES = 2;
 
-  /*
+  /**
    * Define entities that shouldn't be created or deleted when creating/ deleting
-   *  test objects - this prevents world regions, countries etc from being added / deleted
+   * test objects - this prevents world regions, countries etc from being added / deleted
+   * @var array
    */
   static $_testEntitiesToSkip = array();
   /**
-   * The factory class for this application
+   * The factory class for this application.
    * @var object
    */
   static $_factory = NULL;
@@ -77,10 +78,9 @@ class CRM_Core_DAO extends DB_DataObject {
   static $_checkedSqlFunctionsExist = FALSE;
 
   /**
-   * Class constructor
+   * Class constructor.
    *
    * @return \CRM_Core_DAO
-   * @access public
    */
   public function __construct() {
     $this->initialize();
@@ -88,20 +88,19 @@ class CRM_Core_DAO extends DB_DataObject {
   }
 
   /**
-   * Empty definition for virtual function
+   * Empty definition for virtual function.
    */
   public static function getTableName() {
     return NULL;
   }
 
   /**
-   * Initialize the DAO object
+   * Initialize the DAO object.
    *
    * @param string $dsn
    *   The database connection string.
    *
    * @return void
-   * @static
    */
   public static function init($dsn) {
     $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
@@ -130,7 +129,7 @@ class CRM_Core_DAO extends DB_DataObject {
       $required = TRUE;
     }
     if (!$required && $dbName != 'contact_id') {
-      $fkDAO = new $FKClassName;
+      $fkDAO = new $FKClassName();
       if ($fkDAO->find(TRUE)) {
         $this->$dbName = $fkDAO->id;
       }
@@ -221,9 +220,9 @@ class CRM_Core_DAO extends DB_DataObject {
           break;
 
         case CRM_Utils_Type::T_TIME:
-          CRM_Core_Error::fatal('T_TIME shouldnt be used.');
-        //$object->$dbName='000000';
-        //break;
+          CRM_Core_Error::fatal('T_TIME shouldn't be used.');
+          //$object->$dbName='000000';
+          //break;
         case CRM_Utils_Type::T_CCNUM:
           $this->$dbName = '4111 1111 1111 1111';
           break;
@@ -333,7 +332,6 @@ class CRM_Core_DAO extends DB_DataObject {
    *   The factory application object.
    *
    * @return void
-   * @static
    */
   public static function setFactory(&$factory) {
     self::$_factory = &$factory;
@@ -395,24 +393,23 @@ class CRM_Core_DAO extends DB_DataObject {
   }
 
   /**
-   * Returns list of FK relationships
+   * Returns list of FK relationships.
    *
-   * @static
    *
    * @return array
-   *   of CRM_Core_Reference_Interface
+   *   Array of CRM_Core_Reference_Interface
    */
   public static function getReferenceColumns() {
     return array();
   }
 
   /**
-   * Returns all the column names of this table
+   * Returns all the column names of this table.
    *
    *
    * @return array
    */
-  static function &fields() {
+  public static function &fields() {
     $result = NULL;
     return $result;
   }
@@ -420,7 +417,6 @@ class CRM_Core_DAO extends DB_DataObject {
   /**
    * Get/set an associative array of table columns
    *
-   * @param array key=>type array
    * @return array
    *   (associative)
    */
@@ -463,6 +459,31 @@ class CRM_Core_DAO extends DB_DataObject {
     return $this;
   }
 
+  /**
+   * Deletes items from table which match current objects variables.
+   *
+   * Returns the true on success
+   *
+   * for example
+   *
+   * Designed to be extended
+   *
+   * $object = new mytable();
+   * $object->ID=123;
+   * echo $object->delete(); // builds a conditon
+   *
+   * $object = new mytable();
+   * $object->whereAdd('age > 12');
+   * $object->limit(1);
+   * $object->orderBy('age DESC');
+   * $object->delete(true); // dont use object vars, use the conditions, limit and order.
+   *
+   * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
+   *             we will build the condition only using the whereAdd's.  Default is to
+   *             build the condition only using the object parameters.
+   *
+   *     * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
+   */
   public function delete($useWhere = FALSE) {
     $result = parent::delete($useWhere);
 
@@ -507,8 +528,8 @@ class CRM_Core_DAO extends DB_DataObject {
    * @param array $params
    *   (reference ) associative array of name/value pairs.
    *
-   * @return boolean
-   *   did we copy all null values into the object
+   * @return bool
+   *   Did we copy all null values into the object
    */
   public function copyValues(&$params) {
     $fields = &$this->fields();
@@ -552,7 +573,6 @@ class CRM_Core_DAO extends DB_DataObject {
    *   (reference ) associative array of name/value pairs.
    *
    * @return void
-   * @static
    */
   public static function storeValues(&$object, &$values) {
     $fields = &$object->fields();
@@ -575,7 +595,6 @@ class CRM_Core_DAO extends DB_DataObject {
    *
    * @return array|null
    *   the attributes for the object
-   * @static
    */
   public static function makeAttribute($field) {
     if ($field) {
@@ -618,7 +637,7 @@ class CRM_Core_DAO extends DB_DataObject {
   }
 
   /**
-   * Get the size and maxLength attributes for this text field
+   * Get the size and maxLength attributes for this text field.
    * (or for all text fields) in the DAO object.
    *
    * @param string $class
@@ -629,7 +648,6 @@ class CRM_Core_DAO extends DB_DataObject {
    *
    * @return array
    *   assoc array of name => attribute pairs
-   * @static
    */
   public static function getAttribute($class, $fieldName = NULL) {
     $object = new $class();
@@ -664,7 +682,7 @@ class CRM_Core_DAO extends DB_DataObject {
   }
 
   /**
-   * Check if there is a record with the same name in the db
+   * Check if there is a record with the same name in the db.
    *
    * @param string $value
    *   The value of the field we are checking.
@@ -676,9 +694,8 @@ class CRM_Core_DAO extends DB_DataObject {
    * @param string $fieldName
    *   The name of the field in the DAO.
    *
-   * @return boolean
+   * @return bool
    *   true if object exists
-   * @static
    */
   public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
     $object = new $daoName();
@@ -695,16 +712,15 @@ class CRM_Core_DAO extends DB_DataObject {
   }
 
   /**
-   * Check if there is a given column in a specific table
+   * Check if there is a given column in a specific table.
    *
    * @param string $tableName
    * @param string $columnName
    * @param bool $i18nRewrite
    *   Whether to rewrite the query on multilingual setups.
    *
-   * @return boolean
+   * @return bool
    *   true if exists, else false
-   * @static
    */
   public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
     $query = "
@@ -730,7 +746,6 @@ LIKE %1
    * @param string $fieldName
    *
    * @return array
-   * @static
    */
   public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
     $values = array();
@@ -788,9 +803,8 @@ LIKE %1
    * @param string $tableName
    * @param string $constraint
    *
-   * @return boolean
+   * @return bool
    *   true if constraint exists, false otherwise
-   * @static
    */
   public static function checkConstraintExists($tableName, $constraint) {
     static $show = array();
@@ -817,7 +831,7 @@ LIKE %1
    *
    * @throws Exception
    *
-   * @return boolean
+   * @return bool
    *   true if CONSTRAINT keyword exists, false otherwise
    */
   public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
@@ -853,9 +867,8 @@ LIKE %1
    * @param string $tableName
    * @param string $columnName
    *
-   * @return boolean
+   * @return bool
    *   true if in format, false otherwise
-   * @static
    */
   public static function checkFKConstraintInFormat($tableName, $columnName) {
     static $show = array();
@@ -877,15 +890,14 @@ LIKE %1
   }
 
   /**
-   * Check whether a specific column in a specific table has always the same value
+   * Check whether a specific column in a specific table has always the same value.
    *
    * @param string $tableName
    * @param string $columnName
    * @param string $columnValue
    *
-   * @return boolean
+   * @return bool
    *   true if the value is always $columnValue, false otherwise
-   * @static
    */
   public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
     $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
@@ -896,14 +908,13 @@ LIKE %1
   }
 
   /**
-   * Check whether a specific column in a specific table is always NULL
+   * Check whether a specific column in a specific table is always NULL.
    *
    * @param string $tableName
    * @param string $columnName
    *
-   * @return boolean
+   * @return bool
    *   true if if the value is always NULL, false otherwise
-   * @static
    */
   public static function checkFieldIsAlwaysNull($tableName, $columnName) {
     $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
@@ -914,13 +925,12 @@ LIKE %1
   }
 
   /**
-   * Check if there is a given table in the database
+   * Check if there is a given table in the database.
    *
    * @param string $tableName
    *
-   * @return boolean
+   * @return bool
    *   true if exists, else false
-   * @static
    */
   public static function checkTableExists($tableName) {
     $query = "
@@ -983,7 +993,6 @@ FROM   civicrm_domain
    *
    * @return string|null
    *   Value of $returnColumn in the retrieved record
-   * @static
    */
   public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
     if (
@@ -1032,9 +1041,8 @@ FROM   civicrm_domain
    * @param string $searchColumn
    *   Name of the column you want to search by.
    *
-   * @return boolean
+   * @return bool
    *   true if we found and updated the object, else false
-   * @static
    */
   public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
     $object = new $daoName();
@@ -1053,7 +1061,7 @@ FROM   civicrm_domain
   }
 
   /**
-   * Get sort string
+   * Get sort string.
    *
    * @param array|object $sort either array or CRM_Utils_Sort
    * @param string $default
@@ -1061,7 +1069,6 @@ FROM   civicrm_domain
    *
    * @return string
    *   sortString
-   * @static
    */
   public static function getSortString($sort, $default = NULL) {
     // check if sort is of type CRM_Utils_Sort
@@ -1080,7 +1087,7 @@ FROM   civicrm_domain
   }
 
   /**
-   * Fetch object based on array of properties
+   * Fetch object based on array of properties.
    *
    * @param string $daoName
    *   Name of the dao object.
@@ -1093,7 +1100,6 @@ FROM   civicrm_domain
    *
    * @return object
    *   an object of type referenced by daoName
-   * @static
    */
   public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
     $object = new $daoName();
@@ -1113,7 +1119,7 @@ FROM   civicrm_domain
   }
 
   /**
-   * Delete the object records that are associated with this contact
+   * Delete the object records that are associated with this contact.
    *
    * @param string $daoName
    *   Name of the dao object.
@@ -1121,7 +1127,6 @@ FROM   civicrm_domain
    *   Id of the contact to delete.
    *
    * @return void
-   * @static
    */
   public static function deleteEntityContact($daoName, $contactId) {
     $object = new $daoName();
@@ -1132,7 +1137,7 @@ FROM   civicrm_domain
   }
 
   /**
-   * Execute a query
+   * Execute a query.
    *
    * @param string $query
    *   Query to be executed.
@@ -1144,10 +1149,12 @@ FROM   civicrm_domain
    * @param bool $i18nRewrite
    * @param bool $trapException
    *
-   * @return CRM_Core_DAO object that holds the results of the query
-   * @static
+   * @return CRM_Core_DAO|object
+   *   object that holds the results of the query
+   *   NB - if this is defined as just returning a DAO phpstorm keeps pointing
+   *   out all the properties that are not part of the DAO
    */
-  static function &executeQuery(
+  public static function &executeQuery(
     $query,
     $params = array(),
     $abort = TRUE,
@@ -1178,7 +1185,7 @@ FROM   civicrm_domain
     if ($freeDAO ||
       preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
     ) {
-      // we typically do this for insert/update/delete stataments OR if explicitly asked to
+      // we typically do this for insert/update/delete statements OR if explicitly asked to
       // free the dao
       $dao->free();
     }
@@ -1186,7 +1193,7 @@ FROM   civicrm_domain
   }
 
   /**
-   * Execute a query and get the single result
+   * Execute a query and get the single result.
    *
    * @param string $query
    *   Query to be executed.
@@ -1196,9 +1203,8 @@ FROM   civicrm_domain
    * @return string|null
    *   the result of the query if any
    *
-   * @static
    */
-  static function &singleValueQuery(
+  public static function &singleValueQuery(
     $query,
     $params = array(),
     $abort = TRUE,
@@ -1308,7 +1314,7 @@ FROM   civicrm_domain
   }
 
   /**
-   * make a shallow copy of an object
+   * make a shallow copy of an object.
    * and all the fields in the object
    *
    * @param string $daoName
@@ -1329,7 +1335,7 @@ FROM   civicrm_domain
    * @return CRM_Core_DAO
    *   the newly created copy of the object
    */
-  static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
+  public static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
     $object = new $daoName();
     if (!$newData) {
       $object->id = $criteria['id'];
@@ -1402,6 +1408,16 @@ FROM   civicrm_domain
     return $newObject;
   }
 
+  /**
+   * Cascade update through related entities.
+   *
+   * @param string $daoName
+   * @param $fromId
+   * @param $toId
+   * @param array $newData
+   *
+   * @return null
+   */
   public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
     $object = new $daoName();
     $object->id = $fromId;
@@ -1468,7 +1484,7 @@ SELECT contact_id
   }
 
   /**
-   * Fetch object based on array of properties
+   * Fetch object based on array of properties.
    *
    * @param string $daoName
    *   Name of the dao object.
@@ -1480,10 +1496,9 @@ SELECT contact_id
    *
    * @return object
    *   an object of type referenced by daoName
-   * @static
    */
   public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
-    require_once(str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
+    require_once str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php";
     $object = new $daoName();
     $object->$fieldIdName = $fieldId;
 
@@ -1604,9 +1619,10 @@ SELECT contact_id
    * @param int $numObjects
    * @param bool $createOnly
    *
-   * @return
+   * @return object|array|NULL
+   *   NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
    */
-  static function createTestObject(
+  public static function createTestObject(
     $daoName,
     $params = array(),
     $numObjects = 1,
@@ -1623,7 +1639,7 @@ SELECT contact_id
       'CRM_Core_DAO_StateProvince',
       'CRM_Core_DAO_Country',
       'CRM_Core_DAO_Domain',
-      'CRM_Financial_DAO_FinancialType'
+      'CRM_Financial_DAO_FinancialType',
       //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
     );
 
@@ -1672,7 +1688,7 @@ SELECT contact_id
     }
 
     if ($createOnly) {
-      return;
+      return NULL;
     }
     elseif ($numObjects == 1) {
       return $objects[0];
@@ -1683,7 +1699,7 @@ SELECT contact_id
   }
 
   /**
-   * Deletes the this object plus any dependent objects that are associated with it
+   * Deletes the this object plus any dependent objects that are associated with it.
    * ONLY USE FOR TESTING
    *
    * @param string $daoName
@@ -1729,7 +1745,7 @@ SELECT contact_id
   }
 
   /**
-   * Set defaults when creating new entity
+   * Set defaults when creating new entity.
    * (don't call this set defaults as already in use with different signature in some places)
    *
    * @param array $params
@@ -1844,7 +1860,7 @@ SELECT contact_id
   public static function triggerRebuild($tableName = NULL, $force = FALSE) {
     $info = array();
 
-    $logging = new CRM_Logging_Schema;
+    $logging = new CRM_Logging_Schema();
     $logging->triggerInfo($info, $tableName, $force);
 
     CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
@@ -1877,7 +1893,7 @@ SELECT contact_id
   }
 
   /**
-   * Wrapper function to drop triggers
+   * Wrapper function to drop triggers.
    *
    * @param string $tableName
    *   the specific table requiring a rebuild; or NULL to rebuild all tables.
@@ -1885,7 +1901,7 @@ SELECT contact_id
   public static function dropTriggers($tableName = NULL) {
     $info = array();
 
-    $logging = new CRM_Logging_Schema;
+    $logging = new CRM_Logging_Schema();
     $logging->triggerInfo($info, $tableName);
 
     // drop all existing triggers on all tables
@@ -2031,7 +2047,7 @@ SELECT contact_id
    * Find all records which refer to this entity.
    *
    * @return array
-   *   of objects referencing this
+   *   Array of objects referencing this
    */
   public function findReferences() {
     $links = self::getReferencesToTable(static::getTableName());
@@ -2056,11 +2072,11 @@ SELECT contact_id
   /**
    * @return array
    *   each item has keys:
-   *  - name: string
-   *  - type: string
-   *  - count: int
-   *  - table: string|null SQL table name
-   *  - key: string|null SQL column name
+   *   - name: string
+   *   - type: string
+   *   - count: int
+   *   - table: string|null SQL table name
+   *   - key: string|null SQL column name
    */
   public function getReferenceCounts() {
     $links = self::getReferencesToTable(static::getTableName());
@@ -2097,7 +2113,7 @@ SELECT contact_id
    *
    * @return array
    *   structure of table and column, listing every table with a
-   * foreign key reference to $tableName, and the column where the key appears.
+   *   foreign key reference to $tableName, and the column where the key appears.
    */
   public static function getReferencesToTable($tableName) {
     $refsFound = array();
@@ -2143,11 +2159,11 @@ SELECT contact_id
    *
    * @param string $fieldName
    * @param string $context
-   *   : @see CRM_Core_DAO::buildOptionsContext.
+   * @see CRM_Core_DAO::buildOptionsContext
    * @param array $props
-   *   whatever is known about this bao object.
+   *   whatever is known about this bao object.
    *
-   * @return Array|bool
+   * @return array|bool
    */
   public static function buildOptions($fieldName, $context = NULL, $props = array()) {
     // If a given bao does not override this function
@@ -2163,7 +2179,7 @@ SELECT contact_id
   public function getOptionLabels() {
     $fields = $this->fields();
     if ($fields === NULL) {
-      throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
+      throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
     }
     foreach ($fields as $field) {
       $name = CRM_Utils_Array::value('name', $field);
@@ -2188,10 +2204,12 @@ SELECT contact_id
    */
   public static function buildOptionsContext($context = NULL) {
     $contexts = array(
-      'get' => "All options are returned, even if they are disabled. Labels are translated.",
-      'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
-      'search' => "Searchable options are returned. Labels are translated.",
-      'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
+      'get' => "get: all options are returned, even if they are disabled; labels are translated.",
+      'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
+      'search' => "search: searchable options are returned; labels are translated.",
+      'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
+      'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
+      'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
     );
     // Validation: enforce uniformity of this param
     if ($context !== NULL && !isset($contexts[$context])) {
@@ -2237,7 +2255,7 @@ SELECT contact_id
    *   alternative field name ('as') @todo- not actually used.
    * @param bool $returnSanitisedArray
    *   Return a sanitised array instead of a clause.
-   *  this is primarily so we can add filters @ the api level to the Query object based fields
+   *   this is primarily so we can add filters @ the api level to the Query object based fields
    *
    * @throws Exception
    *
@@ -2291,13 +2309,12 @@ SELECT contact_id
             }
             $escapedCriteria = array_map(array(
               'CRM_Core_DAO',
-              'escapeString'
+              'escapeString',
             ), $criteria);
             if (!$returnSanitisedArray) {
               return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
             }
             return $escapedCriteria;
-            break;
 
           // binary operators
 
@@ -2334,7 +2351,7 @@ SELECT contact_id
       'BETWEEN',
       'NOT BETWEEN',
       'IS NOT NULL',
-      'IS NULL'
+      'IS NULL',
     );
   }
 
@@ -2367,7 +2384,7 @@ SELECT contact_id
     }
 
     // the string is longer than the length and we need a uniq string
-    // for the same tablename we need the same uniq string everytime
+    // for the same tablename we need the same uniq string every time
     // hence we use md5 on the string, which is not random
     // we'll append 8 characters to the end of the tableName
     $md5string = substr(md5($string), 0, 8);