* @var null
* @deprecated
*/
- static $_nullObject = NULL;
+ public static $_nullObject = NULL;
/**
* @var array
* @deprecated
*/
- static $_nullArray = array();
+ public static $_nullArray = [];
- static $_dbColumnValueCache = NULL;
+ public static $_dbColumnValueCache = NULL;
const NOT_NULL = 1, IS_NULL = 2,
DB_DAO_NOTNULL = 128,
VALUE_SEPARATOR = "\ 1",
* test objects - this prevents world regions, countries etc from being added / deleted
* @var array
*/
- static $_testEntitiesToSkip = array();
+ public static $_testEntitiesToSkip = [];
/**
* The factory class for this application.
* @var object
*/
- static $_factory = NULL;
+ public static $_factory = NULL;
- static $_checkedSqlFunctionsExist = FALSE;
+ public static $_checkedSqlFunctionsExist = FALSE;
/**
* https://issues.civicrm.org/jira/browse/CRM-17748
* internal variable for DAO to hold per-query settings
+ * @var array
*/
- protected $_options = array();
+ protected $_options = [];
/**
* Class constructor.
$currentModes[] = 'ONLY_FULL_GROUP_BY';
}
if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
- $currentModes = array_merge(array('STRICT_TRANS_TABLES'), $currentModes);
+ $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
}
- CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
+ CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
}
CRM_Core_DAO::executeQuery('SET NAMES utf8');
- CRM_Core_DAO::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request::id(), 'String')));
+ CRM_Core_DAO::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request::id(), 'String']]);
}
/**
if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
$key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
unset($currentModes[$key]);
- CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
+ CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
}
}
$currentModes = CRM_Utils_SQL::getSqlModes();
if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
$currentModes[] = 'ONLY_FULL_GROUP_BY';
- CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
+ CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
}
}
}
elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
// FIXME: the fields() metadata is not specific enough
- $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
+ $depObject = CRM_Core_DAO::createTestObject($FKClassName, ['contact_type' => 'Organization']);
$this->$dbName = $depObject->id;
$depObject->free();
}
/**
* reset the various DB_DAO structures manually
*/
- $this->_query = array();
+ $this->_query = [];
$this->whereAdd();
$this->selectAdd();
$this->joinAdd();
public function keys() {
static $keys;
if (!isset($keys)) {
- $keys = array('id');
+ $keys = ['id'];
}
return $keys;
}
public function sequenceKey() {
static $sequenceKeys;
if (!isset($sequenceKeys)) {
- $sequenceKeys = array('id', TRUE);
+ $sequenceKeys = ['id', TRUE];
}
return $sequenceKeys;
}
* Array of CRM_Core_Reference_Interface
*/
public static function getReferenceColumns() {
- return array();
+ return [];
}
/**
public function table() {
$fields = $this->fields();
- $table = array();
+ $table = [];
if ($fields) {
foreach ($fields as $name => $value) {
$table[$value['name']] = $value['type'];
$maxLength = CRM_Utils_Array::value('maxlength', $field);
$size = CRM_Utils_Array::value('size', $field);
if ($maxLength || $size) {
- $attributes = array();
+ $attributes = [];
if ($maxLength) {
$attributes['maxlength'] = $maxLength;
}
$cols = 80;
}
- $attributes = array();
+ $attributes = [];
$attributes['rows'] = $rows;
$attributes['cols'] = $cols;
return $attributes;
return self::makeAttribute($field);
}
else {
- $attributes = array();
+ $attributes = [];
foreach ($fields as $name => $field) {
$attribute = self::makeAttribute($field);
if ($attribute) {
* true if constraint exists, false otherwise
*/
public static function checkConstraintExists($tableName, $constraint) {
- static $show = array();
+ static $show = [];
if (!array_key_exists($tableName, $show)) {
$query = "SHOW CREATE TABLE $tableName";
* @return bool
* true if CONSTRAINT keyword exists, false otherwise
*/
- public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
- $show = array();
+ public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
+ $show = [];
foreach ($tables as $tableName) {
if (!array_key_exists($tableName, $show)) {
$query = "SHOW CREATE TABLE $tableName";
* true if in format, false otherwise
*/
public static function checkFKConstraintInFormat($tableName, $columnName) {
- static $show = array();
+ static $show = [];
if (!array_key_exists($tableName, $show)) {
$query = "SHOW CREATE TABLE $tableName";
SHOW TABLES
LIKE %1
";
- $params = array(1 => array($tableName, 'String'));
+ $params = [1 => [$tableName, 'String']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$result = $dao->fetch() ? TRUE : FALSE;
* @return array
*/
public function fetchAll() {
- $result = array();
+ $result = [];
while ($this->fetch()) {
$result[] = $this->toArray();
}
* Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
*/
public function fetchMap($keyColumn, $valueColumn) {
- $result = array();
+ $result = [];
while ($this->fetch()) {
$result[$this->{$keyColumn}] = $this->{$valueColumn};
}
$cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
if (self::$_dbColumnValueCache === NULL) {
- self::$_dbColumnValueCache = array();
+ self::$_dbColumnValueCache = [];
}
if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
* @return CRM_Core_DAO
* Object that points to an unbuffered result set
*/
- static public function executeUnbufferedQuery(
+ public static function executeUnbufferedQuery(
$query,
- $params = array(),
+ $params = [],
$abort = TRUE,
$daoName = NULL,
$freeDAO = FALSE,
$freeDAO,
$i18nRewrite,
$trapException,
- array('result_buffering' => 0)
+ ['result_buffering' => 0]
);
}
*/
public static function &executeQuery(
$query,
- $params = array(),
+ $params = [],
$abort = TRUE,
$daoName = NULL,
$freeDAO = FALSE,
$i18nRewrite = TRUE,
$trapException = FALSE,
- $options = array()
+ $options = []
) {
$queryStr = self::composeQuery($query, $params, $abort);
*/
public function isValidOption($options) {
$isValid = FALSE;
- $validOptions = array(
+ $validOptions = [
'result_buffering',
'persistent',
'ssl',
'portability',
- );
+ ];
if (empty($options)) {
return $isValid;
*/
public static function &singleValueQuery(
$query,
- $params = array(),
+ $params = [],
$abort = TRUE,
$i18nRewrite = TRUE
) {
* @throws Exception
*/
public static function composeQuery($query, $params, $abort = TRUE) {
- $tr = array();
+ $tr = [];
foreach ($params as $key => $item) {
if (is_numeric($key)) {
if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
$fields = $object->fields();
if (!is_array($fieldsFix)) {
- $fieldsToPrefix = array();
- $fieldsToSuffix = array();
- $fieldsToReplace = array();
+ $fieldsToPrefix = [];
+ $fieldsToSuffix = [];
+ $fieldsToReplace = [];
}
if (!empty($fieldsFix['prefix'])) {
$fieldsToPrefix = $fieldsFix['prefix'];
}
}
$newObject->save();
+ if (!empty($newData['custom'])) {
+ CRM_Core_BAO_CustomValueTable::store($newData['custom'], $newObject::getTableName(), $newObject->id);
+ }
CRM_Utils_Hook::post('create', CRM_Core_DAO_AllCoreTables::getBriefName($daoName), $newObject->id, $newObject);
}
*
* @return CRM_Core_DAO|null
*/
- public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
+ public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
$object = new $daoName();
$object->id = $fromId;
* @return array
*/
public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
- $contactIDs = array();
+ $contactIDs = [];
if (empty($componentIDs)) {
return $contactIDs;
$object->find();
while ($object->fetch()) {
- $defaults = array();
+ $defaults = [];
self::storeValues($object, $defaults);
$details[$object->id] = $defaults;
}
if (!defined('CIVICRM_DSN')) {
// See http://php.net/manual/en/mysqli.real-escape-string.php for the
// list of characters mysqli_real_escape_string escapes.
- $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
- $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
+ $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
+ $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
return str_replace($search, $replace, $string);
}
$_dao = new CRM_Core_DAO();
return $default;
}
- $escapes = array_map(array($_dao, 'escape'), $strings);
+ $escapes = array_map([$_dao, 'escape'], $strings);
return '"' . implode('","', $escapes) . '"';
}
// card characters and could come in via sortByCharacter
// note that mysql does not escape these characters
if ($string && in_array($string,
- array('%', '_', '%%', '_%')
+ ['%', '_', '%%', '_%']
)
) {
return '\\' . $string;
*/
public static function createTestObject(
$daoName,
- $params = array(),
+ $params = [],
$numObjects = 1,
$createOnly = FALSE
) {
$config->backtrace = TRUE;
static $counter = 0;
- CRM_Core_DAO::$_testEntitiesToSkip = array(
+ CRM_Core_DAO::$_testEntitiesToSkip = [
'CRM_Core_DAO_Worldregion',
'CRM_Core_DAO_StateProvince',
'CRM_Core_DAO_Country',
'CRM_Core_DAO_Domain',
'CRM_Financial_DAO_FinancialType',
//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
- );
+ ];
// Prefer to instantiate BAO's instead of DAO's (when possible)
// so that assignTestValue()/assignTestFK() can be overloaded.
* @param string $daoName
* @param array $params
*/
- public static function deleteTestObjects($daoName, $params = array()) {
+ public static function deleteTestObjects($daoName, $params = []) {
//this is a test function also backtrace is set for the test suite it sometimes unsets itself
// so we re-set here in case
$config = CRM_Core_Config::singleton();
$object = new $daoName();
$object->id = CRM_Utils_Array::value('id', $params);
- $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
+ // array(array(0 => $daoName, 1 => $daoParams))
+ $deletions = [];
if ($object->find(TRUE)) {
$fields = $object->fields();
// to make this test process pass - line below makes pass for now
&& $dbName != 'member_of_contact_id'
) {
- $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
+ // x
+ $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
}
}
}
if ($printDAO) {
global $_DB_DATAOBJECT;
- $q = array();
+ $q = [];
foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
$q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
}
* @return array<CRM_Core_Reference_Interface>
*/
public static function createReferenceColumns($className) {
- $result = array();
+ $result = [];
$fields = $className::fields();
foreach ($fields as $field) {
if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
public function findReferences() {
$links = self::getReferencesToTable(static::getTableName());
- $occurrences = array();
+ $occurrences = [];
foreach ($links as $refSpec) {
/** @var $refSpec CRM_Core_Reference_Interface */
$daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
public function getReferenceCounts() {
$links = self::getReferencesToTable(static::getTableName());
- $counts = array();
+ $counts = [];
foreach ($links as $refSpec) {
/** @var $refSpec CRM_Core_Reference_Interface */
$count = $refSpec->getReferenceCount($this);
* foreign key reference to $tableName, and the column where the key appears.
*/
public static function getReferencesToTable($tableName) {
- $refsFound = array();
+ $refsFound = [];
foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
$links = $daoClassName::getReferenceColumns();
$daoTableName = $daoClassName::getTableName();
$customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
$customValueTables->find();
while ($customValueTables->fetch()) {
- $cidRefs[$customValueTables->table_name] = array('entity_id');
+ $cidRefs[$customValueTables->table_name] = ['entity_id'];
}
}
}
}
-
/**
* Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
*
* This is relevant where we want to offer both the ID field and the label field
* as an option, e.g. search builder.
*
- * It is currently limited for optionGroupName for purposes keeping the scope of the
+ * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
* change small, but is appropriate for other sorts of pseudoconstants.
*
* @param array $fields
*/
- protected static function appendPseudoConstantsToFields(&$fields) {
+ public static function appendPseudoConstantsToFields(&$fields) {
foreach ($fields as $field) {
- if (!empty($field['pseudoconstant']) && !empty($field['pseudoconstant']['optionGroupName'])) {
- $fields[$field['pseudoconstant']['optionGroupName']] = array(
- 'title' => CRM_Core_BAO_OptionGroup::getTitleByName($field['pseudoconstant']['optionGroupName']),
- 'name' => $field['pseudoconstant']['optionGroupName'],
- 'data_type' => CRM_Utils_Type::T_STRING,
- );
+ if (!empty($field['pseudoconstant'])) {
+ $pseudoConstant = $field['pseudoconstant'];
+ if (!empty($pseudoConstant['optionGroupName'])) {
+ $fields[$pseudoConstant['optionGroupName']] = [
+ 'title' => CRM_Core_BAO_OptionGroup::getTitleByName($pseudoConstant['optionGroupName']),
+ 'name' => $pseudoConstant['optionGroupName'],
+ 'data_type' => CRM_Utils_Type::T_STRING,
+ 'is_pseudofield_for' => $field['name'],
+ ];
+ }
+ // We restrict to id + name + FK as we are extending this a bit, but cautiously.
+ elseif (
+ !empty($field['FKClassName'])
+ && CRM_Utils_Array::value('keyColumn', $pseudoConstant) === 'id'
+ && CRM_Utils_Array::value('labelColumn', $pseudoConstant) === 'name'
+ ) {
+ $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
+ // This if is just an extra caution when adding change.
+ if (!isset($fields[$pseudoFieldName])) {
+ $daoName = $field['FKClassName'];
+ $fkFields = $daoName::fields();
+ foreach ($fkFields as $fkField) {
+ if ($fkField['name'] === $pseudoConstant['labelColumn']) {
+ $fields[$pseudoFieldName] = [
+ 'name' => $pseudoFieldName,
+ 'is_pseudofield_for' => $field['name'],
+ 'title' => $fkField['title'],
+ 'data_type' => $fkField['type'],
+ 'where' => $field['where'],
+ ];
+ }
+ }
+ }
+ }
}
}
}
*
* @return array|bool
*/
- public static function buildOptions($fieldName, $context = NULL, $props = array()) {
+ public static function buildOptions($fieldName, $context = NULL, $props = []) {
// If a given bao does not override this function
$baoName = get_called_class();
return CRM_Core_PseudoConstant::get($baoName, $fieldName, $props, $context);
* @return array
*/
public static function buildOptionsContext($context = NULL) {
- $contexts = array(
+ $contexts = [
'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])) {
throw new Exception("'$context' is not a valid context for buildOptions.");
// ternary operators
case 'BETWEEN':
case 'NOT BETWEEN':
- if (empty($criteria[0]) || empty($criteria[1])) {
+ if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))|| (empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
throw new Exception("invalid criteria for $operator");
}
if (!$returnSanitisedArray) {
return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
}
else {
- return NULL; // not yet implemented (tests required to implement)
+ // not yet implemented (tests required to implement)
+ return NULL;
}
break;
if (empty($criteria)) {
throw new Exception("invalid criteria for $operator");
}
- $escapedCriteria = array_map(array(
+ $escapedCriteria = array_map([
'CRM_Core_DAO',
'escapeString',
- ), $criteria);
+ ], $criteria);
if (!$returnSanitisedArray) {
return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
}
return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
}
else {
- return NULL; // not yet implemented (tests required to implement)
+ // not yet implemented (tests required to implement)
+ return NULL;
}
}
}
* @return array
*/
public static function acceptedSQLOperators() {
- return array(
+ return [
'=',
'<=',
'>=',
'NOT BETWEEN',
'IS NOT NULL',
'IS NULL',
- );
+ ];
}
/**
* @return array
*/
public function addSelectWhereClause() {
- $clauses = array();
+ $clauses = [];
$fields = $this->fields();
foreach ($fields as $fieldName => $field) {
// Clause for contact-related entities like Email, Relationship, etc.
}
// Clause for an entity_table/entity_id combo
if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
- $relatedClauses = array();
+ $relatedClauses = [];
$relatedEntities = $this->buildOptions('entity_table', 'get');
foreach ((array) $relatedEntities as $table => $ent) {
if (!empty($ent)) {
if ($tableAlias === NULL) {
$tableAlias = $bao->tableName();
}
- $clauses = array();
+ $clauses = [];
foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
$clauses[$field] = NULL;
if ($vals) {
* @return bool
*/
public static function requireSafeDBName($database) {
- $matches = array();
+ $matches = [];
preg_match(
"/^[\w\-]*[a-z]+[\w\-]*$/i",
$database,
}
switch ($serializationType) {
case self::SERIALIZE_SEPARATOR_BOOKEND:
- return $value === array() ? '' : CRM_Utils_Array::implodePadded($value);
+ return $value === [] ? '' : CRM_Utils_Array::implodePadded($value);
case self::SERIALIZE_SEPARATOR_TRIMMED:
return is_array($value) ? implode(self::VALUE_SEPARATOR, $value) : $value;
return NULL;
}
if ($value === '') {
- return array();
+ return [];
}
switch ($serializationType) {
case self::SERIALIZE_SEPARATOR_BOOKEND:
return explode(self::VALUE_SEPARATOR, trim($value));
case self::SERIALIZE_JSON:
- return strlen($value) ? json_decode($value, TRUE) : array();
+ return strlen($value) ? json_decode($value, TRUE) : [];
case self::SERIALIZE_PHP:
- return strlen($value) ? unserialize($value) : array();
+ return strlen($value) ? unserialize($value) : [];
case self::SERIALIZE_COMMA:
return explode(',', trim(str_replace(', ', '', $value)));
}
}
+ /**
+ * @return array
+ */
+ public static function getEntityRefFilters() {
+ return [];
+ }
+
/**
* Get exportable fields with pseudoconstants rendered as an extra field.
*