* @inheritDoc
*/
protected function buildWhereClause() {
- $filters = array();
+ $filters = [];
foreach ($this->where as $key => $value) {
$table_name = NULL;
$column_name = NULL;
// Legacy support for old filter syntax per the test contract.
// (Convert the style to the later one & then deal with them).
$filterArray = explode('.', $key);
- $value = array($filterArray[1] => $value);
+ $value = [$filterArray[1] => $value];
$key = 'filters';
}
foreach ($value as $filterKey => $filterValue) {
if (substr($filterKey, -4, 4) == 'high') {
$key = substr($filterKey, 0, -5);
- $value = array('<=' => $filterValue);
+ $value = ['<=' => $filterValue];
}
if (substr($filterKey, -3, 3) == 'low') {
$key = substr($filterKey, 0, -4);
- $value = array('>=' => $filterValue);
+ $value = ['>=' => $filterValue];
}
if ($filterKey == 'is_current' || $filterKey == 'isCurrent') {
}
$operator = is_array($value) ? \CRM_Utils_Array::first(array_keys($value)) : NULL;
if (!in_array($operator, \CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
- $value = array('=' => $value);
+ $value = ['=' => $value];
}
$filters[$key] = \CRM_Core_DAO::createSQLFilter("{$table_name}.{$column_name}", $value);
}
$orGroups = array_map('trim', explode(',', $orGroups));
}
if (!is_array(\CRM_Utils_Array::first($orGroups))) {
- $orGroups = array($orGroups);
+ $orGroups = [$orGroups];
}
foreach ($orGroups as $orGroup) {
- $orClause = array();
+ $orClause = [];
foreach ($orGroup as $key) {
if (!isset($filters[$key])) {
throw new \CiviCRM_API3_Exception("'$key' specified in OR group but not added to params");
protected function getFields() {
require_once 'api/v3/Generic.php';
// Call this function directly instead of using the api wrapper to force unique field names off
- $apiSpec = \civicrm_api3_generic_getfields(array(
+ $apiSpec = \civicrm_api3_generic_getfields([
'entity' => $this->entity,
'version' => 3,
- 'params' => array('action' => 'get'),
- ), FALSE);
+ 'params' => ['action' => 'get'],
+ ], FALSE);
return $apiSpec['values'];
}
foreach ($this->apiFieldSpec as $field) {
if (
$fieldName == \CRM_Utils_Array::value('uniqueName', $field) ||
- array_search($fieldName, \CRM_Utils_Array::value('api.aliases', $field, array())) !== FALSE
+ array_search($fieldName, \CRM_Utils_Array::value('api.aliases', $field, [])) !== FALSE
) {
return $field;
}
* @return array<string>
*/
public static function allEvents() {
- return array(
+ return [
self::AUTHORIZE,
self::EXCEPTION,
self::PREPARE,
self::RESOLVE,
self::RESPOND,
- );
+ ];
}
/**
* @param \Exception|NULL $previous
* A previous exception which caused this new exception.
*/
- public function __construct($message, $extraParams = array(), \Exception $previous = NULL) {
+ public function __construct($message, $extraParams = [], \Exception $previous = NULL) {
parent::__construct($message, \API_Exception::NOT_IMPLEMENTED, $extraParams, $previous);
}
* @param \Exception|NULL $previous
* A previous exception which caused this new exception.
*/
- public function __construct($message, $extraParams = array(), \Exception $previous = NULL) {
+ public function __construct($message, $extraParams = [], \Exception $previous = NULL) {
parent::__construct($message, \API_Exception::UNAUTHORIZED, $extraParams, $previous);
}
* @param array $defaultParams
* Default values to merge into any API calls.
*/
- public function __construct($defaultParams = array()) {
+ public function __construct($defaultParams = []) {
global $civicrm_root;
$this->root = $civicrm_root;
$this->settingsPath = defined('CIVICRM_SETTINGS_PATH') ? CIVICRM_SETTINGS_PATH : NULL;
* @param array $params
* @return ExternalBatch
*/
- public function addCall($entity, $action, $params = array()) {
+ public function addCall($entity, $action, $params = []) {
$params = array_merge($this->defaultParams, $params);
- $this->apiCalls[] = array(
+ $this->apiCalls[] = [
'entity' => $entity,
'action' => $action,
'params' => $params,
- );
+ ];
return $this;
}
if (!$process->isRunning()) {
$parsed = json_decode($process->getOutput(), TRUE);
if ($process->getExitCode() || $parsed === NULL) {
- $this->apiResults[] = array(
+ $this->apiResults[] = [
'is_error' => 1,
'error_message' => 'External API returned malformed response.',
- 'trace' => array(
+ 'trace' => [
'code' => $process->getExitCode(),
'stdout' => $process->getOutput(),
'stderr' => $process->getErrorOutput(),
- ),
- );
+ ],
+ ];
}
else {
$this->apiResults[] = $parsed;
* @throws \CRM_Core_Exception
*/
public function createProcess($apiCall) {
- $parts = array();
+ $parts = [];
if (defined('CIVICRM_TEST') && CIVICRM_TEST) {
// When testing, civicrm.settings.php may rely on $_CV, which is only
}
$command = implode(" ", $parts);
- $env = array_merge($this->env, array(
+ $env = array_merge($this->env, [
'CIVICRM_SETTINGS' => $this->settingsPath,
- ));
+ ]);
return new Process($command, $this->root, $env);
}
* @param array $apiProviders
* Array of ProviderInterface.
*/
- public function __construct($dispatcher, $apiProviders = array()) {
+ public function __construct($dispatcher, $apiProviders = []) {
$this->apiProviders = $apiProviders;
$this->dispatcher = $dispatcher;
}
if (!$resolveEvent->getApiProvider()) {
throw new \Civi\API\Exception\NotImplementedException("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
}
- return array($resolveEvent->getApiProvider(), $apiRequest);
+ return [$resolveEvent->getApiProvider(), $apiRequest];
}
/**
*/
public function getEntityNames($version) {
// Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
- $entityNames = array();
+ $entityNames = [];
foreach ($this->getApiProviders() as $provider) {
/** @var ProviderInterface $provider */
$entityNames = array_merge($entityNames, $provider->getEntityNames($version));
*/
public function getActionNames($version, $entity) {
// Question: Would it better to eliminate $this->apiProviders and just use $this->dispatcher?
- $actionNames = array();
+ $actionNames = [];
foreach ($this->getApiProviders() as $provider) {
/** @var ProviderInterface $provider */
$actionNames = array_merge($actionNames, $provider->getActionNames($version, $entity));
* API response.
*/
public function formatException($e, $apiRequest) {
- $data = array();
+ $data = [];
if (!empty($apiRequest['params']['debug'])) {
$data['trace'] = $e->getTraceAsString();
}
* API response.
*/
public function formatPearException($e, $apiRequest) {
- $data = array();
+ $data = [];
$error = $e->getCause();
if ($error instanceof \DB_Error) {
$data["error_code"] = \DB::errorMessage($error->getCode());
// Using a high priority allows adhoc implementations
// to override standard implementations -- which is
// handy for testing/mocking.
- return array(
- Events::RESOLVE => array(
- array('onApiResolve', Events::W_EARLY),
- ),
- Events::AUTHORIZE => array(
- array('onApiAuthorize', Events::W_EARLY),
- ),
- );
+ return [
+ Events::RESOLVE => [
+ ['onApiResolve', Events::W_EARLY],
+ ],
+ Events::AUTHORIZE => [
+ ['onApiAuthorize', Events::W_EARLY],
+ ],
+ ];
}
/**
* @var array (string $name => array('perm' => string, 'callback' => callable))
*/
- protected $actions = array();
+ protected $actions = [];
/**
* @var string
* @return AdhocProvider
*/
public function addAction($name, $perm, $callback) {
- $this->actions[strtolower($name)] = array(
+ $this->actions[strtolower($name)] = [
'perm' => $perm,
'callback' => $callback,
- );
+ ];
return $this;
}
* @return array
*/
public function getEntityNames($version) {
- return array($this->entity);
+ return [$this->entity];
}
/**
return array_keys($this->actions);
}
else {
- return array();
+ return [];
}
}
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::RESOLVE => array(
- array('onApiResolve', Events::W_MIDDLE),
- ),
- );
+ return [
+ Events::RESOLVE => [
+ ['onApiResolve', Events::W_MIDDLE],
+ ],
+ ];
}
/**
/**
*/
public function __construct() {
- $this->cache = array();
+ $this->cache = [];
}
/**
* @return array
*/
public function getEntityNames($version) {
- $entities = array();
+ $entities = [];
$include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
#$include_dirs = array(dirname(__FILE__). '/../../');
foreach ($include_dirs as $include_dir) {
$api_dir = implode(DIRECTORY_SEPARATOR,
- array($include_dir, 'api', 'v' . $version));
+ [$include_dir, 'api', 'v' . $version]);
if (!is_dir($api_dir)) {
continue;
}
}
}
}
- $entities = array_diff($entities, array('Generic'));
+ $entities = array_diff($entities, ['Generic']);
$entities = array_unique($entities);
sort($entities);
$entity = _civicrm_api_get_camel_name($entity);
$entities = $this->getEntityNames($version);
if (!in_array($entity, $entities)) {
- return array();
+ return [];
}
$this->loadEntity($entity, $version);
$functions = get_defined_functions();
- $actions = array();
+ $actions = [];
$prefix = 'civicrm_api' . $version . '_' . _civicrm_api_get_entity_name_from_camel($entity) . '_';
$prefixGeneric = 'civicrm_api' . $version . '_generic_';
foreach ($functions['user'] as $fct) {
// someone already loaded the appropriate file
// FIXME: This has the affect of masking bugs in load order; this is
// included to provide bug-compatibility.
- $this->cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
+ $this->cache[$cachekey] = ['function' => $stdFunction, 'is_generic' => FALSE];
return $this->cache[$cachekey];
}
- $stdFiles = array(
+ $stdFiles = [
// By convention, the $camelName.php is more likely to contain the
// function, so test it first
'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
- );
+ ];
foreach ($stdFiles as $stdFile) {
if (\CRM_Utils_File::isIncludable($stdFile)) {
require_once $stdFile;
if (function_exists($stdFunction)) {
- $this->cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
+ $this->cache[$cachekey] = ['function' => $stdFunction, 'is_generic' => FALSE];
return $this->cache[$cachekey];
}
}
require_once 'api/v3/Generic.php';
# $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
$genericFunction = $this->getFunctionName('generic', $apiRequest['action'], $apiRequest['version']);
- $genericFiles = array(
+ $genericFiles = [
// By convention, the Generic.php is more likely to contain the
// function, so test it first
'api/v' . $apiRequest['version'] . '/Generic.php',
'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
- );
+ ];
foreach ($genericFiles as $genericFile) {
if (\CRM_Utils_File::isIncludable($genericFile)) {
require_once $genericFile;
if (function_exists($genericFunction)) {
- $this->cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
+ $this->cache[$cachekey] = ['function' => $genericFunction, 'is_generic' => TRUE];
return $this->cache[$cachekey];
}
}
}
- $this->cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
+ $this->cache[$cachekey] = ['function' => FALSE, 'is_generic' => FALSE];
return $this->cache[$cachekey];
}
}
// Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
- $loaded_files = array(); // array($relativeFilePath => TRUE)
+ $loaded_files = []; // array($relativeFilePath => TRUE)
$include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
foreach ($include_dirs as $include_dir) {
- foreach (array($camelName, 'Generic') as $name) {
+ foreach ([$camelName, 'Generic'] as $name) {
$action_dir = implode(DIRECTORY_SEPARATOR,
- array($include_dir, 'api', "v${version}", $name));
+ [$include_dir, 'api', "v${version}", $name]);
if (!is_dir($action_dir)) {
continue;
}
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::RESOLVE => array(
+ return [
+ Events::RESOLVE => [
// TODO decide if we really want to override others
- array('onApiResolve', Events::W_EARLY),
- ),
- Events::AUTHORIZE => array(
+ ['onApiResolve', Events::W_EARLY],
+ ],
+ Events::AUTHORIZE => [
// TODO decide if we really want to override others
- array('onApiAuthorize', Events::W_EARLY),
- ),
- );
+ ['onApiAuthorize', Events::W_EARLY],
+ ],
+ ];
}
/**
*/
public function __construct($apiKernel) {
$this->apiKernel = $apiKernel;
- $this->actions = array(
- 'Entity' => array('get', 'getactions'),
- '*' => array('getactions'), // 'getfields'
- );
+ $this->actions = [
+ 'Entity' => ['get', 'getactions'],
+ '*' => ['getactions'], // 'getfields'
+ ];
}
/**
* @return array
*/
public function getEntityNames($version) {
- return array('Entity');
+ return ['Entity'];
}
/**
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::RESOLVE => array(
- array('onApiResolve', Events::W_MIDDLE),
- ),
- Events::AUTHORIZE => array(
- array('onApiAuthorize', Events::W_MIDDLE),
- ),
- );
+ return [
+ Events::RESOLVE => [
+ ['onApiResolve', Events::W_MIDDLE],
+ ],
+ Events::AUTHORIZE => [
+ ['onApiAuthorize', Events::W_MIDDLE],
+ ],
+ ];
}
/**
* @param array $records
* List of mock records to be read/updated by API calls.
*/
- public function __construct($version, $entity, $fields, $perms = array(), $records = array()) {
+ public function __construct($version, $entity, $fields, $perms = [], $records = []) {
parent::__construct($version, $entity);
- $perms = array_merge(array(
+ $perms = array_merge([
'create' => \CRM_Core_Permission::ALWAYS_ALLOW_PERMISSION,
'get' => \CRM_Core_Permission::ALWAYS_ALLOW_PERMISSION,
'delete' => \CRM_Core_Permission::ALWAYS_ALLOW_PERMISSION,
- ), $perms);
+ ], $perms);
- $this->records = \CRM_Utils_Array::index(array('id'), $records);
+ $this->records = \CRM_Utils_Array::index(['id'], $records);
$this->fields = $fields;
- $this->addAction('create', $perms['create'], array($this, 'doCreate'));
- $this->addAction('get', $perms['get'], array($this, 'doGet'));
- $this->addAction('delete', $perms['delete'], array($this, 'doDelete'));
+ $this->addAction('create', $perms['create'], [$this, 'doCreate']);
+ $this->addAction('get', $perms['get'], [$this, 'doGet']);
+ $this->addAction('delete', $perms['delete'], [$this, 'doDelete']);
}
/**
}
else {
$id = max(array_keys($this->records)) + 1;
- $this->records[$id] = array();
+ $this->records[$id] = [];
}
if (!isset($this->records[$id])) {
if ($id && isset($this->records[$id])) {
unset($this->records[$id]);
}
- return civicrm_api3_create_success(array());
+ return civicrm_api3_create_success([]);
}
}
$version = \CRM_Utils_Array::value('version', $params);
switch ($version) {
default:
- $apiRequest = array();
+ $apiRequest = [];
$apiRequest['id'] = self::$nextId++;
$apiRequest['version'] = (int) $version;
$apiRequest['params'] = $params;
return $apiRequest;
case 4:
- $callable = array("Civi\\Api4\\$entity", $action);
+ $callable = ["Civi\\Api4\\$entity", $action];
if (!is_callable($callable)) {
throw new Exception\NotImplementedException("API ($entity, $action) does not exist (join the API team and implement it!)");
}
* @var string
*/
protected $entity;
- public $select = array();
- public $where = array();
- public $orderBy = array();
+ public $select = [];
+ public $where = [];
+ public $orderBy = [];
public $limit;
public $offset;
/**
* @var array
*/
- protected $selectFields = array();
+ protected $selectFields = [];
/**
* @var bool
*/
/**
* @var array
*/
- protected $joins = array();
+ protected $joins = [];
/**
* @var array
*/
/**
* @var array
*/
- protected $aclFields = array();
+ protected $aclFields = [];
/**
* @var string|bool
*/
$this->query->limit($this->limit, $this->offset);
}
- $result_entities = array();
+ $result_entities = [];
$result_dao = \CRM_Core_DAO::executeQuery($this->query->toSQL());
while ($result_dao->fetch()) {
$result_dao->free();
return (int) $result_dao->c;
}
- $result_entities[$result_dao->id] = array();
+ $result_entities[$result_dao->id] = [];
foreach ($this->selectFields as $column => $alias) {
$returnName = $alias;
$alias = str_replace('.', '_', $alias);
// Add acl condition
$joinCondition = array_merge(
- array("$prev.$fk = $tableAlias.$keyColumn"),
+ ["$prev.$fk = $tableAlias.$keyColumn"],
$this->getAclClause($tableAlias, \_civicrm_api3_get_BAO($fkField['FKApiName']), $subStack)
);
$fkField = &$fkField['FKApiSpec'][$fieldName];
$prev = $tableAlias;
}
- return array($tableAlias, $fieldName);
+ return [$tableAlias, $fieldName];
}
/**
$tableName = $customField["table_name"];
$columnName = $customField["column_name"];
$tableAlias = "{$baseTable}_to_$tableName";
- $this->join($side, $tableName, $tableAlias, array("`$tableAlias`.entity_id = `$baseTable`.id"));
- return array($tableAlias, $columnName);
+ $this->join($side, $tableName, $tableAlias, ["`$tableAlias`.entity_id = `$baseTable`.id"]);
+ return [$tableAlias, $columnName];
}
/**
$entity = $spec[$name]['FKApiName'];
$spec = $spec[$name]['FKApiSpec'];
}
- $params = array($fieldName => $value);
+ $params = [$fieldName => $value];
\_civicrm_api3_validate_fields($entity, 'get', $params, $spec);
$value = $params[$fieldName];
}
return TRUE;
}
// Build an array of params that relate to the joined entity
- $params = array(
+ $params = [
'version' => 3,
- 'return' => array(),
+ 'return' => [],
'check_permissions' => $this->checkPermissions,
- );
+ ];
$prefix = implode('.', $fieldStack) . '.';
$len = strlen($prefix);
foreach ($this->select as $key => $ret) {
* @param array $stack
* @return array
*/
- protected function getAclClause($tableAlias, $baoName, $stack = array()) {
+ protected function getAclClause($tableAlias, $baoName, $stack = []) {
if (!$this->checkPermissions) {
- return array();
+ return [];
}
// Prevent (most) redundant acl sub clauses if they have already been applied to the main entity.
// FIXME: Currently this only works 1 level deep, but tracking through multiple joins would increase complexity
// and just doing it for the first join takes care of most acl clause deduping.
if (count($stack) === 1 && in_array($stack[0], $this->aclFields)) {
- return array();
+ return [];
}
$clauses = $baoName::getSelectWhereClause($tableAlias);
if (!$stack) {
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::PREPARE => array(
- array('onApiPrepare', Events::W_MIDDLE),
- array('onApiPrepare_validate', Events::W_LATE),
- ),
- );
+ return [
+ Events::PREPARE => [
+ ['onApiPrepare', Events::W_MIDDLE],
+ ['onApiPrepare_validate', Events::W_LATE],
+ ],
+ ];
}
/**
* @return array
*/
public function getDefaults($fields) {
- $defaults = array();
+ $defaults = [];
foreach ($fields as $field => $values) {
if (isset($values['api.default'])) {
* @return array
*/
public function getRequired($fields) {
- $required = array('version');
+ $required = ['version'];
foreach ($fields as $field => $values) {
if (!empty($values['api.required'])) {
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::RESPOND => array('onApiRespond', Events::W_EARLY),
- );
+ return [
+ Events::RESPOND => ['onApiRespond', Events::W_EARLY],
+ ];
}
/**
// We don't need to worry about nested api in the getfields/getoptions
// actions, so just return immediately.
- if (in_array($action, array('getfields', 'getfield', 'getoptions'))) {
+ if (in_array($action, ['getfields', 'getfield', 'getoptions'])) {
return;
}
// $result to be a recursive array
// $result['values'][0] = $result;
$oldResult = $result;
- $result = array('values' => array(0 => $oldResult));
+ $result = ['values' => [0 => $oldResult]];
}
foreach ($params as $field => $newparams) {
if ((is_array($newparams) || $newparams === 1) && $field <> 'api.has_parent' && substr($field, 0, 3) == 'api') {
// 'api.participant.delete' => 1 is a valid options - handle 1
// instead of an array
if ($newparams === 1) {
- $newparams = array('version' => $version);
+ $newparams = ['version' => $version];
}
// can be api_ or api.
$separator = $field[3];
$subAPI = explode($separator, $field);
$subaction = empty($subAPI[2]) ? $action : $subAPI[2];
- $subParams = array(
+ $subParams = [
'debug' => \CRM_Utils_Array::value('debug', $params),
- );
+ ];
$subEntity = _civicrm_api_get_entity_name_from_camel($subAPI[1]);
// Hard coded list of entitys that have fields starting api_ and shouldn't be automatically
// deemed to be chained API calls
- $skipList = array(
- 'SmsProvider' => array('type', 'url', 'params'),
- 'Job' => array('prefix', 'entity', 'action'),
- 'Contact' => array('key'),
- );
+ $skipList = [
+ 'SmsProvider' => ['type', 'url', 'params'],
+ 'Job' => ['prefix', 'entity', 'action'],
+ 'Contact' => ['key'],
+ ];
if (isset($skipList[$entity]) && in_array($subEntity, $skipList[$entity])) {
continue;
}
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::AUTHORIZE => array(
- array('onApiAuthorize', Events::W_EARLY),
- ),
- );
+ return [
+ Events::AUTHORIZE => [
+ ['onApiAuthorize', Events::W_EARLY],
+ ],
+ ];
}
/**
$apiRequest = $event->getApiRequest();
if ($apiRequest['version'] == 3 && \CRM_Utils_String::convertStringToCamel($apiRequest['entity']) == $this->entityName && in_array(strtolower($apiRequest['action']), $this->actions)) {
if (isset($apiRequest['params']['field_name'])) {
- $fldIdx = \CRM_Utils_Array::index(array('field_name'), $this->getCustomFields());
+ $fldIdx = \CRM_Utils_Array::index(['field_name'], $this->getCustomFields());
if (empty($fldIdx[$apiRequest['params']['field_name']])) {
throw new \Exception("Failed to map custom field to entity table");
}
\CRM_Core_Transaction::create(TRUE)->run(function($tx) use ($entity, $action, $entityId, &$exception, $self) {
$tx->rollback(); // Just to be safe.
- $params = array(
+ $params = [
'version' => 3,
'check_permissions' => 1,
'id' => $entityId,
- );
+ ];
$result = $self->kernel->run($entity, $self->getDelegatedAction($action), $params);
if ($result['is_error'] || empty($result['values'])) {
- $exception = new \Civi\API\Exception\UnauthorizedException("Authorization failed on ($entity,$entityId)", array(
+ $exception = new \Civi\API\Exception\UnauthorizedException("Authorization failed on ($entity,$entityId)", [
'cause' => $result,
- ));
+ ]);
}
});
* @throws \Exception
*/
public function getDelegate($id) {
- $query = \CRM_Core_DAO::executeQuery($this->lookupDelegateSql, array(
- 1 => array($id, 'Positive'),
- ));
+ $query = \CRM_Core_DAO::executeQuery($this->lookupDelegateSql, [
+ 1 => [$id, 'Positive'],
+ ]);
if ($query->fetch()) {
if (!preg_match('/^civicrm_value_/', $query->entity_table)) {
// A normal attachment directly on its entity.
- return array($query->is_valid, $query->entity_table, $query->entity_id);
+ return [$query->is_valid, $query->entity_table, $query->entity_id];
}
// Ex: Translate custom-field table ("civicrm_value_foo_4") to
// entity table ("civicrm_activity").
- $tblIdx = \CRM_Utils_Array::index(array('table_name'), $this->getCustomFields());
+ $tblIdx = \CRM_Utils_Array::index(['table_name'], $this->getCustomFields());
if (isset($tblIdx[$query->entity_table])) {
- return array($query->is_valid, $tblIdx[$query->entity_table]['entity_table'], $query->entity_id);
+ return [$query->is_valid, $tblIdx[$query->entity_table]['entity_table'], $query->entity_id];
}
throw new \Exception('Failed to lookup entity table for custom field.');
}
else {
- return array(FALSE, NULL, NULL);
+ return [FALSE, NULL, NULL];
}
}
*/
public function getCustomFields() {
$query = \CRM_Core_DAO::executeQuery($this->lookupCustomFieldSql);
- $rows = array();
+ $rows = [];
while ($query->fetch()) {
- $rows[] = array(
+ $rows[] = [
'field_name' => $query->field_name,
'table_name' => $query->table_name,
'extends' => $query->extends,
'entity_table' => \CRM_Core_BAO_CustomGroup::getTableNameByEntityName($query->extends),
- );
+ ];
}
return $rows;
}
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::PREPARE => array('onApiPrepare', Events::W_MIDDLE),
- );
+ return [
+ Events::PREPARE => ['onApiPrepare', Events::W_MIDDLE],
+ ];
}
/**
// on multi-lang sites based on request and civicrm_uf_match
if ($multiLang) {
$config = \CRM_Core_Config::singleton();
- $languageLimit = array();
+ $languageLimit = [];
if (isset($config->languageLimit) and $config->languageLimit) {
$languageLimit = $config->languageLimit;
}
$lcMessages = $lcMessagesRequest;
}
else {
- throw new \API_Exception(ts('Language not enabled: %1', array(1 => $lcMessagesRequest)));
+ throw new \API_Exception(ts('Language not enabled: %1', [1 => $lcMessagesRequest]));
}
}
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::AUTHORIZE => array(
- array('onApiAuthorize', Events::W_LATE),
- ),
- );
+ return [
+ Events::AUTHORIZE => [
+ ['onApiAuthorize', Events::W_LATE],
+ ],
+ ];
}
/**
case 'ActionSchedule':
$events = \CRM_Event_BAO_Event::getEvents();
$aclEdit = \CRM_ACL_API::group(\CRM_Core_Permission::EDIT, NULL, 'civicrm_event', $events);
- $param = array('id' => $apiRequest['params']['id']);
- $eventId = \CRM_Core_BAO_ActionSchedule::retrieve($param, $value = array());
+ $param = ['id' => $apiRequest['params']['id']];
+ $eventId = \CRM_Core_BAO_ActionSchedule::retrieve($param, $value = []);
if (in_array($eventId->entity_value, $aclEdit)) {
return TRUE;
}
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::PREPARE => array('onApiPrepare', Events::W_EARLY),
- Events::RESPOND => array('onApiRespond', Events::W_MIDDLE),
- Events::EXCEPTION => array('onApiException', Events::W_EARLY),
- );
+ return [
+ Events::PREPARE => ['onApiPrepare', Events::W_EARLY],
+ Events::RESPOND => ['onApiRespond', Events::W_MIDDLE],
+ Events::EXCEPTION => ['onApiException', Events::W_EARLY],
+ ];
}
/**
* @var array (scalar $apiRequestId => CRM_Core_Transaction $tx)
*/
- private $transactions = array();
+ private $transactions = [];
/**
* @var array (scalar $apiRequestId => bool)
* A list of requests which should be forcibly rolled back to
* their save points.
*/
- private $forceRollback = array();
+ private $forceRollback = [];
/**
* Determine if an API request should be treated as transactional.
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::AUTHORIZE => array('onApiAuthorize', Events::W_EARLY),
- Events::RESPOND => array('onApiRespond', Events::W_MIDDLE),
- );
+ return [
+ Events::AUTHORIZE => ['onApiAuthorize', Events::W_EARLY],
+ Events::RESPOND => ['onApiRespond', Events::W_MIDDLE],
+ ];
}
/**
* @throws \CRM_Core_Exception
*/
public function __construct($rules) {
- $this->rules = array();
+ $this->rules = [];
foreach ($rules as $rule) {
/** @var WhitelistRule $rule */
if ($rule->isValid()) {
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::PREPARE => array('onApiPrepare', Events::W_MIDDLE),
- Events::RESPOND => array('onApiRespond', Events::W_EARLY * 2),
- );
+ return [
+ Events::PREPARE => ['onApiPrepare', Events::W_MIDDLE],
+ Events::RESPOND => ['onApiRespond', Events::W_EARLY * 2],
+ ];
}
/**
* @param array $defaults
* array(\API_Wrapper).
*/
- public function __construct($defaults = array()) {
+ public function __construct($defaults = []) {
$this->defaults = $defaults;
}
* @return array
*/
public static function getSubscribedEvents() {
- return array(
- Events::RESPOND => array('onApiRespond', Events::W_LATE),
- );
+ return [
+ Events::RESPOND => ['onApiRespond', Events::W_LATE],
+ ];
}
/**
*/
class WhitelistRule {
- static $IGNORE_FIELDS = array(
+ static $IGNORE_FIELDS = [
'check_permissions',
'debug',
'offset',
'sequential',
'sort',
'version',
- );
+ ];
/**
* Create a batch of rules from an array.
* @return array
*/
public static function createAll($rules) {
- $whitelist = array();
+ $whitelist = [];
foreach ($rules as $rule) {
$whitelist[] = new WhitelistRule($rule);
}
$this->actions = '*';
}
else {
- $this->actions = array();
+ $this->actions = [];
foreach ((array) $ruleSpec['actions'] as $action) {
$this->actions[] = Request::normalizeActionName($action, $ruleSpec['version']);
}
// Kind'a silly we need to (re(re))parse here for each rule; would be more
// performant if pre-parsed by Request::create().
$options = _civicrm_api3_get_options_from_params($apiRequest['params'], TRUE, $apiRequest['entity'], 'get');
- $return = \CRM_Utils_Array::value('return', $options, array());
+ $return = \CRM_Utils_Array::value('return', $options, []);
$activatedFields = array_merge($activatedFields, array_keys($return));
}
* List of acceptable keys.
*/
protected function filterFields($keys) {
- $r = array();
+ $r = [];
foreach ($keys as $key) {
if (in_array($key, $this->fields)) {
$r[] = $key;
* @var array
* Array(scalar $id => Mapping $mapping).
*/
- protected $mappings = array();
+ protected $mappings = [];
/**
* Register a new mapping.
*/
abstract class Mapping implements MappingInterface {
- private static $fields = array(
+ private static $fields = [
'id',
'entity',
'entity_label',
'entity_status_label',
'entity_date_start',
'entity_date_end',
- );
+ ];
/**
* Create mapping.
return \CRM_Core_OptionGroup::values('auto_renew_options');
}
else {
- return array();
+ return [];
}
}
return self::getValueLabelMap($this->entity_status);
* Array(string $fieldName => string $fieldLabel).
*/
public function getDateFields() {
- $dateFieldLabels = array();
+ $dateFieldLabels = [];
if (!empty($this->entity_date_start)) {
$dateFieldLabels[$this->entity_date_start] = ucwords(str_replace('_', ' ', $this->entity_date_start));
}
* Ex: array('assignee' => 'Activity Assignee').
*/
public function getRecipientTypes() {
- return array();
+ return [];
}
/**
* @see getRecipientTypes
*/
public function getRecipientListing($recipientType) {
- return array();
+ return [];
}
protected static function getValueLabelMap($name) {
$valueLabelMap['civicrm_membership_type'] = \CRM_Member_PseudoConstant::membershipType();
$allCustomFields = \CRM_Core_BAO_CustomField::getFields('');
- $dateFields = array(
+ $dateFields = [
'birth_date' => ts('Birth Date'),
'created_date' => ts('Created Date'),
'modified_date' => ts('Modified Date'),
- );
+ ];
foreach ($allCustomFields as $fieldID => $field) {
if ($field['data_type'] == 'Date') {
$dateFields["custom_$fieldID"] = $field['label'];
* List of error messages.
*/
public function validateSchedule($schedule) {
- return array();
+ return [];
}
/**
// which means reference date mismatches with the end_date where end_date may be used as the start_action_date
// criteria for some schedule reminder so in order to send new reminder we INSERT new reminder with new reference_date
// value via UNION operation
- $referenceReminderIDs = array();
+ $referenceReminderIDs = [];
$referenceDate = NULL;
if (!empty($query['casUseReferenceDate'])) {
// First retrieve all the action log's ids which are outdated or in other words reference_date now don't match with entity date.
$query = $this->prepareQuery(self::PHASE_ADDITION_FIRST);
$insertAdditionalSql = \CRM_Utils_SQL_Select::from("civicrm_contact c")
- ->merge($query, array('params'))
+ ->merge($query, ['params'])
->merge($this->selectIntoActionLog(self::PHASE_ADDITION_FIRST, $query))
->merge($this->joinReminder('LEFT JOIN', 'addl', $query))
->where('reminder.id IS NULL')
->merge($this->selectActionLogFields(self::PHASE_RELATION_REPEAT, $query))
->select("MAX(reminder.action_date_time) as latest_log_time")
->merge($this->prepareRepetitionEndFilter($query['casDateField']))
- ->where($this->actionSchedule->start_action_date ? $startDateClauses[0] : array())
+ ->where($this->actionSchedule->start_action_date ? $startDateClauses[0] : [])
->groupBy("reminder.contact_id, reminder.entity_id, reminder.entity_table")
// @todo replace use of timestampdiff with a direct comparison as TIMESTAMPDIFF cannot use an index.
->having("TIMESTAMPDIFF(HOUR, latest_log_time, CAST(!casNow AS datetime)) >= TIMESTAMPDIFF(HOUR, latest_log_time, DATE_ADD(latest_log_time, INTERVAL !casRepetitionInterval))")
- ->param(array(
+ ->param([
'casRepetitionInterval' => $this->parseRepetitionInterval(),
- ))
+ ])
->strict()
->toSQL();
if ($arrValues) {
\CRM_Core_DAO::executeQuery(
\CRM_Utils_SQL_Insert::into('civicrm_action_log')
- ->columns(array('contact_id', 'entity_id', 'entity_table', 'action_schedule_id'))
+ ->columns(['contact_id', 'entity_id', 'entity_table', 'action_schedule_id'])
->rows($arrValues)
->toSQL()
);
$addlCheck = \CRM_Utils_SQL_Select::from($query['casAddlCheckFrom'])
->select('*')
- ->merge($query, array('params', 'wheres', 'joins'))
+ ->merge($query, ['params', 'wheres', 'joins'])
->merge($this->prepareRepetitionEndFilter($query['casDateField']))
->limit(1)
->strict()
->merge($this->selectActionLogFields(self::PHASE_ADDITION_REPEAT, $query))
->merge($this->joinReminder('INNER JOIN', 'addl', $query))
->select("MAX(reminder.action_date_time) as latest_log_time")
- ->merge($this->prepareAddlFilter('c.id'), array('params'))
+ ->merge($this->prepareAddlFilter('c.id'), ['params'])
->where("c.is_deleted = 0 AND c.is_deceased = 0")
->groupBy("reminder.contact_id")
// @todo replace use of timestampdiff with a direct comparison as TIMESTAMPDIFF cannot use an index.
->having("TIMESTAMPDIFF(HOUR, latest_log_time, CAST(!casNow AS datetime)) >= TIMESTAMPDIFF(HOUR, latest_log_time, DATE_ADD(latest_log_time, INTERVAL !casRepetitionInterval))")
- ->param(array(
+ ->param([
'casRepetitionInterval' => $this->parseRepetitionInterval(),
- ))
+ ])
->strict()
->toSQL();
if ($addValues) {
\CRM_Core_DAO::executeQuery(
\CRM_Utils_SQL_Insert::into('civicrm_action_log')
- ->columns(array('contact_id', 'entity_id', 'entity_table', 'action_schedule_id'))
+ ->columns(['contact_id', 'entity_id', 'entity_table', 'action_schedule_id'])
->rows($addValues)
->toSQL()
);
* @throws \CRM_Core_Exception
*/
protected function prepareQuery($phase) {
- $defaultParams = array(
+ $defaultParams = [
'casActionScheduleId' => $this->actionSchedule->id,
'casMappingId' => $this->mapping->getId(),
'casMappingEntity' => $this->mapping->getEntity(),
'casNow' => $this->now,
- );
+ ];
/** @var \CRM_Utils_SQL_Select $query */
$query = $this->mapping->createQuery($this->actionSchedule, $phase, $defaultParams);
$actionSchedule = $this->actionSchedule;
if ($actionSchedule->group_id) {
- $regularGroupIDs = $smartGroupIDs = $groupWhereCLause = array();
+ $regularGroupIDs = $smartGroupIDs = $groupWhereCLause = [];
$query = \CRM_Utils_SQL_Select::fragment();
// get child group IDs if any
$childGroupIDs = \CRM_Contact_BAO_Group::getChildGroupIds($actionSchedule->group_id);
- foreach (array_merge(array($actionSchedule->group_id), $childGroupIDs) as $groupID) {
+ foreach (array_merge([$actionSchedule->group_id], $childGroupIDs) as $groupID) {
if ($this->isSmartGroup($groupID)) {
// Check that the group is in place in the cache and up to date
\CRM_Contact_BAO_GroupContactCache::check($groupID);
*/
protected function prepareStartDateClauses() {
$actionSchedule = $this->actionSchedule;
- $startDateClauses = array();
+ $startDateClauses = [];
if ($actionSchedule->start_action_date) {
$op = ($actionSchedule->start_action_condition == 'before' ? '<=' : '>=');
$operator = ($actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD');
return \CRM_Utils_SQL_Select::fragment()
->where("@casNow <= !repetitionEndDate")
- ->param(array(
+ ->param([
'!repetitionEndDate' => $repeatEventDateExpr,
- ));
+ ]);
}
/**
$fragment->select($query['casDateField']);
}
$fragment->select(
- array(
+ [
"!casContactIdField as contact_id",
"!casEntityIdField as entity_id",
"@casMappingEntity as entity_table",
"#casActionScheduleId as action_schedule_id",
- )
+ ]
);
break;
case self::PHASE_ADDITION_FIRST:
case self::PHASE_ADDITION_REPEAT:
//CRM-19017: Load default params for fragment query object.
- $params = array(
+ $params = [
'casActionScheduleId' => $this->actionSchedule->id,
'casNow' => $this->now,
- );
+ ];
$fragment = \CRM_Utils_SQL_Select::fragment()->param($params);
$fragment->select(
- array(
+ [
"c.id as contact_id",
"c.id as entity_id",
"'civicrm_contact' as entity_table",
"#casActionScheduleId as action_schedule_id",
- )
+ ]
);
break;
* @throws \CRM_Core_Exception
*/
protected function selectIntoActionLog($phase, $query) {
- $actionLogColumns = array(
+ $actionLogColumns = [
"contact_id",
"entity_id",
"entity_table",
"action_schedule_id",
- );
+ ];
if ($phase === self::PHASE_RELATION_FIRST || $phase === self::PHASE_RELATION_REPEAT) {
if (!empty($query['casUseReferenceDate'])) {
array_unshift($actionLogColumns, 'reference_date');
$this->angular = \Civi::service('angular');
$this->region = \CRM_Utils_Request::retrieve('snippet', 'String') ? 'ajax-snippet' : 'html-header';
$this->pageName = isset($_GET['q']) ? $_GET['q'] : NULL;
- $this->modules = array();
+ $this->modules = [];
}
/**
if ($this->crmApp !== NULL) {
$this->addModules($this->crmApp['modules']);
$region = \CRM_Core_Region::instance($this->crmApp['region']);
- $region->update('default', array('disabled' => TRUE));
- $region->add(array('template' => $this->crmApp['file'], 'weight' => 0));
- $this->res->addSetting(array(
- 'crmApp' => array(
+ $region->update('default', ['disabled' => TRUE]);
+ $region->add(['template' => $this->crmApp['file'], 'weight' => 0]);
+ $this->res->addSetting([
+ 'crmApp' => [
'defaultRoute' => $this->crmApp['defaultRoute'],
- ),
- ));
+ ],
+ ]);
// If trying to load an Angular page via AJAX, the route must be passed as a
// URL parameter, since the server doesn't receive information about
// URL fragments (i.e, what comes after the #).
- $this->res->addSetting(array(
+ $this->res->addSetting([
'angularRoute' => $this->crmApp['activeRoute'],
- ));
+ ]);
}
$moduleNames = $this->findActiveModules();
if (!$this->isAllModules($moduleNames)) {
- $assetParams = array('modules' => implode(',', $moduleNames));
+ $assetParams = ['modules' => implode(',', $moduleNames)];
}
else {
// The module list will be "all modules that the user can see".
- $assetParams = array('nonce' => md5(implode(',', $moduleNames)));
+ $assetParams = ['nonce' => md5(implode(',', $moduleNames))];
}
$res->addSettingsFactory(function () use (&$moduleNames, $angular, $res, $assetParams) {
// TODO optimization; client-side caching
- $result = array_merge($angular->getResources($moduleNames, 'settings', 'settings'), array(
+ $result = array_merge($angular->getResources($moduleNames, 'settings', 'settings'), [
'resourceUrls' => \CRM_Extension_System::singleton()->getMapper()->getActiveModuleUrls(),
- 'angular' => array(
+ 'angular' => [
'modules' => $moduleNames,
'requires' => $angular->getResources($moduleNames, 'requires', 'requires'),
'cacheCode' => $res->getCacheCode(),
'bundleUrl' => \Civi::service('asset_builder')->getUrl('angular-modules.json', $assetParams),
- ),
- ));
+ ],
+ ]);
return $result;
});
* @return AngularLoader
* @link https://code.angularjs.org/1.5.11/docs/guide/bootstrap
*/
- public function useApp($settings = array()) {
- $defaults = array(
- 'modules' => array('crmApp'),
+ public function useApp($settings = []) {
+ $defaults = [
+ 'modules' => ['crmApp'],
'activeRoute' => NULL,
'defaultRoute' => NULL,
'region' => 'page-body',
'file' => 'Civi/Angular/Page/Main.tpl',
- );
+ ];
$this->crmApp = array_merge($defaults, $settings);
return $this;
}
* - resourceType: string
* - callback: function
*/
- protected $resFilters = array();
+ protected $resFilters = [];
/**
* @var array
* - regex: string
* - callback: function
*/
- protected $htmlFilters = array();
+ protected $htmlFilters = [];
/**
* @param string $name
return $this->alterResource('requires',
function ($values) use ($module, $dependencies) {
if (!isset($values[$module])) {
- $values[$module] = array();
+ $values[$module] = [];
}
$values[$module] = array_unique(array_merge($values[$module], $dependencies));
return $values;
* @return ChangeSet
*/
public function alterResource($resourceType, $callback) {
- $this->resFilters[] = array(
+ $this->resFilters[] = [
'resourceType' => $resourceType,
'callback' => $callback,
- );
+ ];
return $this;
}
* @return ChangeSet
*/
public function alterHtml($file, $callback) {
- $this->htmlFilters[] = array(
+ $this->htmlFilters[] = [
'regex' => ($file{0} === ';') ? $file : $this->createRegex($file),
'callback' => $callback,
- );
+ ];
return $this;
}
}
protected function cleanup($html) {
- $html = preg_replace_callback("/([\\-a-zA-Z0-9]+)=(')([^']*)(')/", array($this, 'cleanupAttribute'), $html);
- $html = preg_replace_callback('/([\-a-zA-Z0-9]+)=(")([^"]*)(")/', array($this, 'cleanupAttribute'), $html);
+ $html = preg_replace_callback("/([\\-a-zA-Z0-9]+)=(')([^']*)(')/", [$this, 'cleanupAttribute'], $html);
+ $html = preg_replace_callback('/([\-a-zA-Z0-9]+)=(")([^"]*)(")/', [$this, 'cleanupAttribute'], $html);
return $html;
}
*/
public function __construct($res, \CRM_Utils_Cache_Interface $cache = NULL) {
$this->res = $res;
- $this->cache = $cache ? $cache : new \CRM_Utils_Cache_Arraycache(array());
+ $this->cache = $cache ? $cache : new \CRM_Utils_Cache_Arraycache([]);
}
/**
// Note: It would be nice to just glob("$civicrm_root/ang/*.ang.php"), but at time
// of writing CiviMail and CiviCase have special conditionals.
- $angularModules = array();
+ $angularModules = [];
$angularModules['angularFileUpload'] = include "$civicrm_root/ang/angularFileUpload.ang.php";
$angularModules['crmApp'] = include "$civicrm_root/ang/crmApp.ang.php";
$angularModules['crmAttachment'] = include "$civicrm_root/ang/crmAttachment.ang.php";
\CRM_Utils_Hook::angularModules($angularModules);
foreach (array_keys($angularModules) as $module) {
if (!isset($angularModules[$module]['basePages'])) {
- $angularModules[$module]['basePages'] = array('civicrm/a');
+ $angularModules[$module]['basePages'] = ['civicrm/a'];
}
}
$this->modules = $this->resolvePatterns($angularModules);
*/
public function resolveDependencies($names) {
$allModules = $this->getModules();
- $visited = array();
+ $visited = [];
$result = $names;
while (($missingModules = array_diff($result, array_keys($visited))) && !empty($missingModules)) {
foreach ($missingModules as $module) {
$visited[$module] = 1;
if (!isset($allModules[$module])) {
- \Civi::log()->warning('Unrecognized Angular module {name}. Please ensure that all Angular modules are declared.', array(
+ \Civi::log()->warning('Unrecognized Angular module {name}. Please ensure that all Angular modules are declared.', [
'name' => $module,
'civi.tag' => 'deprecated',
- ));
+ ]);
}
elseif (isset($allModules[$module]['requires'])) {
$result = array_unique(array_merge($result, $allModules[$module]['requires']));
*/
public function resolveDefaultModules($basePage) {
$modules = $this->getModules();
- $result = array();
+ $result = [];
foreach ($modules as $moduleName => $module) {
if (in_array($basePage, $module['basePages']) || in_array('*', $module['basePages'])) {
$result[] = $moduleName;
* Updated list of Angular modules
*/
protected function resolvePatterns($modules) {
- $newModules = array();
+ $newModules = [];
foreach ($modules as $moduleKey => $module) {
- foreach (array('js', 'css', 'partials') as $fileset) {
+ foreach (['js', 'css', 'partials'] as $fileset) {
if (!isset($module[$fileset])) {
continue;
}
*/
public function getRawPartials($name) {
$module = $this->getModule($name);
- $result = array();
+ $result = [];
if (isset($module['partials'])) {
foreach ($module['partials'] as $partialDir) {
$partialDir = $this->res->getPath($module['ext']) . '/' . $partialDir;
*/
public function getTranslatedStrings($name) {
$module = $this->getModule($name);
- $result = array();
+ $result = [];
$strings = $this->getStrings($name);
foreach ($strings as $string) {
// TODO: should we pass translation domain based on $module[ext] or $module[tsDomain]?
// It doesn't look like client side really supports the domain right now...
- $translated = ts($string, array(
- 'domain' => array($module['ext'], NULL),
- ));
+ $translated = ts($string, [
+ 'domain' => [$module['ext'], NULL],
+ ]);
if ($translated != $string) {
$result[$string] = $translated;
}
*/
public function getStrings($name) {
$module = $this->getModule($name);
- $result = array();
+ $result = [];
if (isset($module['js'])) {
foreach ($module['js'] as $file) {
$strings = $this->res->getStrings()->get(
* @throws \CRM_Core_Exception
*/
public function getResources($moduleNames, $resType, $refType) {
- $result = array();
+ $result = [];
$moduleNames = (array) $moduleNames;
foreach ($moduleNames as $moduleName) {
$module = $this->getModule($moduleName);
case 'path-assetBuilder':
$assetName = parse_url($file, PHP_URL_HOST) . parse_url($file, PHP_URL_PATH);
- $assetParams = array();
+ $assetParams = [];
parse_str('' . parse_url($file, PHP_URL_QUERY), $assetParams);
$result[] = \Civi::service('asset_builder')->getPath($assetName, $assetParams);
break;
case 'rawUrl-assetBuilder':
case 'cacheUrl-assetBuilder':
$assetName = parse_url($file, PHP_URL_HOST) . parse_url($file, PHP_URL_PATH);
- $assetParams = array();
+ $assetParams = [];
parse_str('' . parse_url($file, PHP_URL_QUERY), $assetParams);
$result[] = \Civi::service('asset_builder')->getUrl($assetName, $assetParams);
break;
*/
public function getChangeSets() {
if ($this->changeSets === NULL) {
- $this->changeSets = array();
+ $this->changeSets = [];
\CRM_Utils_Hook::alterAngular($this);
}
return $this->changeSets;
public function registerResources() {
$loader = new \Civi\Angular\AngularLoader();
$loader->setPageName('civicrm/a');
- $loader->useApp(array(
+ $loader->useApp([
'activeRoute' => \CRM_Utils_Request::retrieve('route', 'String'),
'defaultRoute' => NULL,
- ));
+ ]);
$loader->load();
}
* @return string
*/
public function digestJs($files) {
- $scripts = array();
+ $scripts = [];
foreach ($files as $file) {
$scripts[] = file_get_contents($file);
}
$scripts = \CRM_Utils_JS::dedupeClosures(
$scripts,
- array('angular', '$', '_'),
- array('angular', 'CRM.$', 'CRM._')
+ ['angular', '$', '_'],
+ ['angular', 'CRM.$', 'CRM._']
);
// This impl of stripComments currently adds 10-20ms and cuts ~7%
return \CRM_Utils_JS::stripComments(implode("\n", $scripts));
*/
public function getMetadata($moduleNames, $angular) {
$modules = $angular->getModules();
- $result = array();
+ $result = [];
foreach ($moduleNames as $moduleName) {
if (isset($modules[$moduleName])) {
- $result[$moduleName] = array();
+ $result[$moduleName] = [];
$result[$moduleName]['domain'] = $modules[$moduleName]['ext'];
$result[$moduleName]['js'] = $angular->getResources($moduleName, 'js', 'rawUrl');
$result[$moduleName]['css'] = $angular->getResources($moduleName, 'css', 'rawUrl');
* @return bool
*/
public function hasActivity($type, $status = NULL) {
- $idx = $this->getActivityIndex(array('activity_type_id', 'status_id'));
- $activityTypeGroup = civicrm_api3('option_group', 'get', array('name' => 'activity_type'));
- $activityType = array(
+ $idx = $this->getActivityIndex(['activity_type_id', 'status_id']);
+ $activityTypeGroup = civicrm_api3('option_group', 'get', ['name' => 'activity_type']);
+ $activityType = [
'name' => $type,
'option_group_id' => $activityTypeGroup['id'],
- );
+ ];
$activityTypeID = civicrm_api3('option_value', 'get', $activityType);
$activityTypeID = $activityTypeID['values'][$activityTypeID['id']]['value'];
if ($status) {
- $activityStatusGroup = civicrm_api3('option_group', 'get', array('name' => 'activity_status'));
- $activityStatus = array(
+ $activityStatusGroup = civicrm_api3('option_group', 'get', ['name' => 'activity_status']);
+ $activityStatus = [
'name' => $status,
'option_group_id' => $activityStatusGroup['id'],
- );
+ ];
$activityStatusID = civicrm_api3('option_value', 'get', $activityStatus);
$activityStatusID = $activityStatusID['values'][$activityStatusID['id']]['value'];
}
if ($this->activities === NULL) {
// TODO find batch-oriented API for getting all activities in a case
$case = $this->getCase();
- $activities = array();
+ $activities = [];
if (isset($case['activities'])) {
foreach ($case['activities'] as $actId) {
- $result = civicrm_api3('Activity', 'get', array(
+ $result = civicrm_api3('Activity', 'get', [
'id' => $actId,
'is_current_revision' => 1,
- ));
+ ]);
$activities = array_merge($activities, $result['values']);
}
}
* @return array|NULL, activity record (api/v3)
*/
public function getSingleActivity($type) {
- $idx = $this->getActivityIndex(array('activity_type_id', 'id'));
+ $idx = $this->getActivityIndex(['activity_type_id', 'id']);
$actTypes = array_flip(\CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate'));
$typeId = $actTypes[$type];
$count = isset($idx[$typeId]) ? count($idx[$typeId]) : 0;
*/
public function getCase() {
if ($this->case === NULL) {
- $this->case = civicrm_api3('case', 'getsingle', array('id' => $this->caseId));
+ $this->case = civicrm_api3('case', 'getsingle', ['id' => $this->caseId]);
}
return $this->case;
}
$this->case = NULL;
$this->caseType = NULL;
$this->activities = NULL;
- $this->indices = array();
+ $this->indices = [];
}
}
* @inheritDoc
*/
public function getHookValues() {
- return array($this->analyzer);
+ return [$this->analyzer];
}
}
*
* We do not want to fire case-change events recursively.
*/
- static $isActive = array();
+ static $isActive = [];
/**
* Following a change to an activity or case, fire the case-change event.
$tx = new \CRM_Core_Transaction();
\CRM_Core_Transaction::addCallback(
\CRM_Core_Transaction::PHASE_POST_COMMIT,
- array(__CLASS__, 'fireCaseChangeForRealz'),
- array($caseId),
+ [__CLASS__, 'fireCaseChangeForRealz'],
+ [$caseId],
"Civi_CCase_Events::fire::{$caseId}"
);
}
$actTypes = array_flip(\CRM_Activity_BAO_Activity::buildOptions('activity_type_id', 'validate'));
$actStatuses = array_flip(\CRM_Activity_BAO_Activity::getStatusesByType(\CRM_Activity_BAO_Activity::COMPLETED));
- $actIndex = $analyzer->getActivityIndex(array('activity_type_id', 'status_id'));
+ $actIndex = $analyzer->getActivityIndex(['activity_type_id', 'status_id']);
foreach ($activitySetXML->ActivityTypes->ActivityType as $actTypeXML) {
$actTypeId = $actTypes[(string) $actTypeXML->name];
}
// OK, the all activities have completed
- civicrm_api3('Case', 'create', array(
+ civicrm_api3('Case', 'create', [
'id' => $analyzer->getCaseId(),
'status_id' => 'Closed',
- ));
+ ]);
$analyzer->flush();
}
* @param \SimpleXMLElement $actXML the <ActivityType> tag which describes the new activity
*/
public function createActivity(Analyzer $analyzer, \SimpleXMLElement $actXML) {
- $params = array(
+ $params = [
'activity_type_id' => (string) $actXML->name,
'status_id' => 'Scheduled',
'activity_date_time' => \CRM_Utils_Time::getTime('YmdHis'),
'case_id' => $analyzer->getCaseId(),
- );
+ ];
$case = $analyzer->getCase();
if (!empty($case['contact_id'])) {
$params['target_id'] = \CRM_Utils_Array::first($case['contact_id']);
* @return array
*/
public static function collect($arr, $col) {
- $r = array();
+ $r = [];
foreach ($arr as $k => $item) {
$r[$k] = $item[$col];
}
fwrite($fh, $csvContent);
rewind($fh);
- $results = array();
+ $results = [];
while (($r = fgetcsv($fh)) !== FALSE) {
$name = str_replace('.', '::', trim($r[0]));
$status = trim($r[1]);
}
list ($program, $target, $suite) = $argv;
- $candidateTests = \Civi\CiUtil\PHPUnitScanner::findTestsByPath(array($suite));
+ $candidateTests = \Civi\CiUtil\PHPUnitScanner::findTestsByPath([$suite]);
// $candidateTests = array(
// array('class' => 'CRM_Core_RegionTest', 'method' => 'testBlank'),
// array('class' => 'CRM_Core_RegionTest', 'method' => 'testDefault'),
// );
$antagonist = self::findAntagonist($target, $candidateTests);
if ($antagonist) {
- print_r(array('found an antagonist' => $antagonist));
+ print_r(['found an antagonist' => $antagonist]);
}
else {
- print_r(array('found no antagonists'));
+ print_r(['found no antagonists']);
}
}
public static function findAntagonist($target, $candidateTests) {
//$phpUnit = new \Civi\CiUtil\EnvTestRunner('./scripts/phpunit', 'EnvTests');
$phpUnit = new \Civi\CiUtil\EnvTestRunner('phpunit', 'tests/phpunit/EnvTests.php');
- $expectedResults = $phpUnit->run(array($target));
- print_r(array('$expectedResults' => $expectedResults));
+ $expectedResults = $phpUnit->run([$target]);
+ print_r(['$expectedResults' => $expectedResults]);
foreach ($candidateTests as $candidateTest) {
$candidateTestName = $candidateTest['class'] . '::' . $candidateTest['method'];
if ($candidateTestName == $target) {
continue;
}
- $actualResults = $phpUnit->run(array(
+ $actualResults = $phpUnit->run([
$candidateTestName,
$target,
- ));
- print_r(array('$actualResults' => $actualResults));
+ ]);
+ print_r(['$actualResults' => $actualResults]);
foreach ($expectedResults as $testName => $expectedResult) {
if ($actualResults[$testName] != $expectedResult) {
- return array(
+ return [
'antagonist' => $candidateTest,
'expectedResults' => $expectedResults,
'actualResults' => $actualResults,
- );
+ ];
}
}
}
exit(1);
}
- $parser = array('\Civi\CiUtil\PHPUnitParser', 'parseJsonResults');
+ $parser = ['\Civi\CiUtil\PHPUnitParser', 'parseJsonResults'];
$printerType = 'txt';
- $suites = array(); // array('file' => string, 'results' => array)
+ $suites = []; // array('file' => string, 'results' => array)
for ($i = 1; $i < count($argv); $i++) {
switch ($argv[$i]) {
case '--phpunit-json':
- $parser = array('\Civi\CiUtil\PHPUnitParser', 'parseJsonResults');
+ $parser = ['\Civi\CiUtil\PHPUnitParser', 'parseJsonResults'];
break;
case '--jenkins-xml':
- $parser = array('\Civi\CiUtil\JenkinsParser', 'parseXmlResults');
+ $parser = ['\Civi\CiUtil\JenkinsParser', 'parseXmlResults'];
break;
case '--csv':
- $parser = array('\Civi\CiUtil\CSVParser', 'parseResults');
+ $parser = ['\Civi\CiUtil\CSVParser', 'parseResults'];
break;
case '--out=txt':
break;
default:
- $suites[] = array(
+ $suites[] = [
'file' => $argv[$i],
'results' => call_user_func($parser, file_get_contents($argv[$i])),
- );
+ ];
}
}
- $tests = array(); // array(string $name)
+ $tests = []; // array(string $name)
foreach ($suites as $suite) {
$tests = array_unique(array_merge(
$tests,
$printer = new \Civi\CiUtil\ComparisonPrinter(\Civi\CiUtil\Arrays::collect($suites, 'file'));
}
foreach ($tests as $test) {
- $values = array();
+ $values = [];
foreach ($suites as $suite) {
$values[] = isset($suite['results'][$test]) ? $suite['results'][$test] : 'MISSING';
}
*/
public static function parseXmlResults($content) {
$xml = simplexml_load_string($content);
- $results = array();
+ $results = [];
foreach ($xml->suites as $suites) {
foreach ($suites->suite as $suite) {
foreach ($suite->cases as $cases) {
*/
protected static function parseJsonStream($content) {
$content = '['
- . strtr($content, array("}{" => "},{"))
+ . strtr($content, ["}{" => "},{"])
. ']';
return json_decode($content, TRUE);
}
*/
public static function parseJsonResults($content) {
$records = self::parseJsonStream($content);
- $results = array();
+ $results = [];
foreach ($records as $r) {
if ($r['event'] == 'test') {
$results[$r['test']] = $r['status'];
* @throws \Exception
*/
public static function findTestClasses($paths) {
- $testClasses = array();
+ $testClasses = [];
$finder = new Finder();
foreach ($paths as $path) {
* - method: string
*/
public static function findTestsByPath($paths) {
- $r = array();
+ $r = [];
$testClasses = self::findTestClasses($paths);
foreach ($testClasses as $testFile => $testClass) {
$clazz = new \ReflectionClass($testClass);
foreach ($clazz->getMethods() as $method) {
if (preg_match('/^test/', $method->name)) {
- $r[] = array(
+ $r[] = [
'file' => $testFile,
'class' => $testClass,
'method' => $method->name,
- );
+ ];
}
}
}
*/
public function login($username, $password) {
$config = \CRM_Core_Config::singleton();
- $handler = array($this, 'loginTo' . $config->userFramework);
+ $handler = [$this, 'loginTo' . $config->userFramework];
if (is_callable($handler)) {
call_user_func($handler, $username, $password);
}
* Array(string $value => string $label).
*/
public static function getCacheModes() {
- return array(
+ return [
'0' => ts('Disable'),
'1' => ts('Enable'),
'auto' => ts('Auto'),
- );
+ ];
}
protected $cacheEnabled;
* URL.
* Ex: 'http://example.org/files/civicrm/dyn/angular.abcd1234abcd1234.json'.
*/
- public function getUrl($name, $params = array()) {
+ public function getUrl($name, $params = []) {
if (!$this->isValidName($name)) {
throw new \RuntimeException("Invalid dynamic asset name");
}
return $this->getCacheUrl($fileName);
}
else {
- return \CRM_Utils_System::url('civicrm/asset/builder', array(
+ return \CRM_Utils_System::url('civicrm/asset/builder', [
'an' => $name,
'ap' => $this->encode($params),
'ad' => $this->digest($name, $params),
- ), TRUE, NULL, FALSE);
+ ], TRUE, NULL, FALSE);
}
}
* URL.
* Ex: '/var/www/files/civicrm/dyn/angular.abcd1234abcd1234.json'.
*/
- public function getPath($name, $params = array()) {
+ public function getPath($name, $params = []) {
if (!$this->isValidName($name)) {
throw new \RuntimeException("Invalid dynamic asset name");
}
throw new UnknownAssetException("Asset name is malformed");
}
$nameParts = explode('.', $name);
- array_splice($nameParts, -1, 0, array($this->digest($name, $params)));
+ array_splice($nameParts, -1, 0, [$this->digest($name, $params)]);
$fileName = implode('.', $nameParts);
if ($force || !file_exists($this->getCachePath($fileName))) {
// No file locking, but concurrent writers should produce
* - content: string, ex: '<body>Hello world</body>'.
* @throws \CRM_Core_Exception
*/
- public function render($name, $params = array()) {
+ public function render($name, $params = []) {
if (!$this->isValidName($name)) {
throw new UnknownAssetException("Asset name is malformed");
}
throw new UnknownAssetException("Unrecognized asset name: $name");
}
// Beg your pardon, sir. Please may I have an HTTP response class instead?
- return array(
+ return [
'statusCode' => 200,
'mimeType' => $mimeType,
'content' => $content,
- );
+ ];
}
/**
*/
protected function decode($str) {
if ($str === NULL || $str === FALSE || $str === '') {
- return array();
+ return [];
}
$str = base64_decode($str);
return $assets->render($get['an'], $assets->decode($get['ap']));
}
catch (UnknownAssetException $e) {
- return array(
+ return [
'statusCode' => 404,
'mimeType' => 'text/plain',
'content' => $e->getMessage(),
- );
+ ];
}
}
* @var array
* Array(string $eventName => trueish).
*/
- private $autoListeners = array();
+ private $autoListeners = [];
/**
* Determine whether $eventName should delegate to the CMS hook system.
// WISHLIST: For native extensions (and possibly D6/D7/D8/BD), enumerate
// the listeners and list them one-by-one. This would make it easier to
// inspect via "cv debug:event-dispatcher".
- $this->addListener($eventName, array(
+ $this->addListener($eventName, [
'\Civi\Core\CiviEventDispatcher',
'delegateToUF',
- ), self::DEFAULT_HOOK_PRIORITY);
+ ], self::DEFAULT_HOOK_PRIORITY);
}
}
}
* @see \CRM_Utils_Hook::eventDefs()
*/
public static function findBuiltInEvents(\Civi\Core\Event\GenericHookEvent $e) {
- $skipList = array('singleton');
+ $skipList = ['singleton'];
$e->inspector->addStaticStubs('CRM_Utils_Hook', 'hook_civicrm_',
function ($eventDef, $method) use ($skipList) {
return in_array($method->name, $skipList) ? NULL : $eventDef;
*/
public function build($force = FALSE) {
if ($force || $this->eventDefs === NULL) {
- $this->eventDefs = array();
+ $this->eventDefs = [];
\CRM_Utils_Hook::eventDefs($this);
ksort($this->eventDefs);
}
return FALSE;
}
- if (!in_array($eventDef['type'], array('hook', 'object'))) {
+ if (!in_array($eventDef['type'], ['hook', 'object'])) {
return FALSE;
}
* @return CiviEventInspector
*/
public function addEventClass($event, $className) {
- $this->add(array(
+ $this->add([
'name' => $event,
'class' => $className,
- ));
+ ]);
return $this;
}
continue;
}
- $eventDef = array(
+ $eventDef = [
'name' => $prefix . $method->name,
'description_html' => $method->getDocComment() ? \CRM_Admin_Page_APIExplorer::formatDocBlock($method->getDocComment()) : '',
- 'fields' => array(),
+ 'fields' => [],
'class' => 'Civi\Core\Event\GenericHookEvent',
'stub' => $method,
- );
+ ];
foreach ($method->getParameters() as $parameter) {
- $eventDef['fields'][$parameter->getName()] = array(
+ $eventDef['fields'][$parameter->getName()] = [
'name' => $parameter->getName(),
'ref' => (bool) $parameter->isPassedByReference(),
// WISHLIST: 'type' => 'mixed',
- );
+ ];
}
if ($filter !== NULL) {
$containerBuilder->compile();
$dumper = new PhpDumper($containerBuilder);
$containerConfigCache->write(
- $dumper->dump(array('class' => 'CachedCiviContainer')),
+ $dumper->dump(['class' => 'CachedCiviContainer']),
$containerBuilder->getResources()
);
}
$container->setDefinition(self::SELF, new Definition(
'Civi\Core\Container',
- array()
+ []
));
// TODO Move configuration to an external file; define caching structure
$container->setDefinition('angular', new Definition(
'Civi\Angular\Manager',
- array()
+ []
))
- ->setFactory(array(new Reference(self::SELF), 'createAngularManager'));
+ ->setFactory([new Reference(self::SELF), 'createAngularManager']);
$container->setDefinition('dispatcher', new Definition(
'Civi\Core\CiviEventDispatcher',
- array(new Reference('service_container'))
+ [new Reference('service_container')]
))
- ->setFactory(array(new Reference(self::SELF), 'createEventDispatcher'));
+ ->setFactory([new Reference(self::SELF), 'createEventDispatcher']);
$container->setDefinition('magic_function_provider', new Definition(
'Civi\API\Provider\MagicFunctionProvider',
- array()
+ []
));
$container->setDefinition('civi_api_kernel', new Definition(
'Civi\API\Kernel',
- array(new Reference('dispatcher'), new Reference('magic_function_provider'))
+ [new Reference('dispatcher'), new Reference('magic_function_provider')]
))
- ->setFactory(array(new Reference(self::SELF), 'createApiKernel'));
+ ->setFactory([new Reference(self::SELF), 'createApiKernel']);
$container->setDefinition('cxn_reg_client', new Definition(
'Civi\Cxn\Rpc\RegistrationClient',
- array()
+ []
))
->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient');
- $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
+ $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []));
- $basicCaches = array(
+ $basicCaches = [
'js_strings' => 'js_strings',
'community_messages' => 'community_messages',
'checks' => 'checks',
'session' => 'CiviCRM Session',
'long' => 'long',
- );
+ ];
foreach ($basicCaches as $cacheSvc => $cacheGrp) {
$container->setDefinition("cache.{$cacheSvc}", new Definition(
'CRM_Utils_Cache_Interface',
- array(
- array(
+ [
+ [
'name' => $cacheGrp,
- 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
- ),
- )
+ 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
+ ],
+ ]
))->setFactory('CRM_Utils_Cache::create');
}
$container->setDefinition('sql_triggers', new Definition(
'Civi\Core\SqlTriggers',
- array()
+ []
));
$container->setDefinition('asset_builder', new Definition(
'Civi\Core\AssetBuilder',
- array()
+ []
));
$container->setDefinition('pear_mail', new Definition('Mail'))
}
// Expose legacy singletons as services in the container.
- $singletons = array(
+ $singletons = [
'httpClient' => 'CRM_Utils_HttpClient',
'cache.default' => 'CRM_Utils_Cache',
'i18n' => 'CRM_Core_I18n',
// Maybe? 'config' => 'CRM_Core_Config',
// Maybe? 'smarty' => 'CRM_Core_Smarty',
- );
+ ];
foreach ($singletons as $name => $class) {
$container->setDefinition($name, new Definition(
$class
))
- ->setFactory(array($class, 'singleton'));
+ ->setFactory([$class, 'singleton']);
}
$container->setAlias('cache.short', 'cache.default');
$container->setDefinition('resources', new Definition(
'CRM_Core_Resources',
[new Reference('service_container')]
- ))->setFactory(array(new Reference(self::SELF), 'createResources'));
+ ))->setFactory([new Reference(self::SELF), 'createResources']);
$container->setDefinition('prevnext', new Definition(
'CRM_Core_PrevNextCache_Interface',
[new Reference('service_container')]
- ))->setFactory(array(new Reference(self::SELF), 'createPrevNextCache'));
+ ))->setFactory([new Reference(self::SELF), 'createPrevNextCache']);
$container->setDefinition('prevnext.driver.sql', new Definition(
'CRM_Core_PrevNextCache_Sql',
));
$container->setDefinition('cache_config', new Definition('ArrayObject'))
- ->setFactory(array(new Reference(self::SELF), 'createCacheConfig'));
+ ->setFactory([new Reference(self::SELF), 'createCacheConfig']);
$container->setDefinition('civi.mailing.triggers', new Definition(
'Civi\Core\SqlTrigger\TimestampTriggers',
- array('civicrm_mailing', 'Mailing')
- ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
+ ['civicrm_mailing', 'Mailing']
+ ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
$container->setDefinition('civi.activity.triggers', new Definition(
'Civi\Core\SqlTrigger\TimestampTriggers',
- array('civicrm_activity', 'Activity')
- ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
+ ['civicrm_activity', 'Activity']
+ ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
$container->setDefinition('civi.case.triggers', new Definition(
'Civi\Core\SqlTrigger\TimestampTriggers',
- array('civicrm_case', 'Case')
- ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
+ ['civicrm_case', 'Case']
+ ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
$container->setDefinition('civi.case.staticTriggers', new Definition(
'Civi\Core\SqlTrigger\StaticTriggers',
- array(
- array(
- array(
- 'upgrade_check' => array('table' => 'civicrm_case', 'column' => 'modified_date'),
+ [
+ [
+ [
+ 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
'table' => 'civicrm_case_activity',
'when' => 'AFTER',
- 'event' => array('INSERT'),
+ 'event' => ['INSERT'],
'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
- ),
- array(
- 'upgrade_check' => array('table' => 'civicrm_case', 'column' => 'modified_date'),
+ ],
+ [
+ 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
'table' => 'civicrm_activity',
'when' => 'BEFORE',
- 'event' => array('UPDATE', 'DELETE'),
+ 'event' => ['UPDATE', 'DELETE'],
'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id IN (SELECT ca.case_id FROM civicrm_case_activity ca WHERE ca.activity_id = OLD.id);\n",
- ),
- ),
- )
+ ],
+ ],
+ ]
))
- ->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
+ ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
$container->setDefinition('civi_token_compat', new Definition(
'Civi\Token\TokenCompatSubscriber',
- array()
+ []
))->addTag('kernel.event_subscriber');
$container->setDefinition("crm_mailing_action_tokens", new Definition(
"CRM_Mailing_ActionTokens",
- array()
+ []
))->addTag('kernel.event_subscriber');
- foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
+ foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
$container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
"CRM_{$comp}_Tokens",
- array()
+ []
))->addTag('kernel.event_subscriber');
}
if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
- \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, array($container));
+ \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, [$container]);
}
\CRM_Utils_Hook::container($container);
*/
public function createEventDispatcher($container) {
$dispatcher = new CiviEventDispatcher($container);
- $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\InstallationCanary', 'check'));
- $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\DatabaseInitializer', 'initialize'));
- $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\LocalizationInitializer', 'initialize'));
- $dispatcher->addListener('hook_civicrm_pre', array('\Civi\Core\Event\PreEvent', 'dispatchSubevent'), 100);
- $dispatcher->addListener('hook_civicrm_post', array('\Civi\Core\Event\PostEvent', 'dispatchSubevent'), 100);
- $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
- $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
- $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
- $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
- $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\CiviEventInspector', 'findBuiltInEvents'));
+ $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\InstallationCanary', 'check']);
+ $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\DatabaseInitializer', 'initialize']);
+ $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\LocalizationInitializer', 'initialize']);
+ $dispatcher->addListener('hook_civicrm_pre', ['\Civi\Core\Event\PreEvent', 'dispatchSubevent'], 100);
+ $dispatcher->addListener('hook_civicrm_post', ['\Civi\Core\Event\PostEvent', 'dispatchSubevent'], 100);
+ $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
+ $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
+ $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
+ $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
+ $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
// TODO We need a better code-convention for metadata about non-hook events.
- $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\API\Events', 'hookEventDefs'));
- $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs'));
- $dispatcher->addListener('hook_civicrm_buildAsset', array('\Civi\Angular\Page\Modules', 'buildAngularModules'));
- $dispatcher->addListener('hook_civicrm_buildAsset', array('\CRM_Utils_VisualBundle', 'buildAssetJs'));
- $dispatcher->addListener('hook_civicrm_buildAsset', array('\CRM_Utils_VisualBundle', 'buildAssetCss'));
- $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
- $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
- $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
- $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
+ $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
+ $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
+ $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
+ $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
+ $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
+ $dispatcher->addListener('civi.dao.postInsert', ['\CRM_Core_BAO_RecurringEntity', 'triggerInsert']);
+ $dispatcher->addListener('civi.dao.postUpdate', ['\CRM_Core_BAO_RecurringEntity', 'triggerUpdate']);
+ $dispatcher->addListener('civi.dao.postDelete', ['\CRM_Core_BAO_RecurringEntity', 'triggerDelete']);
+ $dispatcher->addListener('hook_civicrm_unhandled_exception', [
'CRM_Core_LegacyErrorHandler',
'handleException',
- ), -200);
- $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
- $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
- $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
- $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
- $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
- $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
+ ], -200);
+ $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
+ $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
+ $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
+ $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
+ $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
+ $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
- \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, array($dispatcher));
+ \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, [$dispatcher]);
}
return $dispatcher;
// the container. For now, we'll make-do with some define()s.
$lm = new LockManager();
$lm
- ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
- ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
- ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
- ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
+ ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
+ ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
+ ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createCivimailLock'])
+ ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createScopedLock']);
// Registrations may use complex resolver expressions, but (as a micro-optimization)
// the default factory is specified as an array.
$dispatcher->addSubscriber($magicFunctionProvider);
$dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
$dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
- $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
+ $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter([
\CRM_Utils_API_HTMLInputCoder::singleton(),
\CRM_Utils_API_NullOutputCoder::singleton(),
\CRM_Utils_API_ReloadOption::singleton(),
\CRM_Utils_API_MatchOption::singleton(),
- )));
+ ]));
$dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
$kernel = new \Civi\API\Kernel($dispatcher);
$dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
$kernel,
'Attachment',
- array('create', 'get', 'delete'),
+ ['create', 'get', 'delete'],
// Given a file ID, determine the entity+table it's attached to.
'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
FROM civicrm_file cf
INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
WHERE fld.data_type = "File"
',
- array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
+ ['civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant']
));
- $kernel->setApiProviders(array(
+ $kernel->setApiProviders([
$reflectionProvider,
$magicFunctionProvider,
- ));
+ ]);
return $kernel;
}
*/
public static function boot($loadFromDB) {
// Array(string $serviceId => object $serviceInstance).
- $bootServices = array();
+ $bootServices = [];
\Civi::$statics[__CLASS__]['boot'] = &$bootServices;
$bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
$userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
$bootServices['userPermissionClass'] = new $userPermissionClass();
- $bootServices['cache.settings'] = \CRM_Utils_Cache::create(array(
+ $bootServices['cache.settings'] = \CRM_Utils_Cache::create([
'name' => 'settings',
- 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
- ));
+ 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
+ ]);
$bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
* @throws \CRM_Core_Exception
*/
public static function initialize(SystemInstallEvent $event) {
- $api_params = array(
+ $api_params = [
'version' => 3,
'triggers' => 1,
'session' => 1,
- );
+ ];
civicrm_api('System', 'flush', $api_params);
}
* @var mixed
* @deprecated
*/
- private $returnValues = array();
+ private $returnValues = [];
/**
* List of field names that are prohibited due to conflicts
*
* @var array
*/
- private static $BLACKLIST = array(
+ private static $BLACKLIST = [
'name',
'dispatcher',
'propagationStopped',
'hookValues',
'hookFields',
'hookFieldsFlip',
- );
+ ];
/**
* Create a GenericHookEvent using key-value pairs.
* @inheritDoc
*/
public function getHookValues() {
- return array($this->action, $this->entity, $this->id, &$this->object);
+ return [$this->action, $this->entity, $this->id, &$this->object];
}
}
* @inheritDoc
*/
public function getHookValues() {
- return array($this->action, $this->entity, $this->id, &$this->params);
+ return [$this->action, $this->entity, $this->id, &$this->params];
}
}
* @inheritDoc
*/
public function getHookValues() {
- return array($this->exception, $this->request);
+ return [$this->exception, $this->request];
}
}
$fileName = $localeDir . $seedLanguage . DIRECTORY_SEPARATOR . 'settings.default.json';
// initalization
- $settingsParams = array();
+ $settingsParams = [];
if (file_exists($fileName)) {
if (!empty($settings)) {
// get all valid settings
- $results = civicrm_api3('Setting', 'getfields', array());
+ $results = civicrm_api3('Setting', 'getfields', []);
$validSettings = array_keys($results['values']);
// add valid settings to params to send to api
foreach ($settings as $setting => $value) {
// set default currency in currencies_enabled (option group)
if (isset($settings['defaultCurrency'])) {
- \CRM_Admin_Form_Setting_Localization::updateEnabledCurrencies(array($settings['defaultCurrency']), $settings['defaultCurrency']);
+ \CRM_Admin_Form_Setting_Localization::updateEnabledCurrencies([$settings['defaultCurrency']], $settings['defaultCurrency']);
}
}
*/
class LockManager {
- private $rules = array();
+ private $rules = [];
/**
* @param string $name
$factory = $this->getFactory($name);
if ($factory) {
/** @var LockInterface $lock */
- $lock = call_user_func_array($factory, array($name));
+ $lock = call_user_func_array($factory, [$name]);
return $lock;
}
else {
* @see Resolver
*/
public function register($pattern, $factory) {
- $this->rules[] = array(
+ $this->rules[] = [
'pattern' => $pattern,
'factory' => $factory,
- );
+ ];
return $this;
}
* @var array
* Array(string $name => array(url => $, path => $)).
*/
- private $variables = array();
+ private $variables = [];
- private $variableFactory = array();
+ private $variableFactory = [];
/**
* Class constructor.
return \CRM_Core_Config::singleton()->userSystem->getCiviSourceStorage();
})
->register('civicrm.packages', function () {
- return array(
+ return [
'path' => \Civi::paths()->getPath('[civicrm.root]/packages/'),
'url' => \Civi::paths()->getUrl('[civicrm.root]/packages/'),
- );
+ ];
})
->register('civicrm.vendor', function () {
- return array(
+ return [
'path' => \Civi::paths()->getPath('[civicrm.root]/vendor/'),
'url' => \Civi::paths()->getUrl('[civicrm.root]/vendor/'),
- );
+ ];
})
->register('civicrm.bower', function () {
- return array(
+ return [
'path' => \Civi::paths()->getPath('[civicrm.root]/bower_components/'),
'url' => \Civi::paths()->getUrl('[civicrm.root]/bower_components/'),
- );
+ ];
})
->register('civicrm.files', function () {
return \CRM_Core_Config::singleton()->userSystem->getDefaultFileStorage();
})
->register('wp.frontend.base', function () {
- return array('url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/');
+ return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/'];
})
->register('wp.frontend', function () use ($paths) {
$config = \CRM_Core_Config::singleton();
$suffix = defined('CIVICRM_UF_WP_BASEPAGE') ? CIVICRM_UF_WP_BASEPAGE : $config->wpBasePage;
- return array(
+ return [
'url' => $paths->getVariable('wp.frontend.base', 'url') . $suffix,
- );
+ ];
})
->register('wp.backend.base', function () {
- return array('url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/wp-admin/');
+ return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/wp-admin/'];
})
->register('wp.backend', function () use ($paths) {
- return array(
+ return [
'url' => $paths->getVariable('wp.backend.base', 'url') . 'admin.php',
- );
+ ];
})
->register('cms', function () {
- return array(
+ return [
'path' => \CRM_Core_Config::singleton()->userSystem->cmsRootPath(),
'url' => \CRM_Utils_System::baseCMSURL(),
- );
+ ];
})
->register('cms.root', function () {
- return array(
+ return [
'path' => \CRM_Core_Config::singleton()->userSystem->cmsRootPath(),
// Misleading: this *removes* the language part of the URL, producing a pristine base URL.
'url' => \CRM_Utils_System::languageNegotiationURL(\CRM_Utils_System::baseCMSURL(), FALSE, TRUE),
- );
+ ];
});
}
case 'call':
// Callback: Object/method in container.
$obj = \Civi::service($url['host']);
- return array($obj, ltrim($url['path'], '/'));
+ return [$obj, ltrim($url['path'], '/')];
case 'api3':
// Callback: API.
throw new \RuntimeException("Unsupported callback scheme: " . $url['scheme']);
}
}
- elseif (in_array($id, array('0', '1'))) {
+ elseif (in_array($id, ['0', '1'])) {
// Callback: Constant value.
return new ResolverConstantCallback((int) $id);
}
* Fire an API call.
*/
public function __invoke() {
- $apiParams = array();
+ $apiParams = [];
if (isset($this->url['query'])) {
parse_str($this->url['query'], $apiParams);
}
* (e.g. "@1" => "firstValue").
*/
protected function createPlaceholders($prefix, $args) {
- $result = array();
+ $result = [];
foreach ($args as $offset => $arg) {
$result[$prefix . (1 + $offset)] = $arg;
}
public function __construct($domainId, $contactId) {
$this->domainId = $domainId;
$this->contactId = $contactId;
- $this->values = array();
+ $this->values = [];
$this->combined = NULL;
}
// Note: Don't use DAO child classes. They require fields() which require
// translations -- which are keyed off settings!
- $this->values = array();
+ $this->values = [];
$this->combined = NULL;
// Ordinarily, we just load values from `civicrm_setting`. But upgrades require care.
if ($isUpgradeMode && empty($this->contactId) && \CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_domain', 'config_backend', FALSE)) {
$config_backend = \CRM_Core_DAO::singleValueQuery('SELECT config_backend FROM civicrm_domain WHERE id = %1',
- array(1 => array($this->domainId, 'Positive')));
+ [1 => [$this->domainId, 'Positive']]);
$oldSettings = \CRM_Upgrade_Incremental_php_FourSeven::convertBackendToSettings($this->domainId, $config_backend);
\CRM_Utils_Array::extend($this->values, $oldSettings);
}
public function all() {
if ($this->combined === NULL) {
$this->combined = $this->combine(
- array($this->defaults, $this->values, $this->mandatory)
+ [$this->defaults, $this->values, $this->mandatory]
);
}
return $this->combined;
protected function createQuery() {
$select = \CRM_Utils_SQL_Select::from('civicrm_setting')
->select('id, name, value, domain_id, contact_id, is_domain, component_id, created_date, created_id')
- ->where('domain_id = #id', array(
+ ->where('domain_id = #id', [
'id' => $this->domainId,
- ));
+ ]);
if ($this->contactId === NULL) {
$select->where('is_domain = 1');
}
else {
- $select->where('contact_id = #id', array(
+ $select->where('contact_id = #id', [
'id' => $this->contactId,
- ));
+ ]);
$select->where('is_domain = 0');
}
return $select;
* @return array
*/
protected function combine($arrays) {
- $combined = array();
+ $combined = [];
foreach ($arrays as $array) {
foreach ($array as $k => $v) {
if ($v !== NULL) {
* The new value of the setting.
*/
protected function setDb($name, $value) {
- $fields = array();
- $fieldsToSet = \CRM_Core_BAO_Setting::validateSettingsInput(array($name => $value), $fields);
+ $fields = [];
+ $fieldsToSet = \CRM_Core_BAO_Setting::validateSettingsInput([$name => $value], $fields);
//We haven't traditionally validated inputs to setItem, so this breaks things.
//foreach ($fieldsToSet as $settingField => &$settingValue) {
// self::validateSetting($settingValue, $fields['values'][$settingField]);
* @var
* Array (int $id => SettingsBag $bag).
*/
- protected $bagsByDomain = array(), $bagsByContact = array();
+ protected $bagsByDomain = [], $bagsByContact = [];
/**
* @var array|NULL
$cacheKey = 'defaults_' . $entity;
$defaults = $this->cache->get($cacheKey);
if (!is_array($defaults)) {
- $specs = SettingsMetadata::getMetadata(array(
+ $specs = SettingsMetadata::getMetadata([
'is_contact' => ($entity === 'contact' ? 1 : 0),
- ));
- $defaults = array();
+ ]);
+ $defaults = [];
foreach ($specs as $key => $spec) {
$defaults[$key] = \CRM_Utils_Array::value('default', $spec);
}
* @return array
*/
public static function parseMandatorySettings($civicrm_setting) {
- $result = array(
- 'domain' => array(),
- 'contact' => array(),
- );
+ $result = [
+ 'domain' => [],
+ 'contact' => [],
+ ];
- $rewriteGroups = array(
+ $rewriteGroups = [
//\CRM_Core_BAO_Setting::ADDRESS_STANDARDIZATION_PREFERENCES_NAME => 'domain',
//\CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME => 'domain',
//\CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME => 'domain',
//\CRM_Core_BAO_Setting::URL_PREFERENCES_NAME => 'domain',
'domain' => 'domain',
'contact' => 'contact',
- );
+ ];
if (is_array($civicrm_setting)) {
foreach ($civicrm_setting as $oldGroup => $values) {
* @return array
*/
private static function getSystemDefaults($entity) {
- $defaults = array();
+ $defaults = [];
switch ($entity) {
case 'domain':
- $defaults = array(
+ $defaults = [
'installed' => FALSE,
- 'enable_components' => array('CiviEvent', 'CiviContribute', 'CiviMember', 'CiviMail', 'CiviReport', 'CiviPledge'),
+ 'enable_components' => ['CiviEvent', 'CiviContribute', 'CiviMember', 'CiviMail', 'CiviReport', 'CiviPledge'],
'customFileUploadDir' => '[civicrm.files]/custom/',
'imageUploadDir' => '[civicrm.files]/persist/contribute/',
'uploadDir' => '[civicrm.files]/upload/',
'extensionsURL' => '[civicrm.files]/ext/',
'resourceBase' => '[civicrm.root]/',
'userFrameworkResourceURL' => '[civicrm.root]/',
- );
+ ];
break;
}
* - description
* - help_text
*/
- public static function getMetadata($filters = array(), $domainID = NULL) {
+ public static function getMetadata($filters = [], $domainID = NULL) {
if ($domainID === NULL) {
$domainID = \CRM_Core_Config::domainID();
}
$settingsMetadata = $cache->get(self::ALL);
if (empty($settingsMetadata)) {
global $civicrm_root;
- $metaDataFolders = array($civicrm_root . '/settings');
+ $metaDataFolders = [$civicrm_root . '/settings'];
\CRM_Utils_Hook::alterSettingsFolders($metaDataFolders);
$settingsMetadata = self::loadSettingsMetaDataFolders($metaDataFolders);
$cache->set(self::ALL, $settingsMetadata);
* @return array
*/
protected static function loadSettingsMetaDataFolders($metaDataFolders) {
- $settingsMetadata = array();
- $loadedFolders = array();
+ $settingsMetadata = [];
+ $loadedFolders = [];
foreach ($metaDataFolders as $metaDataFolder) {
$realFolder = realpath($metaDataFolder);
if (is_dir($realFolder) && !isset($loadedFolders[$realFolder])) {
* @return array
*/
protected static function loadSettingsMetadata($metaDataFolder) {
- $settingMetaData = array();
+ $settingMetaData = [];
$settingsFiles = \CRM_Utils_File::findFiles($metaDataFolder, '*.setting.php');
foreach ($settingsFiles as $file) {
$settings = include $file;
if (empty($filters)) {
return;
}
- elseif (array_keys($filters) == array('name')) {
- $settingSpec = array($filters['name'] => \CRM_Utils_Array::value($filters['name'], $settingSpec, ''));
+ elseif (array_keys($filters) == ['name']) {
+ $settingSpec = [$filters['name'] => \CRM_Utils_Array::value($filters['name'], $settingSpec, '')];
return;
}
else {
* @var array
* Ex: $stack[0] == ['settingName', 'oldSettingValue'];
*/
- protected $stack = array();
+ protected $stack = [];
/**
* Temporarily apply a setting.
*/
public function push($setting, $settingValue) {
if (isset($GLOBALS['civicrm_setting']['domain'][$setting])) {
- $this->stack[] = array($setting, $GLOBALS['civicrm_setting']['domain'][$setting]);
+ $this->stack[] = [$setting, $GLOBALS['civicrm_setting']['domain'][$setting]];
}
else {
- $this->stack[] = array($setting, NULL);
+ $this->stack[] = [$setting, NULL];
}
$GLOBALS['civicrm_setting']['domain'][$setting] = $settingValue;
\Civi::service('settings_manager')->useMandatory();
$customDataEntity,
$createdDate = 'created_date',
$modifiedDate = 'modified_date',
- $relations = array()
+ $relations = []
) {
$this->tableName = $tableName;
$this->customDataEntity = $customDataEntity;
}
if ($tableFilter == NULL || $tableFilter == $this->getTableName()) {
- $info[] = array(
- 'table' => array($this->getTableName()),
+ $info[] = [
+ 'table' => [$this->getTableName()],
'when' => 'BEFORE',
- 'event' => array('INSERT'),
+ 'event' => ['INSERT'],
'sql' => "\nSET NEW.{$this->getCreatedDate()} = CURRENT_TIMESTAMP;\n",
- );
+ ];
}
// Update timestamp when modifying closely related tables
$relIdx = \CRM_Utils_Array::index(
- array('column', 'table'),
+ ['column', 'table'],
$this->getAllRelations()
);
foreach ($relIdx as $column => $someRelations) {
// If specific related table requested, just process that one.
// (Reply: This feels fishy.)
if (in_array($tableFilter, $relatedTableNames)) {
- $relatedTableNames = array($tableFilter);
+ $relatedTableNames = [$tableFilter];
}
// If no specific table requested (include all related tables),
// or a specific related table requested (as matched above)
if (empty($tableFilter) || isset($relatedTableNames[$tableFilter])) {
- $info[] = array(
+ $info[] = [
'table' => $relatedTableNames,
'when' => 'AFTER',
- 'event' => array('INSERT', 'UPDATE'),
+ 'event' => ['INSERT', 'UPDATE'],
'sql' => "\nUPDATE {$this->getTableName()} SET {$this->getModifiedDate()} = CURRENT_TIMESTAMP WHERE id = NEW.$contactRefColumn;\n",
- );
- $info[] = array(
+ ];
+ $info[] = [
'table' => $relatedTableNames,
'when' => 'AFTER',
- 'event' => array('DELETE'),
+ 'event' => ['DELETE'],
'sql' => "\nUPDATE {$this->getTableName()} SET {$this->getModifiedDate()} = CURRENT_TIMESTAMP WHERE id = OLD.$contactRefColumn;\n",
- );
+ ];
}
}
$customGroupDAO->is_multiple = 0;
$customGroupDAO->find();
while ($customGroupDAO->fetch()) {
- $relations[] = array(
+ $relations[] = [
'table' => $customGroupDAO->table_name,
'column' => 'entity_id',
- );
+ ];
}
}
* @see CRM-9716
*/
public function rebuild($tableName = NULL, $force = FALSE) {
- $info = array();
+ $info = [];
$logging = new \CRM_Logging_Schema();
$logging->triggerInfo($info, $tableName, $force);
return;
}
- $triggers = array();
+ $triggers = [];
// now enumerate the tables and the events and collect the same set in a different format
foreach ($info as $value) {
}
if (is_string($value['table']) == TRUE) {
- $tables = array($value['table']);
+ $tables = [$value['table']];
}
else {
$tables = $value['table'];
}
if (is_string($value['event']) == TRUE) {
- $events = array(strtolower($value['event']));
+ $events = [strtolower($value['event'])];
}
else {
$events = array_map('strtolower', $value['event']);
foreach ($tables as $tableName) {
if (!isset($triggers[$tableName])) {
- $triggers[$tableName] = array();
+ $triggers[$tableName] = [];
}
foreach ($events as $eventName) {
- $template_params = array('{tableName}', '{eventName}');
- $template_values = array($tableName, $eventName);
+ $template_params = ['{tableName}', '{eventName}'];
+ $template_values = [$tableName, $eventName];
$sql = str_replace($template_params,
$template_values,
);
if (!isset($triggers[$tableName][$eventName])) {
- $triggers[$tableName][$eventName] = array();
+ $triggers[$tableName][$eventName] = [];
}
if (!isset($triggers[$tableName][$eventName][$whenName])) {
// We're leaving out cursors, conditions, and handlers for now
// they are kind of dangerous in this context anyway
// better off putting them in stored procedures
- $triggers[$tableName][$eventName][$whenName] = array(
- 'variables' => array(),
- 'sql' => array(),
- );
+ $triggers[$tableName][$eventName][$whenName] = [
+ 'variables' => [],
+ 'sql' => [],
+ ];
}
if ($variables) {
* the specific table requiring a rebuild; or NULL to rebuild all tables.
*/
public function dropTriggers($tableName = NULL) {
- $info = array();
+ $info = [];
$logging = new \CRM_Logging_Schema();
$logging->triggerInfo($info, $tableName);
* @param array $params
* Optional parameters to interpolate into the string.
*/
- public function enqueueQuery($triggerSQL, $params = array()) {
+ public function enqueueQuery($triggerSQL, $params = []) {
if (\Civi::settings()->get('logging_no_trigger_permission')) {
if (!file_exists($this->getFile())) {
// Ugh. Need to let user know somehow. This is the first change.
- \CRM_Core_Session::setStatus(ts('The mysql commands you need to run are stored in %1', array(
+ \CRM_Core_Session::setStatus(ts('The mysql commands you need to run are stored in %1', [
1 => $this->getFile(),
- )),
+ ]),
'',
'alert',
- array('expires' => 0)
+ ['expires' => 0]
);
}
$this->commitStmt = $commitStmt;
$this->rollbackStmt = $rollbackStmt;
- $this->callbacks = array(
- \CRM_Core_Transaction::PHASE_PRE_COMMIT => array(),
- \CRM_Core_Transaction::PHASE_POST_COMMIT => array(),
- \CRM_Core_Transaction::PHASE_PRE_ROLLBACK => array(),
- \CRM_Core_Transaction::PHASE_POST_ROLLBACK => array(),
- );
+ $this->callbacks = [
+ \CRM_Core_Transaction::PHASE_PRE_COMMIT => [],
+ \CRM_Core_Transaction::PHASE_POST_COMMIT => [],
+ \CRM_Core_Transaction::PHASE_PRE_ROLLBACK => [],
+ \CRM_Core_Transaction::PHASE_POST_ROLLBACK => [],
+ ];
}
public function inc() {
*/
public function addCallback($phase, $callback, $params = NULL, $id = NULL) {
if ($id) {
- $this->callbacks[$phase][$id] = array(
+ $this->callbacks[$phase][$id] = [
'callback' => $callback,
- 'parameters' => (is_array($params) ? $params : array($params)),
- );
+ 'parameters' => (is_array($params) ? $params : [$params]),
+ ];
}
else {
- $this->callbacks[$phase][] = array(
+ $this->callbacks[$phase][] = [
'callback' => $callback,
- 'parameters' => (is_array($params) ? $params : array($params)),
- );
+ 'parameters' => (is_array($params) ? $params : [$params]),
+ ];
}
}
/**
* @var array<Frame> stack of SQL transactions/savepoints
*/
- private $frames = array();
+ private $frames = [];
/**
* @var int
// internal state of each frame is consistent with its outcome
$oldFrames = $this->frames;
- $this->frames = array();
+ $this->frames = [];
foreach ($oldFrames as $oldFrame) {
$oldFrame->forceRollback();
}
*/
const REQUIREMENT_ERROR = 2;
- protected $system_checks = array(
+ protected $system_checks = [
'checkMemory',
'checkServerVariables',
'checkMysqlConnectExists',
'checkJsonEncodeExists',
'checkMultibyteExists',
- );
+ ];
- protected $database_checks = array(
+ protected $database_checks = [
'checkMysqlConnection',
'checkMysqlVersion',
'checkMysqlInnodb',
'checkMysqlThreadStack',
'checkMysqlLockTables',
'checkMysqlUtf8mb4',
- );
+ ];
/**
* Run all requirements tests.
* @return array
*/
public function checkSystem(array $file_paths) {
- $errors = array();
+ $errors = [];
$errors[] = $this->checkFilepathIsWritable($file_paths);
foreach ($this->system_checks as $check) {
* @return array
*/
public function checkDatabase(array $db_config) {
- $errors = array();
+ $errors = [];
foreach ($this->database_checks as $check) {
$errors[] = $this->$check($db_config);
$mem = $this->getPHPMemory();
$mem_string = ini_get('memory_limit');
- $results = array(
+ $results = [
'title' => 'CiviCRM memory check',
'severity' => $this::REQUIREMENT_OK,
'details' => "You have $mem_string allocated (minimum 32Mb, recommended 64Mb)",
- );
+ ];
if ($mem < $min && $mem > 0) {
$results['severity'] = $this::REQUIREMENT_ERROR;
* @return array
*/
public function checkServerVariables() {
- $results = array(
+ $results = [
'title' => 'CiviCRM PHP server variables',
'severity' => $this::REQUIREMENT_OK,
'details' => 'The required $_SERVER variables are set',
- );
+ ];
- $required_variables = array('SCRIPT_NAME', 'HTTP_HOST', 'SCRIPT_FILENAME');
- $missing = array();
+ $required_variables = ['SCRIPT_NAME', 'HTTP_HOST', 'SCRIPT_FILENAME'];
+ $missing = [];
foreach ($required_variables as $required_variable) {
if (empty($_SERVER[$required_variable])) {
* @return array
*/
public function checkJsonEncodeExists() {
- $results = array(
+ $results = [
'title' => 'CiviCRM JSON encoding support',
'severity' => $this::REQUIREMENT_OK,
'details' => 'Function json_encode() found',
- );
+ ];
if (!function_exists('json_encode')) {
$results['severity'] = $this::REQUIREMENT_ERROR;
$results['details'] = 'Function json_encode() does not exist';
* @return array
*/
public function checkMultibyteExists() {
- $results = array(
+ $results = [
'title' => 'CiviCRM MultiByte encoding support',
'severity' => $this::REQUIREMENT_OK,
'details' => 'PHP Multibyte etension found',
- );
+ ];
if (!function_exists('mb_substr')) {
$results['severity'] = $this::REQUIREMENT_ERROR;
$results['details'] = 'PHP Multibyte extension has not been installed and enabled';
* @return array
*/
public function checkMysqlConnectExists() {
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL check',
'severity' => $this::REQUIREMENT_OK,
'details' => 'Function mysqli_connect() found',
- );
+ ];
if (!function_exists('mysqli_connect')) {
$results['severity'] = $this::REQUIREMENT_ERROR;
$results['details'] = 'Function mysqli_connect() does not exist';
* @return array
*/
public function checkMysqlConnection(array $db_config) {
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL connection',
'severity' => $this::REQUIREMENT_OK,
'details' => "Connected",
- );
+ ];
$conn = $this->connect($db_config);
*/
public function checkMysqlVersion(array $db_config) {
$min = '5.1';
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL Version',
'severity' => $this::REQUIREMENT_OK,
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn || !($info = mysqli_get_server_info($conn))) {
* @return array
*/
public function checkMysqlInnodb(array $db_config) {
- $results = array(
+ $results = [
'title' => 'CiviCRM InnoDB support',
'severity' => $this::REQUIREMENT_ERROR,
'details' => 'Could not determine if MySQL has InnoDB support. Assuming none.',
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn) {
* @return array
*/
public function checkMysqlTempTables(array $db_config) {
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL Temp Tables',
'severity' => $this::REQUIREMENT_OK,
'details' => 'MySQL server supports temporary tables',
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn) {
* @return array
*/
public function checkMysqlTrigger($db_config) {
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL Trigger',
'severity' => $this::REQUIREMENT_OK,
'details' => 'Database supports MySQL triggers',
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn) {
* @return array
*/
public function checkMySQLAutoIncrementIncrementOne(array $db_config) {
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL AutoIncrementIncrement',
'severity' => $this::REQUIREMENT_OK,
'details' => 'MySQL server auto_increment_increment is 1',
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn) {
public function checkMysqlThreadStack($db_config) {
$min_thread_stack = 192;
- $results = array(
+ $results = [
'title' => 'CiviCRM Mysql thread stack',
'severity' => $this::REQUIREMENT_OK,
'details' => 'MySQL thread_stack is OK',
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn) {
* @return array
*/
public function checkMysqlLockTables($db_config) {
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL Lock Tables',
'severity' => $this::REQUIREMENT_OK,
'details' => 'Can successfully lock and unlock tables',
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn) {
* @return array
*/
public function checkFilepathIsWritable($file_paths) {
- $results = array(
+ $results = [
'title' => 'CiviCRM directories are writable',
'severity' => $this::REQUIREMENT_OK,
'details' => 'All required directories are writable: ' . implode(', ', $file_paths),
- );
+ ];
- $unwritable_dirs = array();
+ $unwritable_dirs = [];
foreach ($file_paths as $path) {
if (!is_writable($path)) {
$unwritable_dirs[] = $path;
* @return array
*/
public function checkMysqlUtf8mb4($db_config) {
- $results = array(
+ $results = [
'title' => 'CiviCRM MySQL utf8mb4 Support',
'severity' => $this::REQUIREMENT_OK,
'details' => 'Your system supports the MySQL utf8mb4 character set.',
- );
+ ];
$conn = $this->connect($db_config);
if (!$conn) {
/**
* @var array cache
*/
- private $cache = array();
+ private $cache = [];
/**
* @return \Civi\Payment\System
if ($id == 0) {
return new \CRM_Core_Payment_Manual();
}
- $processor = civicrm_api3('payment_processor', 'getsingle', array('id' => $id, 'is_test' => NULL));
+ $processor = civicrm_api3('payment_processor', 'getsingle', ['id' => $id, 'is_test' => NULL]);
return self::getByProcessor($processor);
}
* @throws \CiviCRM_API3_Exception
*/
public function getByName($name, $is_test) {
- $processor = civicrm_api3('payment_processor', 'getsingle', array('name' => $name, 'is_test' => $is_test));
+ $processor = civicrm_api3('payment_processor', 'getsingle', ['name' => $name, 'is_test' => $is_test]);
return self::getByProcessor($processor);
}
* This is particularly used for tests.
*/
public function flushProcessors() {
- $this->cache = array();
+ $this->cache = [];
\CRM_Financial_BAO_PaymentProcessor::getAllPaymentProcessors('all', TRUE);
\CRM_Financial_BAO_PaymentProcessor::getAllPaymentProcessors('live', TRUE);
\CRM_Financial_BAO_PaymentProcessor::getAllPaymentProcessors('test', TRUE);
* @throws \CiviCRM_API3_Exception
*/
public function getByClass($className) {
- return $this->getByProcessor(array(
+ return $this->getByProcessor([
'class_name' => $className,
'id' => 0,
'is_test' => 0,
- ),
+ ],
TRUE);
}
/**
* @var array
*/
- private static $singletons = array();
+ private static $singletons = [];
/**
* Get the data source used for testing.
try {
self::$singletons['pdo'] = new PDO("mysql:host={$host}" . ($port ? ";port=$port" : ""),
$dsninfo['username'], $dsninfo['password'],
- array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE)
+ [PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE]
);
}
catch (PDOException $e) {
// Attempt to convert lowercase action name to CamelCase.
// This is clunky/imperfect due to the convention of all lowercase actions.
$exampleName = \CRM_Utils_String::convertStringToCamel($action);
- $knownPrefixes = array(
+ $knownPrefixes = [
'Get',
'Set',
'Create',
'Update',
'Send',
- );
+ ];
foreach ($knownPrefixes as $prefix) {
if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
$exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
unset($params['version']);
}
// Format multiline description as array
- $desc = array();
+ $desc = [];
if (is_string($description) && strlen($description)) {
foreach (explode("\n", $description) as $line) {
$desc[] = trim($line);
if (!is_array($result)) {
return;
}
- $fieldsToChange = array(
+ $fieldsToChange = [
'hash' => '67eac7789eaee00',
'modified_date' => '2012-11-14 16:02:35',
'created_date' => '2013-07-28 08:49:19',
'end_date' => '2013-08-04 00:00:00',
'event_end_date' => '2013-08-04 00:00:00',
'decision_date' => '20130805000000',
- );
+ ];
- $keysToUnset = array('xdebug', 'undefined_fields');
+ $keysToUnset = ['xdebug', 'undefined_fields'];
foreach ($keysToUnset as $unwantedKey) {
if (isset($result[$unwantedKey])) {
unset($result[$unwantedKey]);
* @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'));
+ public function assertAPIArrayComparison($result, $expected, $valuesToExclude = [], $prefix = '') {
+ $valuesToExclude = array_merge($valuesToExclude, ['debug', 'xdebug', 'sequential']);
foreach ($valuesToExclude as $value) {
if (isset($result[$value])) {
unset($result[$value]);
* @param $id
*/
public function assertAPIDeleted($entity, $id) {
- $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
+ $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0);
}
/**
*/
public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
if (is_array($params)) {
- $params += array(
+ $params += [
'version' => $this->_apiversion,
- );
+ ];
}
$result = $this->civicrm_api($entity, $action, $params);
$this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
* @return array|int
*/
public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
- $params = array_merge(array(
+ $params = array_merge([
'version' => $this->_apiversion,
'debug' => 1,
- ),
+ ],
$params
);
switch (strtolower($action)) {
* @return array|int
*/
public function callAPISuccessGetCount($entity, $params, $count = NULL) {
- $params += array(
+ $params += [
'version' => $this->_apiversion,
'debug' => 1,
- );
+ ];
$result = $this->civicrm_api($entity, 'getcount', $params);
if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) {
throw new \Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
* @return array|int
*/
public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
- $params += array(
+ $params += [
'version' => $this->_apiversion,
- );
+ ];
$result = $this->civicrm_api($entity, 'getsingle', $params);
if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
$unfilteredResult = $this->civicrm_api($entity, 'get', $params);
* @return array|int
*/
public function callAPISuccessGetValue($entity, $params, $type = NULL) {
- $params += array(
+ $params += [
'version' => $this->_apiversion,
'debug' => 1,
- );
+ ];
$result = $this->civicrm_api($entity, 'getvalue', $params);
if (is_array($result) && (!empty($result['is_error']) || isset($result['values']))) {
throw new \Exception('Invalid getvalue result' . print_r($result, TRUE));
class CiviEnvBuilder {
protected $name;
- private $steps = array();
+ private $steps = [];
/**
* @var string|NULL
}
public function isValid() {
- if (!in_array($this->action, array('install', 'uninstall'))) {
+ if (!in_array($this->action, ['install', 'uninstall'])) {
return FALSE;
}
foreach ($this->names as $name) {
public function getSig() {
- return implode(' ', array(
+ return implode(' ', [
$this->file,
filemtime($this->file),
filectime($this->file),
- ));
+ ]);
}
public function isValid() {
* Ex: $cache['Some_Test_Class']['civicrm_foobar'] = 'hook_civicrm_foobar';
* Array(string $testClass => Array(string $hookName => string $methodName)).
*/
- private $cache = array();
+ private $cache = [];
/**
* @var \CRM_Core_Transaction|NULL
}
public function endTestSuite(\PHPUnit_Framework_TestSuite $suite) {
- $this->cache = array();
+ $this->cache = [];
}
public function startTest(\PHPUnit_Framework_Test $test) {
protected function findTestHooks(HookInterface $test) {
$class = get_class($test);
if (!isset($this->cache[$class])) {
- $funcs = array();
+ $funcs = [];
foreach (get_class_methods($class) as $func) {
if (preg_match('/^hook_/', $func)) {
$funcs[substr($func, 5)] = $func;
/** @var \CRM_Utils_Hook_UnitTests $hooks */
$hooks = \CRM_Utils_Hook::singleton();
foreach ($this->findTestHooks($test) as $hook => $func) {
- $hooks->setHook($hook, array($test, $func));
+ $hooks->setHook($hook, [$test, $func]);
}
}
*/
protected function cv($cmd, $decode = 'json') {
$cmd = 'cv ' . $cmd;
- $descriptorSpec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => STDERR);
+ $descriptorSpec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => STDERR];
$oldOutput = getenv('CV_OUTPUT');
putenv("CV_OUTPUT=json");
$process = proc_open($cmd, $descriptorSpec, $pipes, __DIR__);
* @return array
*/
protected function indexTestsByInterface($tests) {
- $byInterface = array('HeadlessInterface' => array(), 'EndToEndInterface' => array());
+ $byInterface = ['HeadlessInterface' => [], 'EndToEndInterface' => []];
foreach ($tests as $test) {
/** @var \PHPUnit_Framework_Test $test */
if ($test instanceof HeadlessInterface) {
\Civi\Test::schema()->setStrict(TRUE);
// Rebuild triggers
- civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
+ civicrm_api('system', 'flush', ['version' => 3, 'triggers' => 1]);
- \CRM_Core_BAO_ConfigSetting::setEnabledComponents(array(
+ \CRM_Core_BAO_ConfigSetting::setEnabledComponents([
'CiviEvent',
'CiviContribute',
'CiviMember',
'CiviMail',
'CiviReport',
'CiviPledge',
- ));
+ ]);
return TRUE;
}
$pdo->quote($type)
);
$tables = $pdo->query($query);
- $result = array();
+ $result = [];
foreach ($tables as $table) {
$result[] = $table['table_name'];
}
public function setStrict($checks) {
$dbName = \Civi\Test::dsn('database');
if ($checks) {
- $queries = array(
+ $queries = [
"USE {$dbName};",
"SET global innodb_flush_log_at_trx_commit = 1;",
"SET SQL_MODE='STRICT_ALL_TABLES';",
"SET foreign_key_checks = 1;",
- );
+ ];
}
else {
- $queries = array(
+ $queries = [
"USE {$dbName};",
"SET foreign_key_checks = 0",
"SET SQL_MODE='STRICT_ALL_TABLES';",
"SET global innodb_flush_log_at_trx_commit = 2;",
- );
+ ];
}
foreach ($queries as $query) {
if (\Civi\Test::execute($query) === FALSE) {
}
public function dropAll() {
- $queries = array();
+ $queries = [];
foreach ($this->getTables('VIEW') as $table) {
if (preg_match('/^(civicrm_|log_)/', $table)) {
$queries[] = "DROP VIEW $table";
public function truncateAll() {
$tables = \Civi\Test::schema()->getTables('BASE TABLE');
- $truncates = array();
- $drops = array();
+ $truncates = [];
+ $drops = [];
foreach ($tables as $table) {
// skip log tables
if (substr($table, 0, 4) == 'log_') {
abstract class AbstractTokenSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
- return array(
+ return [
Events::TOKEN_REGISTER => 'registerTokens',
Events::TOKEN_EVALUATE => 'evaluateTokens',
\Civi\ActionSchedule\Events::MAILING_QUERY => 'alterActionScheduleQuery',
- );
+ ];
}
/**
* @param array $tokenNames
* Array(string $tokenName => string $label).
*/
- public function __construct($entity, $tokenNames = array()) {
+ public function __construct($entity, $tokenNames = []) {
$this->entity = $entity;
$this->tokenNames = $tokenNames;
}
return;
}
foreach ($this->tokenNames as $name => $label) {
- $e->register(array(
+ $e->register([
'entity' => $this->entity,
'field' => $name,
'label' => $label,
- ));
+ ]);
}
}
$params = $paramsOrField;
}
else {
- $params = array(
+ $params = [
'field' => $paramsOrField,
'label' => $label,
- );
+ ];
}
$params = array_merge($this->defaults, $params);
$this->tokenProcessor->addToken($params);
* @inheritDoc
*/
public static function getSubscribedEvents() {
- return array(
+ return [
Events::TOKEN_EVALUATE => 'onEvaluate',
Events::TOKEN_RENDER => 'onRender',
- );
+ ];
}
/**
// hook *categories* (aka entities aka namespaces). We'll cache
// this in the TokenProcessor's context.
- $hookTokens = array();
+ $hookTokens = [];
\CRM_Utils_Hook::tokens($hookTokens);
$categories = array_keys($hookTokens);
$e->getTokenProcessor()->context['hookTokenCategories'] = $categories;
/** @var int $contactId */
$contactId = $row->context['contactId'];
if (empty($row->context['contact'])) {
- $params = array(
- array('contact_id', '=', $contactId, 0, 0),
- );
+ $params = [
+ ['contact_id', '=', $contactId, 0, 0],
+ ];
list($contact, $_) = \CRM_Contact_BAO_Query::apiQuery($params);
$contact = reset($contact); //CRM-4524
if (!$contact || is_a($contact, 'CRM_Core_Error')) {
if (!empty($messageTokens['contact'])) {
foreach ($messageTokens['contact'] as $token) {
if (\CRM_Core_BAO_CustomField::getKeyID($token)) {
- $contact[$token] = civicrm_api3('Contact', 'getvalue', array(
+ $contact[$token] = civicrm_api3('Contact', 'getvalue', [
'return' => $token,
'id' => $contactId,
- ));
+ ]);
}
}
}
$contact = array_merge($contact, $row->context['tmpTokenParams']);
}
- $contactArray = !is_array($contactId) ? array($contactId => $contact) : $contact;
+ $contactArray = !is_array($contactId) ? [$contactId => $contact] : $contact;
// Note: This is a small contract change from the past; data should be missing
// less randomly.
* @return TokenProcessor
*/
public function addMessage($name, $value, $format) {
- $this->messages[$name] = array(
+ $this->messages[$name] = [
'string' => $value,
'format' => $format,
'tokens' => \CRM_Utils_Token::getTokens($value),
- );
+ ];
return $this;
}
*/
public function addRow() {
$key = $this->next++;
- $this->rowContexts[$key] = array();
- $this->rowValues[$key] = array(
- 'text/plain' => array(),
- 'text/html' => array(),
- );
+ $this->rowContexts[$key] = [];
+ $this->rowValues[$key] = [
+ 'text/plain' => [],
+ 'text/html' => [],
+ ];
return new TokenRow($this, $key);
}
* @return array
*/
public function getMessageTokens() {
- $tokens = array();
+ $tokens = [];
foreach ($this->messages as $message) {
$tokens = \CRM_Utils_Array::crmArrayMerge($tokens, $message['tokens']);
}
*/
public function getTokens() {
if ($this->tokens === NULL) {
- $this->tokens = array();
- $event = new TokenRegisterEvent($this, array('entity' => 'undefined'));
+ $this->tokens = [];
+ $event = new TokenRegisterEvent($this, ['entity' => 'undefined']);
$this->dispatcher->dispatch(Events::TOKEN_REGISTER, $event);
}
return $this->tokens;
*/
public function listTokens() {
if ($this->listTokens === NULL) {
- $this->listTokens = array();
+ $this->listTokens = [];
foreach ($this->getTokens() as $token => $values) {
$this->listTokens['{' . $token . '}'] = $values['label'];
}
// FIXME preg_callback.
$tokens = $this->rowValues[$row->tokenRow][$message['format']];
- $flatTokens = array();
+ $flatTokens = [];
\CRM_Utils_Array::flatten($tokens, $flatTokens, '', '.');
- $filteredTokens = array();
+ $filteredTokens = [];
foreach ($flatTokens as $k => $v) {
$filteredTokens['{' . $k . '}'] = ($useSmarty ? \CRM_Utils_Token::tokenEscapeSmarty($v) : $v);
}
}
if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/html'])) {
- $this->tokenProcessor->rowValues[$this->tokenRow]['text/html'] = array();
+ $this->tokenProcessor->rowValues[$this->tokenRow]['text/html'] = [];
}
if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'])) {
- $this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'] = array();
+ $this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'] = [];
}
$htmlTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/html'];
case 'text/html':
// Plain => HTML.
foreach ($textTokens as $entity => $values) {
- $entityFields = civicrm_api3($entity, "getFields", array('api_action' => 'get'));
+ $entityFields = civicrm_api3($entity, "getFields", ['api_action' => 'get']);
foreach ($values as $field => $value) {
if (!isset($htmlTokens[$entity][$field])) {
// CRM-18420 - Activity Details Field are enclosed within <p>,