From: Coleman Watts Date: Fri, 29 Mar 2019 01:10:29 +0000 (-0400) Subject: NFC - Short array syntax - auto-convert Civi dir X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=c64f69d9efe28a677084a1da2420f4c613ec169b;p=civicrm-core.git NFC - Short array syntax - auto-convert Civi dir --- diff --git a/Civi/API/Api3SelectQuery.php b/Civi/API/Api3SelectQuery.php index 4c0c986112..d036484d2a 100644 --- a/Civi/API/Api3SelectQuery.php +++ b/Civi/API/Api3SelectQuery.php @@ -36,7 +36,7 @@ class Api3SelectQuery extends SelectQuery { * @inheritDoc */ protected function buildWhereClause() { - $filters = array(); + $filters = []; foreach ($this->where as $key => $value) { $table_name = NULL; $column_name = NULL; @@ -45,7 +45,7 @@ class Api3SelectQuery extends SelectQuery { // 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'; } @@ -54,12 +54,12 @@ class Api3SelectQuery extends SelectQuery { 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') { @@ -110,7 +110,7 @@ class Api3SelectQuery extends SelectQuery { } $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); } @@ -121,10 +121,10 @@ class Api3SelectQuery extends SelectQuery { $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"); @@ -147,11 +147,11 @@ class Api3SelectQuery extends SelectQuery { 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']; } @@ -174,7 +174,7 @@ class Api3SelectQuery extends SelectQuery { 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; } diff --git a/Civi/API/Events.php b/Civi/API/Events.php index 81f7475197..9051f75d2b 100644 --- a/Civi/API/Events.php +++ b/Civi/API/Events.php @@ -96,13 +96,13 @@ class Events { * @return array */ public static function allEvents() { - return array( + return [ self::AUTHORIZE, self::EXCEPTION, self::PREPARE, self::RESOLVE, self::RESPOND, - ); + ]; } /** diff --git a/Civi/API/Exception/NotImplementedException.php b/Civi/API/Exception/NotImplementedException.php index f2df795ca3..0c263d4f8b 100644 --- a/Civi/API/Exception/NotImplementedException.php +++ b/Civi/API/Exception/NotImplementedException.php @@ -18,7 +18,7 @@ class NotImplementedException extends \API_Exception { * @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); } diff --git a/Civi/API/Exception/UnauthorizedException.php b/Civi/API/Exception/UnauthorizedException.php index 0235f1f440..e35cf3faa3 100644 --- a/Civi/API/Exception/UnauthorizedException.php +++ b/Civi/API/Exception/UnauthorizedException.php @@ -18,7 +18,7 @@ class UnauthorizedException extends \API_Exception { * @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); } diff --git a/Civi/API/ExternalBatch.php b/Civi/API/ExternalBatch.php index 6a8d463e14..d2f039a854 100644 --- a/Civi/API/ExternalBatch.php +++ b/Civi/API/ExternalBatch.php @@ -46,7 +46,7 @@ class ExternalBatch { * @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; @@ -65,14 +65,14 @@ class ExternalBatch { * @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; } @@ -124,15 +124,15 @@ class ExternalBatch { 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; @@ -183,7 +183,7 @@ class ExternalBatch { * @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 @@ -214,9 +214,9 @@ class ExternalBatch { } $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); } diff --git a/Civi/API/Kernel.php b/Civi/API/Kernel.php index 986c7ad149..96167a8e8e 100644 --- a/Civi/API/Kernel.php +++ b/Civi/API/Kernel.php @@ -55,7 +55,7 @@ class Kernel { * @param array $apiProviders * Array of ProviderInterface. */ - public function __construct($dispatcher, $apiProviders = array()) { + public function __construct($dispatcher, $apiProviders = []) { $this->apiProviders = $apiProviders; $this->dispatcher = $dispatcher; } @@ -223,7 +223,7 @@ class Kernel { 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]; } /** @@ -285,7 +285,7 @@ class Kernel { */ 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)); @@ -305,7 +305,7 @@ class Kernel { */ 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)); @@ -324,7 +324,7 @@ class Kernel { * API response. */ public function formatException($e, $apiRequest) { - $data = array(); + $data = []; if (!empty($apiRequest['params']['debug'])) { $data['trace'] = $e->getTraceAsString(); } @@ -362,7 +362,7 @@ class Kernel { * 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()); diff --git a/Civi/API/Provider/AdhocProvider.php b/Civi/API/Provider/AdhocProvider.php index 758287997b..4a03ed0486 100644 --- a/Civi/API/Provider/AdhocProvider.php +++ b/Civi/API/Provider/AdhocProvider.php @@ -42,20 +42,20 @@ class AdhocProvider implements EventSubscriberInterface, ProviderInterface { // 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 @@ -90,10 +90,10 @@ class AdhocProvider implements EventSubscriberInterface, ProviderInterface { * @return AdhocProvider */ public function addAction($name, $perm, $callback) { - $this->actions[strtolower($name)] = array( + $this->actions[strtolower($name)] = [ 'perm' => $perm, 'callback' => $callback, - ); + ]; return $this; } @@ -137,7 +137,7 @@ class AdhocProvider implements EventSubscriberInterface, ProviderInterface { * @return array */ public function getEntityNames($version) { - return array($this->entity); + return [$this->entity]; } /** @@ -151,7 +151,7 @@ class AdhocProvider implements EventSubscriberInterface, ProviderInterface { return array_keys($this->actions); } else { - return array(); + return []; } } diff --git a/Civi/API/Provider/MagicFunctionProvider.php b/Civi/API/Provider/MagicFunctionProvider.php index 1b44dd931a..27324e452e 100644 --- a/Civi/API/Provider/MagicFunctionProvider.php +++ b/Civi/API/Provider/MagicFunctionProvider.php @@ -39,11 +39,11 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa * @return array */ public static function getSubscribedEvents() { - return array( - Events::RESOLVE => array( - array('onApiResolve', Events::W_MIDDLE), - ), - ); + return [ + Events::RESOLVE => [ + ['onApiResolve', Events::W_MIDDLE], + ], + ]; } /** @@ -54,7 +54,7 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa /** */ public function __construct() { - $this->cache = array(); + $this->cache = []; } /** @@ -108,12 +108,12 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa * @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; } @@ -137,7 +137,7 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa } } } - $entities = array_diff($entities, array('Generic')); + $entities = array_diff($entities, ['Generic']); $entities = array_unique($entities); sort($entities); @@ -154,12 +154,12 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa $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) { @@ -203,21 +203,21 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa // 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]; } } @@ -227,23 +227,23 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa 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]; } @@ -285,12 +285,12 @@ class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterfa } // 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; } diff --git a/Civi/API/Provider/ReflectionProvider.php b/Civi/API/Provider/ReflectionProvider.php index 8dbef5c8b1..48a680d29f 100644 --- a/Civi/API/Provider/ReflectionProvider.php +++ b/Civi/API/Provider/ReflectionProvider.php @@ -38,16 +38,16 @@ class ReflectionProvider implements EventSubscriberInterface, ProviderInterface * @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], + ], + ]; } /** @@ -66,10 +66,10 @@ class ReflectionProvider implements EventSubscriberInterface, ProviderInterface */ public function __construct($apiKernel) { $this->apiKernel = $apiKernel; - $this->actions = array( - 'Entity' => array('get', 'getactions'), - '*' => array('getactions'), // 'getfields' - ); + $this->actions = [ + 'Entity' => ['get', 'getactions'], + '*' => ['getactions'], // 'getfields' + ]; } /** @@ -133,7 +133,7 @@ class ReflectionProvider implements EventSubscriberInterface, ProviderInterface * @return array */ public function getEntityNames($version) { - return array('Entity'); + return ['Entity']; } /** diff --git a/Civi/API/Provider/StaticProvider.php b/Civi/API/Provider/StaticProvider.php index 0745f23fc5..f4e2701e05 100644 --- a/Civi/API/Provider/StaticProvider.php +++ b/Civi/API/Provider/StaticProvider.php @@ -44,14 +44,14 @@ class StaticProvider extends AdhocProvider { * @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], + ], + ]; } /** @@ -66,21 +66,21 @@ class StaticProvider extends AdhocProvider { * @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']); } /** @@ -111,7 +111,7 @@ class StaticProvider extends AdhocProvider { } else { $id = max(array_keys($this->records)) + 1; - $this->records[$id] = array(); + $this->records[$id] = []; } if (!isset($this->records[$id])) { @@ -150,7 +150,7 @@ class StaticProvider extends AdhocProvider { if ($id && isset($this->records[$id])) { unset($this->records[$id]); } - return civicrm_api3_create_success(array()); + return civicrm_api3_create_success([]); } } diff --git a/Civi/API/Request.php b/Civi/API/Request.php index dbf0cb1ee8..b40ece71e7 100644 --- a/Civi/API/Request.php +++ b/Civi/API/Request.php @@ -62,7 +62,7 @@ class Request { $version = \CRM_Utils_Array::value('version', $params); switch ($version) { default: - $apiRequest = array(); + $apiRequest = []; $apiRequest['id'] = self::$nextId++; $apiRequest['version'] = (int) $version; $apiRequest['params'] = $params; @@ -73,7 +73,7 @@ class Request { 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!)"); } diff --git a/Civi/API/SelectQuery.php b/Civi/API/SelectQuery.php index 80d552bd67..9a03d7eb39 100644 --- a/Civi/API/SelectQuery.php +++ b/Civi/API/SelectQuery.php @@ -50,15 +50,15 @@ abstract class SelectQuery { * @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 */ @@ -70,7 +70,7 @@ abstract class SelectQuery { /** * @var array */ - protected $joins = array(); + protected $joins = []; /** * @var array */ @@ -82,7 +82,7 @@ abstract class SelectQuery { /** * @var array */ - protected $aclFields = array(); + protected $aclFields = []; /** * @var string|bool */ @@ -139,7 +139,7 @@ abstract class SelectQuery { $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()) { @@ -147,7 +147,7 @@ abstract class SelectQuery { $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); @@ -240,7 +240,7 @@ abstract class SelectQuery { // 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) ); @@ -259,7 +259,7 @@ abstract class SelectQuery { $fkField = &$fkField['FKApiSpec'][$fieldName]; $prev = $tableAlias; } - return array($tableAlias, $fieldName); + return [$tableAlias, $fieldName]; } /** @@ -300,8 +300,8 @@ abstract class SelectQuery { $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]; } /** @@ -330,7 +330,7 @@ abstract class SelectQuery { $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]; } @@ -348,11 +348,11 @@ abstract class SelectQuery { 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) { @@ -377,15 +377,15 @@ abstract class SelectQuery { * @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) { diff --git a/Civi/API/Subscriber/APIv3SchemaAdapter.php b/Civi/API/Subscriber/APIv3SchemaAdapter.php index 649ec9c7cc..af77d3b7ea 100644 --- a/Civi/API/Subscriber/APIv3SchemaAdapter.php +++ b/Civi/API/Subscriber/APIv3SchemaAdapter.php @@ -39,12 +39,12 @@ class APIv3SchemaAdapter implements EventSubscriberInterface { * @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], + ], + ]; } /** @@ -96,7 +96,7 @@ class APIv3SchemaAdapter implements EventSubscriberInterface { * @return array */ public function getDefaults($fields) { - $defaults = array(); + $defaults = []; foreach ($fields as $field => $values) { if (isset($values['api.default'])) { @@ -112,7 +112,7 @@ class APIv3SchemaAdapter implements EventSubscriberInterface { * @return array */ public function getRequired($fields) { - $required = array('version'); + $required = ['version']; foreach ($fields as $field => $values) { if (!empty($values['api.required'])) { diff --git a/Civi/API/Subscriber/ChainSubscriber.php b/Civi/API/Subscriber/ChainSubscriber.php index cc27ba3bc8..5fb27c1ed6 100644 --- a/Civi/API/Subscriber/ChainSubscriber.php +++ b/Civi/API/Subscriber/ChainSubscriber.php @@ -54,9 +54,9 @@ class ChainSubscriber implements EventSubscriberInterface { * @return array */ public static function getSubscribedEvents() { - return array( - Events::RESPOND => array('onApiRespond', Events::W_EARLY), - ); + return [ + Events::RESPOND => ['onApiRespond', Events::W_EARLY], + ]; } /** @@ -93,7 +93,7 @@ class ChainSubscriber implements EventSubscriberInterface { // 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; } @@ -102,7 +102,7 @@ class ChainSubscriber implements EventSubscriberInterface { // $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') { @@ -110,7 +110,7 @@ class ChainSubscriber implements EventSubscriberInterface { // '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]; @@ -120,18 +120,18 @@ class ChainSubscriber implements EventSubscriberInterface { $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; } diff --git a/Civi/API/Subscriber/DynamicFKAuthorization.php b/Civi/API/Subscriber/DynamicFKAuthorization.php index daddd72af9..03ba52d0b4 100644 --- a/Civi/API/Subscriber/DynamicFKAuthorization.php +++ b/Civi/API/Subscriber/DynamicFKAuthorization.php @@ -51,11 +51,11 @@ class DynamicFKAuthorization implements EventSubscriberInterface { * @return array */ public static function getSubscribedEvents() { - return array( - Events::AUTHORIZE => array( - array('onApiAuthorize', Events::W_EARLY), - ), - ); + return [ + Events::AUTHORIZE => [ + ['onApiAuthorize', Events::W_EARLY], + ], + ]; } /** @@ -146,7 +146,7 @@ class DynamicFKAuthorization implements EventSubscriberInterface { $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"); } @@ -229,17 +229,17 @@ class DynamicFKAuthorization implements EventSubscriberInterface { \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, - )); + ]); } }); @@ -325,25 +325,25 @@ class DynamicFKAuthorization implements EventSubscriberInterface { * @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]; } } @@ -363,14 +363,14 @@ class DynamicFKAuthorization implements EventSubscriberInterface { */ 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; } diff --git a/Civi/API/Subscriber/I18nSubscriber.php b/Civi/API/Subscriber/I18nSubscriber.php index b1284a3648..632064f3cf 100644 --- a/Civi/API/Subscriber/I18nSubscriber.php +++ b/Civi/API/Subscriber/I18nSubscriber.php @@ -39,9 +39,9 @@ class I18nSubscriber implements EventSubscriberInterface { * @return array */ public static function getSubscribedEvents() { - return array( - Events::PREPARE => array('onApiPrepare', Events::W_MIDDLE), - ); + return [ + Events::PREPARE => ['onApiPrepare', Events::W_MIDDLE], + ]; } /** @@ -80,7 +80,7 @@ class I18nSubscriber implements EventSubscriberInterface { // 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; } @@ -89,7 +89,7 @@ class I18nSubscriber implements EventSubscriberInterface { $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])); } } diff --git a/Civi/API/Subscriber/PermissionCheck.php b/Civi/API/Subscriber/PermissionCheck.php index aca26888cc..0a8248ef57 100644 --- a/Civi/API/Subscriber/PermissionCheck.php +++ b/Civi/API/Subscriber/PermissionCheck.php @@ -40,11 +40,11 @@ class PermissionCheck implements EventSubscriberInterface { * @return array */ public static function getSubscribedEvents() { - return array( - Events::AUTHORIZE => array( - array('onApiAuthorize', Events::W_LATE), - ), - ); + return [ + Events::AUTHORIZE => [ + ['onApiAuthorize', Events::W_LATE], + ], + ]; } /** @@ -122,8 +122,8 @@ class PermissionCheck implements EventSubscriberInterface { 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; } diff --git a/Civi/API/Subscriber/TransactionSubscriber.php b/Civi/API/Subscriber/TransactionSubscriber.php index 3e7c08da79..8b110ab70c 100644 --- a/Civi/API/Subscriber/TransactionSubscriber.php +++ b/Civi/API/Subscriber/TransactionSubscriber.php @@ -48,17 +48,17 @@ class TransactionSubscriber implements EventSubscriberInterface { * @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) @@ -66,7 +66,7 @@ class TransactionSubscriber implements EventSubscriberInterface { * 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. diff --git a/Civi/API/Subscriber/WhitelistSubscriber.php b/Civi/API/Subscriber/WhitelistSubscriber.php index 6362a1a33f..3c69c04af1 100644 --- a/Civi/API/Subscriber/WhitelistSubscriber.php +++ b/Civi/API/Subscriber/WhitelistSubscriber.php @@ -46,10 +46,10 @@ class WhitelistSubscriber implements EventSubscriberInterface { * @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], + ]; } /** @@ -73,7 +73,7 @@ class WhitelistSubscriber implements EventSubscriberInterface { * @throws \CRM_Core_Exception */ public function __construct($rules) { - $this->rules = array(); + $this->rules = []; foreach ($rules as $rule) { /** @var WhitelistRule $rule */ if ($rule->isValid()) { diff --git a/Civi/API/Subscriber/WrapperAdapter.php b/Civi/API/Subscriber/WrapperAdapter.php index 78410f705b..736aa548bd 100644 --- a/Civi/API/Subscriber/WrapperAdapter.php +++ b/Civi/API/Subscriber/WrapperAdapter.php @@ -41,10 +41,10 @@ class WrapperAdapter implements EventSubscriberInterface { * @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], + ]; } /** @@ -56,7 +56,7 @@ class WrapperAdapter implements EventSubscriberInterface { * @param array $defaults * array(\API_Wrapper). */ - public function __construct($defaults = array()) { + public function __construct($defaults = []) { $this->defaults = $defaults; } diff --git a/Civi/API/Subscriber/XDebugSubscriber.php b/Civi/API/Subscriber/XDebugSubscriber.php index 2056f0d5b2..294ed9fd23 100644 --- a/Civi/API/Subscriber/XDebugSubscriber.php +++ b/Civi/API/Subscriber/XDebugSubscriber.php @@ -39,9 +39,9 @@ class XDebugSubscriber implements EventSubscriberInterface { * @return array */ public static function getSubscribedEvents() { - return array( - Events::RESPOND => array('onApiRespond', Events::W_LATE), - ); + return [ + Events::RESPOND => ['onApiRespond', Events::W_LATE], + ]; } /** diff --git a/Civi/API/WhitelistRule.php b/Civi/API/WhitelistRule.php index 0090638f67..50d5b3e232 100644 --- a/Civi/API/WhitelistRule.php +++ b/Civi/API/WhitelistRule.php @@ -48,7 +48,7 @@ namespace Civi\API; */ class WhitelistRule { - static $IGNORE_FIELDS = array( + static $IGNORE_FIELDS = [ 'check_permissions', 'debug', 'offset', @@ -61,7 +61,7 @@ class WhitelistRule { 'sequential', 'sort', 'version', - ); + ]; /** * Create a batch of rules from an array. @@ -70,7 +70,7 @@ class WhitelistRule { * @return array */ public static function createAll($rules) { - $whitelist = array(); + $whitelist = []; foreach ($rules as $rule) { $whitelist[] = new WhitelistRule($rule); } @@ -126,7 +126,7 @@ class WhitelistRule { $this->actions = '*'; } else { - $this->actions = array(); + $this->actions = []; foreach ((array) $ruleSpec['actions'] as $action) { $this->actions[] = Request::normalizeActionName($action, $ruleSpec['version']); } @@ -197,7 +197,7 @@ class WhitelistRule { // 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)); } @@ -267,7 +267,7 @@ class WhitelistRule { * List of acceptable keys. */ protected function filterFields($keys) { - $r = array(); + $r = []; foreach ($keys as $key) { if (in_array($key, $this->fields)) { $r[] = $key; diff --git a/Civi/ActionSchedule/Event/MappingRegisterEvent.php b/Civi/ActionSchedule/Event/MappingRegisterEvent.php index cd350bd075..9392dbd984 100644 --- a/Civi/ActionSchedule/Event/MappingRegisterEvent.php +++ b/Civi/ActionSchedule/Event/MappingRegisterEvent.php @@ -16,7 +16,7 @@ class MappingRegisterEvent extends Event { * @var array * Array(scalar $id => Mapping $mapping). */ - protected $mappings = array(); + protected $mappings = []; /** * Register a new mapping. diff --git a/Civi/ActionSchedule/Mapping.php b/Civi/ActionSchedule/Mapping.php index 4ccf57f881..1040a5012a 100644 --- a/Civi/ActionSchedule/Mapping.php +++ b/Civi/ActionSchedule/Mapping.php @@ -63,7 +63,7 @@ namespace Civi\ActionSchedule; */ abstract class Mapping implements MappingInterface { - private static $fields = array( + private static $fields = [ 'id', 'entity', 'entity_label', @@ -73,7 +73,7 @@ abstract class Mapping implements MappingInterface { 'entity_status_label', 'entity_date_start', 'entity_date_end', - ); + ]; /** * Create mapping. @@ -229,7 +229,7 @@ abstract class Mapping implements MappingInterface { return \CRM_Core_OptionGroup::values('auto_renew_options'); } else { - return array(); + return []; } } return self::getValueLabelMap($this->entity_status); @@ -242,7 +242,7 @@ abstract class Mapping implements MappingInterface { * 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)); } @@ -263,7 +263,7 @@ abstract class Mapping implements MappingInterface { * Ex: array('assignee' => 'Activity Assignee'). */ public function getRecipientTypes() { - return array(); + return []; } /** @@ -280,7 +280,7 @@ abstract class Mapping implements MappingInterface { * @see getRecipientTypes */ public function getRecipientListing($recipientType) { - return array(); + return []; } protected static function getValueLabelMap($name) { @@ -300,11 +300,11 @@ abstract class Mapping implements MappingInterface { $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']; @@ -326,7 +326,7 @@ abstract class Mapping implements MappingInterface { * List of error messages. */ public function validateSchedule($schedule) { - return array(); + return []; } /** diff --git a/Civi/ActionSchedule/RecipientBuilder.php b/Civi/ActionSchedule/RecipientBuilder.php index b72bbdada5..d979b94677 100644 --- a/Civi/ActionSchedule/RecipientBuilder.php +++ b/Civi/ActionSchedule/RecipientBuilder.php @@ -182,7 +182,7 @@ class RecipientBuilder { // 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. @@ -241,7 +241,7 @@ class RecipientBuilder { $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') @@ -279,13 +279,13 @@ class RecipientBuilder { ->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(); @@ -296,7 +296,7 @@ class RecipientBuilder { 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() ); @@ -314,7 +314,7 @@ class RecipientBuilder { $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() @@ -326,14 +326,14 @@ class RecipientBuilder { ->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(); @@ -344,7 +344,7 @@ class RecipientBuilder { 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() ); @@ -358,12 +358,12 @@ class RecipientBuilder { * @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); @@ -419,12 +419,12 @@ class RecipientBuilder { $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); @@ -481,7 +481,7 @@ class RecipientBuilder { */ 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'); @@ -536,9 +536,9 @@ WHERE $group.id = {$groupId} return \CRM_Utils_SQL_Select::fragment() ->where("@casNow <= !repetitionEndDate") - ->param(array( + ->param([ '!repetitionEndDate' => $repeatEventDateExpr, - )); + ]); } /** @@ -574,30 +574,30 @@ WHERE $group.id = {$groupId} $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; @@ -619,12 +619,12 @@ WHERE $group.id = {$groupId} * @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'); diff --git a/Civi/Angular/AngularLoader.php b/Civi/Angular/AngularLoader.php index e16cab3419..181c8d2c93 100644 --- a/Civi/Angular/AngularLoader.php +++ b/Civi/Angular/AngularLoader.php @@ -74,7 +74,7 @@ class AngularLoader { $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 = []; } /** @@ -89,42 +89,42 @@ class AngularLoader { 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; }); @@ -190,14 +190,14 @@ class AngularLoader { * @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; } diff --git a/Civi/Angular/ChangeSet.php b/Civi/Angular/ChangeSet.php index f3cb2db35b..f0eb38148c 100644 --- a/Civi/Angular/ChangeSet.php +++ b/Civi/Angular/ChangeSet.php @@ -82,7 +82,7 @@ class ChangeSet implements ChangeSetInterface { * - resourceType: string * - callback: function */ - protected $resFilters = array(); + protected $resFilters = []; /** * @var array @@ -90,7 +90,7 @@ class ChangeSet implements ChangeSetInterface { * - regex: string * - callback: function */ - protected $htmlFilters = array(); + protected $htmlFilters = []; /** * @param string $name @@ -115,7 +115,7 @@ class ChangeSet implements ChangeSetInterface { 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; @@ -130,10 +130,10 @@ class ChangeSet implements ChangeSetInterface { * @return ChangeSet */ public function alterResource($resourceType, $callback) { - $this->resFilters[] = array( + $this->resFilters[] = [ 'resourceType' => $resourceType, 'callback' => $callback, - ); + ]; return $this; } @@ -152,10 +152,10 @@ class ChangeSet implements ChangeSetInterface { * @return ChangeSet */ public function alterHtml($file, $callback) { - $this->htmlFilters[] = array( + $this->htmlFilters[] = [ 'regex' => ($file{0} === ';') ? $file : $this->createRegex($file), 'callback' => $callback, - ); + ]; return $this; } diff --git a/Civi/Angular/Coder.php b/Civi/Angular/Coder.php index c780462c93..a1aa080238 100644 --- a/Civi/Angular/Coder.php +++ b/Civi/Angular/Coder.php @@ -56,8 +56,8 @@ class Coder { } 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; } diff --git a/Civi/Angular/Manager.php b/Civi/Angular/Manager.php index 61f36af0ee..2d2e5ed025 100644 --- a/Civi/Angular/Manager.php +++ b/Civi/Angular/Manager.php @@ -47,7 +47,7 @@ class Manager { */ 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([]); } /** @@ -75,7 +75,7 @@ class Manager { // 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"; @@ -101,7 +101,7 @@ class Manager { \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); @@ -143,16 +143,16 @@ class Manager { */ 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'])); @@ -175,7 +175,7 @@ class Manager { */ 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; @@ -193,10 +193,10 @@ class Manager { * 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; } @@ -220,7 +220,7 @@ class Manager { */ 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; @@ -265,14 +265,14 @@ class Manager { */ 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; } @@ -290,7 +290,7 @@ class Manager { */ 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( @@ -322,7 +322,7 @@ class Manager { * @throws \CRM_Core_Exception */ public function getResources($moduleNames, $resType, $refType) { - $result = array(); + $result = []; $moduleNames = (array) $moduleNames; foreach ($moduleNames as $moduleName) { $module = $this->getModule($moduleName); @@ -348,7 +348,7 @@ class Manager { 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; @@ -356,7 +356,7 @@ class Manager { 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; @@ -396,7 +396,7 @@ class Manager { */ public function getChangeSets() { if ($this->changeSets === NULL) { - $this->changeSets = array(); + $this->changeSets = []; \CRM_Utils_Hook::alterAngular($this); } return $this->changeSets; diff --git a/Civi/Angular/Page/Main.php b/Civi/Angular/Page/Main.php index aa31fef711..1c2a447a58 100644 --- a/Civi/Angular/Page/Main.php +++ b/Civi/Angular/Page/Main.php @@ -76,10 +76,10 @@ class Main extends \CRM_Core_Page { 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(); } diff --git a/Civi/Angular/Page/Modules.php b/Civi/Angular/Page/Modules.php index 663a8f6ea1..3b6b5a75ba 100644 --- a/Civi/Angular/Page/Modules.php +++ b/Civi/Angular/Page/Modules.php @@ -102,14 +102,14 @@ class Modules extends \CRM_Core_Page { * @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)); @@ -144,10 +144,10 @@ class Modules extends \CRM_Core_Page { */ 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'); diff --git a/Civi/CCase/Analyzer.php b/Civi/CCase/Analyzer.php index f4d1569bb1..12de74ab9f 100644 --- a/Civi/CCase/Analyzer.php +++ b/Civi/CCase/Analyzer.php @@ -80,20 +80,20 @@ class Analyzer { * @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']; } @@ -115,13 +115,13 @@ class Analyzer { 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']); } } @@ -139,7 +139,7 @@ class Analyzer { * @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; @@ -169,7 +169,7 @@ class Analyzer { */ 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; } @@ -223,7 +223,7 @@ class Analyzer { $this->case = NULL; $this->caseType = NULL; $this->activities = NULL; - $this->indices = array(); + $this->indices = []; } } diff --git a/Civi/CCase/Event/CaseChangeEvent.php b/Civi/CCase/Event/CaseChangeEvent.php index 7f19502db3..e091ac4ba7 100644 --- a/Civi/CCase/Event/CaseChangeEvent.php +++ b/Civi/CCase/Event/CaseChangeEvent.php @@ -49,7 +49,7 @@ class CaseChangeEvent extends GenericHookEvent { * @inheritDoc */ public function getHookValues() { - return array($this->analyzer); + return [$this->analyzer]; } } diff --git a/Civi/CCase/Events.php b/Civi/CCase/Events.php index 6ff05e64ec..278590dfa9 100644 --- a/Civi/CCase/Events.php +++ b/Civi/CCase/Events.php @@ -37,7 +37,7 @@ class Events { * * 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. @@ -73,8 +73,8 @@ class Events { $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}" ); } diff --git a/Civi/CCase/SequenceListener.php b/Civi/CCase/SequenceListener.php index 7135c84b54..3629914bca 100644 --- a/Civi/CCase/SequenceListener.php +++ b/Civi/CCase/SequenceListener.php @@ -54,7 +54,7 @@ class SequenceListener implements CaseChangeListener { $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]; @@ -78,10 +78,10 @@ class SequenceListener implements CaseChangeListener { } // OK, the all activities have completed - civicrm_api3('Case', 'create', array( + civicrm_api3('Case', 'create', [ 'id' => $analyzer->getCaseId(), 'status_id' => 'Closed', - )); + ]); $analyzer->flush(); } @@ -114,12 +114,12 @@ class SequenceListener implements CaseChangeListener { * @param \SimpleXMLElement $actXML the 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']); diff --git a/Civi/CiUtil/Arrays.php b/Civi/CiUtil/Arrays.php index f34954c1d3..48b6c226d4 100644 --- a/Civi/CiUtil/Arrays.php +++ b/Civi/CiUtil/Arrays.php @@ -14,7 +14,7 @@ class Arrays { * @return array */ public static function collect($arr, $col) { - $r = array(); + $r = []; foreach ($arr as $k => $item) { $r[$k] = $item[$col]; } diff --git a/Civi/CiUtil/CSVParser.php b/Civi/CiUtil/CSVParser.php index 05893dfda0..f48521fde7 100644 --- a/Civi/CiUtil/CSVParser.php +++ b/Civi/CiUtil/CSVParser.php @@ -19,7 +19,7 @@ class CSVParser { fwrite($fh, $csvContent); rewind($fh); - $results = array(); + $results = []; while (($r = fgetcsv($fh)) !== FALSE) { $name = str_replace('.', '::', trim($r[0])); $status = trim($r[1]); diff --git a/Civi/CiUtil/Command/AntagonistCommand.php b/Civi/CiUtil/Command/AntagonistCommand.php index 1f9e9335f6..4f7e479116 100644 --- a/Civi/CiUtil/Command/AntagonistCommand.php +++ b/Civi/CiUtil/Command/AntagonistCommand.php @@ -17,7 +17,7 @@ class AntagonistCommand { } 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'), @@ -26,10 +26,10 @@ class AntagonistCommand { // ); $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']); } } @@ -50,26 +50,26 @@ class AntagonistCommand { 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, - ); + ]; } } } diff --git a/Civi/CiUtil/Command/CompareCommand.php b/Civi/CiUtil/Command/CompareCommand.php index ae8bd6d3f0..84b7064239 100644 --- a/Civi/CiUtil/Command/CompareCommand.php +++ b/Civi/CiUtil/Command/CompareCommand.php @@ -17,21 +17,21 @@ class CompareCommand { 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': @@ -43,14 +43,14 @@ class CompareCommand { 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, @@ -66,7 +66,7 @@ class CompareCommand { $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'; } diff --git a/Civi/CiUtil/JenkinsParser.php b/Civi/CiUtil/JenkinsParser.php index 8ca35b0d84..616219ced2 100644 --- a/Civi/CiUtil/JenkinsParser.php +++ b/Civi/CiUtil/JenkinsParser.php @@ -13,7 +13,7 @@ class JenkinsParser { */ 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) { diff --git a/Civi/CiUtil/PHPUnitParser.php b/Civi/CiUtil/PHPUnitParser.php index 06e0ec02aa..e956388adf 100644 --- a/Civi/CiUtil/PHPUnitParser.php +++ b/Civi/CiUtil/PHPUnitParser.php @@ -13,7 +13,7 @@ class PHPUnitParser { */ protected static function parseJsonStream($content) { $content = '[' - . strtr($content, array("}{" => "},{")) + . strtr($content, ["}{" => "},{"]) . ']'; return json_decode($content, TRUE); } @@ -26,7 +26,7 @@ class PHPUnitParser { */ 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']; diff --git a/Civi/CiUtil/PHPUnitScanner.php b/Civi/CiUtil/PHPUnitScanner.php index cd7a1b9a2e..8264e9e266 100644 --- a/Civi/CiUtil/PHPUnitScanner.php +++ b/Civi/CiUtil/PHPUnitScanner.php @@ -32,7 +32,7 @@ class PHPUnitScanner { * @throws \Exception */ public static function findTestClasses($paths) { - $testClasses = array(); + $testClasses = []; $finder = new Finder(); foreach ($paths as $path) { @@ -77,17 +77,17 @@ class PHPUnitScanner { * - 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, - ); + ]; } } } diff --git a/Civi/Codeception/CiviAcceptanceTesterTrait.php b/Civi/Codeception/CiviAcceptanceTesterTrait.php index 47b2c1417e..b5a4dea57a 100644 --- a/Civi/Codeception/CiviAcceptanceTesterTrait.php +++ b/Civi/Codeception/CiviAcceptanceTesterTrait.php @@ -33,7 +33,7 @@ trait CiviAcceptanceTesterTrait { */ 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); } diff --git a/Civi/Core/AssetBuilder.php b/Civi/Core/AssetBuilder.php index 5f79555650..595a53ce40 100644 --- a/Civi/Core/AssetBuilder.php +++ b/Civi/Core/AssetBuilder.php @@ -77,11 +77,11 @@ class AssetBuilder { * Array(string $value => string $label). */ public static function getCacheModes() { - return array( + return [ '0' => ts('Disable'), '1' => ts('Enable'), 'auto' => ts('Auto'), - ); + ]; } protected $cacheEnabled; @@ -121,7 +121,7 @@ class AssetBuilder { * 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"); } @@ -131,11 +131,11 @@ class AssetBuilder { 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); } } @@ -147,7 +147,7 @@ class AssetBuilder { * 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"); } @@ -174,7 +174,7 @@ class AssetBuilder { 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 @@ -203,7 +203,7 @@ class AssetBuilder { * - content: string, ex: 'Hello world'. * @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"); } @@ -212,11 +212,11 @@ class AssetBuilder { 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, - ); + ]; } /** @@ -305,7 +305,7 @@ class AssetBuilder { */ protected function decode($str) { if ($str === NULL || $str === FALSE || $str === '') { - return array(); + return []; } $str = base64_decode($str); @@ -372,11 +372,11 @@ class AssetBuilder { return $assets->render($get['an'], $assets->decode($get['ap'])); } catch (UnknownAssetException $e) { - return array( + return [ 'statusCode' => 404, 'mimeType' => 'text/plain', 'content' => $e->getMessage(), - ); + ]; } } diff --git a/Civi/Core/CiviEventDispatcher.php b/Civi/Core/CiviEventDispatcher.php index a10fa63fd6..2334f1298c 100644 --- a/Civi/Core/CiviEventDispatcher.php +++ b/Civi/Core/CiviEventDispatcher.php @@ -26,7 +26,7 @@ class CiviEventDispatcher extends ContainerAwareEventDispatcher { * @var array * Array(string $eventName => trueish). */ - private $autoListeners = array(); + private $autoListeners = []; /** * Determine whether $eventName should delegate to the CMS hook system. @@ -124,10 +124,10 @@ class CiviEventDispatcher extends ContainerAwareEventDispatcher { // 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); } } } diff --git a/Civi/Core/CiviEventInspector.php b/Civi/Core/CiviEventInspector.php index 4f74cc54a8..ad260c099c 100644 --- a/Civi/Core/CiviEventInspector.php +++ b/Civi/Core/CiviEventInspector.php @@ -33,7 +33,7 @@ class CiviEventInspector { * @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; @@ -56,7 +56,7 @@ class CiviEventInspector { */ public function build($force = FALSE) { if ($force || $this->eventDefs === NULL) { - $this->eventDefs = array(); + $this->eventDefs = []; \CRM_Utils_Hook::eventDefs($this); ksort($this->eventDefs); } @@ -113,7 +113,7 @@ class CiviEventInspector { return FALSE; } - if (!in_array($eventDef['type'], array('hook', 'object'))) { + if (!in_array($eventDef['type'], ['hook', 'object'])) { return FALSE; } @@ -167,10 +167,10 @@ class CiviEventInspector { * @return CiviEventInspector */ public function addEventClass($event, $className) { - $this->add(array( + $this->add([ 'name' => $event, 'class' => $className, - )); + ]); return $this; } @@ -195,20 +195,20 @@ class CiviEventInspector { 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) { diff --git a/Civi/Core/Container.php b/Civi/Core/Container.php index 92290febc7..2763d763d7 100644 --- a/Civi/Core/Container.php +++ b/Civi/Core/Container.php @@ -82,7 +82,7 @@ class Container { $containerBuilder->compile(); $dumper = new PhpDumper($containerBuilder); $containerConfigCache->write( - $dumper->dump(array('class' => 'CachedCiviContainer')), + $dumper->dump(['class' => 'CachedCiviContainer']), $containerBuilder->getResources() ); } @@ -110,7 +110,7 @@ class Container { $container->setDefinition(self::SELF, new Definition( 'Civi\Core\Container', - array() + [] )); // TODO Move configuration to an external file; define caching structure @@ -131,62 +131,62 @@ class Container { $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')) @@ -200,30 +200,30 @@ class Container { } // 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', @@ -236,64 +236,64 @@ class Container { )); $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); @@ -314,38 +314,38 @@ class 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; @@ -359,10 +359,10 @@ class Container { // 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. @@ -383,12 +383,12 @@ class Container { $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); @@ -398,7 +398,7 @@ class Container { $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 @@ -412,13 +412,13 @@ class Container { 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; } @@ -473,7 +473,7 @@ class Container { */ 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(); @@ -488,10 +488,10 @@ class Container { $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']); diff --git a/Civi/Core/DatabaseInitializer.php b/Civi/Core/DatabaseInitializer.php index e3b3e4278b..e13c8b7f89 100644 --- a/Civi/Core/DatabaseInitializer.php +++ b/Civi/Core/DatabaseInitializer.php @@ -42,11 +42,11 @@ class DatabaseInitializer { * @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); } diff --git a/Civi/Core/Event/GenericHookEvent.php b/Civi/Core/Event/GenericHookEvent.php index a39f2f9d0f..c98053d20e 100644 --- a/Civi/Core/Event/GenericHookEvent.php +++ b/Civi/Core/Event/GenericHookEvent.php @@ -108,7 +108,7 @@ class GenericHookEvent extends \Symfony\Component\EventDispatcher\Event { * @var mixed * @deprecated */ - private $returnValues = array(); + private $returnValues = []; /** * List of field names that are prohibited due to conflicts @@ -116,7 +116,7 @@ class GenericHookEvent extends \Symfony\Component\EventDispatcher\Event { * * @var array */ - private static $BLACKLIST = array( + private static $BLACKLIST = [ 'name', 'dispatcher', 'propagationStopped', @@ -124,7 +124,7 @@ class GenericHookEvent extends \Symfony\Component\EventDispatcher\Event { 'hookValues', 'hookFields', 'hookFieldsFlip', - ); + ]; /** * Create a GenericHookEvent using key-value pairs. diff --git a/Civi/Core/Event/PostEvent.php b/Civi/Core/Event/PostEvent.php index 50d41f66ce..fe69d3f98e 100644 --- a/Civi/Core/Event/PostEvent.php +++ b/Civi/Core/Event/PostEvent.php @@ -81,7 +81,7 @@ class PostEvent extends GenericHookEvent { * @inheritDoc */ public function getHookValues() { - return array($this->action, $this->entity, $this->id, &$this->object); + return [$this->action, $this->entity, $this->id, &$this->object]; } } diff --git a/Civi/Core/Event/PreEvent.php b/Civi/Core/Event/PreEvent.php index fdbb4ca6c1..6332658a7b 100644 --- a/Civi/Core/Event/PreEvent.php +++ b/Civi/Core/Event/PreEvent.php @@ -81,7 +81,7 @@ class PreEvent extends GenericHookEvent { * @inheritDoc */ public function getHookValues() { - return array($this->action, $this->entity, $this->id, &$this->params); + return [$this->action, $this->entity, $this->id, &$this->params]; } } diff --git a/Civi/Core/Event/UnhandledExceptionEvent.php b/Civi/Core/Event/UnhandledExceptionEvent.php index ef378ab2c3..dbb56c48eb 100644 --- a/Civi/Core/Event/UnhandledExceptionEvent.php +++ b/Civi/Core/Event/UnhandledExceptionEvent.php @@ -56,7 +56,7 @@ class UnhandledExceptionEvent extends GenericHookEvent { * @inheritDoc */ public function getHookValues() { - return array($this->exception, $this->request); + return [$this->exception, $this->request]; } } diff --git a/Civi/Core/LocalizationInitializer.php b/Civi/Core/LocalizationInitializer.php index 227864927d..6fb2dabbd2 100644 --- a/Civi/Core/LocalizationInitializer.php +++ b/Civi/Core/LocalizationInitializer.php @@ -56,7 +56,7 @@ class LocalizationInitializer { $fileName = $localeDir . $seedLanguage . DIRECTORY_SEPARATOR . 'settings.default.json'; // initalization - $settingsParams = array(); + $settingsParams = []; if (file_exists($fileName)) { @@ -66,7 +66,7 @@ class LocalizationInitializer { 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) { @@ -86,7 +86,7 @@ class LocalizationInitializer { // 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']); } } diff --git a/Civi/Core/Lock/LockManager.php b/Civi/Core/Lock/LockManager.php index 74f531eecf..56b667664c 100644 --- a/Civi/Core/Lock/LockManager.php +++ b/Civi/Core/Lock/LockManager.php @@ -37,7 +37,7 @@ use Civi\Core\Resolver; */ class LockManager { - private $rules = array(); + private $rules = []; /** * @param string $name @@ -53,7 +53,7 @@ class LockManager { $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 { @@ -111,10 +111,10 @@ class LockManager { * @see Resolver */ public function register($pattern, $factory) { - $this->rules[] = array( + $this->rules[] = [ 'pattern' => $pattern, 'factory' => $factory, - ); + ]; return $this; } diff --git a/Civi/Core/Paths.php b/Civi/Core/Paths.php index 8cab188a59..31c9266013 100644 --- a/Civi/Core/Paths.php +++ b/Civi/Core/Paths.php @@ -22,9 +22,9 @@ class Paths { * @var array * Array(string $name => array(url => $, path => $)). */ - private $variables = array(); + private $variables = []; - private $variableFactory = array(); + private $variableFactory = []; /** * Class constructor. @@ -36,56 +36,56 @@ class Paths { 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), - ); + ]; }); } diff --git a/Civi/Core/Resolver.php b/Civi/Core/Resolver.php index 0d71d185e7..3583a6303b 100644 --- a/Civi/Core/Resolver.php +++ b/Civi/Core/Resolver.php @@ -77,7 +77,7 @@ class Resolver { 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. @@ -91,7 +91,7 @@ class Resolver { 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); } @@ -184,7 +184,7 @@ class ResolverApi { * Fire an API call. */ public function __invoke() { - $apiParams = array(); + $apiParams = []; if (isset($this->url['query'])) { parse_str($this->url['query'], $apiParams); } @@ -212,7 +212,7 @@ class ResolverApi { * (e.g. "@1" => "firstValue"). */ protected function createPlaceholders($prefix, $args) { - $result = array(); + $result = []; foreach ($args as $offset => $arg) { $result[$prefix . (1 + $offset)] = $arg; } diff --git a/Civi/Core/SettingsBag.php b/Civi/Core/SettingsBag.php index 80d7dd9bab..613703305a 100644 --- a/Civi/Core/SettingsBag.php +++ b/Civi/Core/SettingsBag.php @@ -89,7 +89,7 @@ class SettingsBag { public function __construct($domainId, $contactId) { $this->domainId = $domainId; $this->contactId = $contactId; - $this->values = array(); + $this->values = []; $this->combined = NULL; } @@ -128,7 +128,7 @@ class SettingsBag { // 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. @@ -141,7 +141,7 @@ class SettingsBag { 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); } @@ -180,7 +180,7 @@ class SettingsBag { 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; @@ -281,16 +281,16 @@ class SettingsBag { 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; @@ -306,7 +306,7 @@ class SettingsBag { * @return array */ protected function combine($arrays) { - $combined = array(); + $combined = []; foreach ($arrays as $array) { foreach ($array as $k => $v) { if ($v !== NULL) { @@ -326,8 +326,8 @@ class SettingsBag { * 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]); diff --git a/Civi/Core/SettingsManager.php b/Civi/Core/SettingsManager.php index d3cb26f01f..6ceab0519a 100644 --- a/Civi/Core/SettingsManager.php +++ b/Civi/Core/SettingsManager.php @@ -70,7 +70,7 @@ class SettingsManager { * @var * Array (int $id => SettingsBag $bag). */ - protected $bagsByDomain = array(), $bagsByContact = array(); + protected $bagsByDomain = [], $bagsByContact = []; /** * @var array|NULL @@ -219,10 +219,10 @@ class SettingsManager { $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); } @@ -266,12 +266,12 @@ class SettingsManager { * @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', @@ -290,7 +290,7 @@ class SettingsManager { //\CRM_Core_BAO_Setting::URL_PREFERENCES_NAME => 'domain', 'domain' => 'domain', 'contact' => 'contact', - ); + ]; if (is_array($civicrm_setting)) { foreach ($civicrm_setting as $oldGroup => $values) { @@ -341,12 +341,12 @@ class SettingsManager { * @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/', @@ -355,7 +355,7 @@ class SettingsManager { 'extensionsURL' => '[civicrm.files]/ext/', 'resourceBase' => '[civicrm.root]/', 'userFrameworkResourceURL' => '[civicrm.root]/', - ); + ]; break; } diff --git a/Civi/Core/SettingsMetadata.php b/Civi/Core/SettingsMetadata.php index 2ba5c4d54d..00d04d3421 100644 --- a/Civi/Core/SettingsMetadata.php +++ b/Civi/Core/SettingsMetadata.php @@ -65,7 +65,7 @@ class SettingsMetadata { * - 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(); } @@ -81,7 +81,7 @@ class SettingsMetadata { $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); @@ -106,8 +106,8 @@ class 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])) { @@ -126,7 +126,7 @@ class SettingsMetadata { * @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; @@ -148,8 +148,8 @@ class SettingsMetadata { 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 { diff --git a/Civi/Core/SettingsStack.php b/Civi/Core/SettingsStack.php index 5d503b379a..9183857d5c 100644 --- a/Civi/Core/SettingsStack.php +++ b/Civi/Core/SettingsStack.php @@ -19,7 +19,7 @@ class SettingsStack { * @var array * Ex: $stack[0] == ['settingName', 'oldSettingValue']; */ - protected $stack = array(); + protected $stack = []; /** * Temporarily apply a setting. @@ -29,10 +29,10 @@ class SettingsStack { */ 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(); diff --git a/Civi/Core/SqlTrigger/TimestampTriggers.php b/Civi/Core/SqlTrigger/TimestampTriggers.php index 69ff095093..235ce70b60 100644 --- a/Civi/Core/SqlTrigger/TimestampTriggers.php +++ b/Civi/Core/SqlTrigger/TimestampTriggers.php @@ -110,7 +110,7 @@ class TimestampTriggers { $customDataEntity, $createdDate = 'created_date', $modifiedDate = 'modified_date', - $relations = array() + $relations = [] ) { $this->tableName = $tableName; $this->customDataEntity = $customDataEntity; @@ -153,17 +153,17 @@ class TimestampTriggers { } 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) { @@ -203,24 +203,24 @@ class TimestampTriggers { // 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", - ); + ]; } } @@ -321,10 +321,10 @@ class TimestampTriggers { $customGroupDAO->is_multiple = 0; $customGroupDAO->find(); while ($customGroupDAO->fetch()) { - $relations[] = array( + $relations[] = [ 'table' => $customGroupDAO->table_name, 'column' => 'entity_id', - ); + ]; } } diff --git a/Civi/Core/SqlTriggers.php b/Civi/Core/SqlTriggers.php index 8d5a4a3330..172e7d0e79 100644 --- a/Civi/Core/SqlTriggers.php +++ b/Civi/Core/SqlTriggers.php @@ -53,7 +53,7 @@ class SqlTriggers { * @see CRM-9716 */ public function rebuild($tableName = NULL, $force = FALSE) { - $info = array(); + $info = []; $logging = new \CRM_Logging_Schema(); $logging->triggerInfo($info, $tableName, $force); @@ -82,7 +82,7 @@ class SqlTriggers { return; } - $triggers = array(); + $triggers = []; // now enumerate the tables and the events and collect the same set in a different format foreach ($info as $value) { @@ -98,14 +98,14 @@ class SqlTriggers { } 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']); @@ -115,12 +115,12 @@ class SqlTriggers { 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, @@ -132,17 +132,17 @@ class SqlTriggers { ); 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) { @@ -181,7 +181,7 @@ class SqlTriggers { * 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); @@ -201,17 +201,17 @@ class SqlTriggers { * @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] ); } diff --git a/Civi/Core/Transaction/Frame.php b/Civi/Core/Transaction/Frame.php index 5fe8b86092..74ee8e83bb 100644 --- a/Civi/Core/Transaction/Frame.php +++ b/Civi/Core/Transaction/Frame.php @@ -83,12 +83,12 @@ class Frame { $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() { @@ -186,16 +186,16 @@ class Frame { */ 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]), + ]; } } diff --git a/Civi/Core/Transaction/Manager.php b/Civi/Core/Transaction/Manager.php index bf9ddd584d..70f63ab062 100644 --- a/Civi/Core/Transaction/Manager.php +++ b/Civi/Core/Transaction/Manager.php @@ -44,7 +44,7 @@ class Manager { /** * @var array stack of SQL transactions/savepoints */ - private $frames = array(); + private $frames = []; /** * @var int @@ -131,7 +131,7 @@ class Manager { // internal state of each frame is consistent with its outcome $oldFrames = $this->frames; - $this->frames = array(); + $this->frames = []; foreach ($oldFrames as $oldFrame) { $oldFrame->forceRollback(); } diff --git a/Civi/Install/Requirements.php b/Civi/Install/Requirements.php index 4d2d3f72d4..e4423e8f51 100644 --- a/Civi/Install/Requirements.php +++ b/Civi/Install/Requirements.php @@ -23,15 +23,15 @@ class Requirements { */ 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', @@ -41,7 +41,7 @@ class Requirements { 'checkMysqlThreadStack', 'checkMysqlLockTables', 'checkMysqlUtf8mb4', - ); + ]; /** * Run all requirements tests. @@ -70,7 +70,7 @@ class Requirements { * @return array */ public function checkSystem(array $file_paths) { - $errors = array(); + $errors = []; $errors[] = $this->checkFilepathIsWritable($file_paths); foreach ($this->system_checks as $check) { @@ -94,7 +94,7 @@ class Requirements { * @return array */ public function checkDatabase(array $db_config) { - $errors = array(); + $errors = []; foreach ($this->database_checks as $check) { $errors[] = $this->$check($db_config); @@ -132,11 +132,11 @@ class Requirements { $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; @@ -178,14 +178,14 @@ class Requirements { * @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])) { @@ -205,11 +205,11 @@ class Requirements { * @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'; @@ -223,11 +223,11 @@ class Requirements { * @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'; @@ -240,11 +240,11 @@ class Requirements { * @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'; @@ -259,11 +259,11 @@ class Requirements { * @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); @@ -289,10 +289,10 @@ class Requirements { */ 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))) { @@ -317,11 +317,11 @@ class Requirements { * @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) { @@ -352,11 +352,11 @@ class Requirements { * @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) { @@ -388,11 +388,11 @@ class Requirements { * @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) { @@ -433,11 +433,11 @@ class Requirements { * @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) { @@ -469,11 +469,11 @@ class Requirements { 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) { @@ -510,11 +510,11 @@ class Requirements { * @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) { @@ -562,13 +562,13 @@ class Requirements { * @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; @@ -589,11 +589,11 @@ class Requirements { * @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) { diff --git a/Civi/Payment/System.php b/Civi/Payment/System.php index 4150e8b083..ed207143ad 100644 --- a/Civi/Payment/System.php +++ b/Civi/Payment/System.php @@ -16,7 +16,7 @@ class System { /** * @var array cache */ - private $cache = array(); + private $cache = []; /** * @return \Civi\Payment\System @@ -111,7 +111,7 @@ class 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); } @@ -123,7 +123,7 @@ class System { * @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); } @@ -133,7 +133,7 @@ class System { * 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); @@ -151,11 +151,11 @@ class System { * @throws \CiviCRM_API3_Exception */ public function getByClass($className) { - return $this->getByProcessor(array( + return $this->getByProcessor([ 'class_name' => $className, 'id' => 0, 'is_test' => 0, - ), + ], TRUE); } diff --git a/Civi/Test.php b/Civi/Test.php index e70f0f4026..8e44fcd509 100644 --- a/Civi/Test.php +++ b/Civi/Test.php @@ -14,7 +14,7 @@ class Test { /** * @var array */ - private static $singletons = array(); + private static $singletons = []; /** * Get the data source used for testing. @@ -55,7 +55,7 @@ class Test { 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) { diff --git a/Civi/Test/Api3DocTrait.php b/Civi/Test/Api3DocTrait.php index 17b0ece5d9..a4c3ceb565 100644 --- a/Civi/Test/Api3DocTrait.php +++ b/Civi/Test/Api3DocTrait.php @@ -78,13 +78,13 @@ trait Api3DocTrait { // 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)]); @@ -97,7 +97,7 @@ trait Api3DocTrait { 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); @@ -139,7 +139,7 @@ trait Api3DocTrait { 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', @@ -154,9 +154,9 @@ trait Api3DocTrait { '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]); diff --git a/Civi/Test/Api3TestTrait.php b/Civi/Test/Api3TestTrait.php index 96e41b9d7a..4b85837021 100644 --- a/Civi/Test/Api3TestTrait.php +++ b/Civi/Test/Api3TestTrait.php @@ -28,8 +28,8 @@ trait Api3TestTrait { * @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]); @@ -48,7 +48,7 @@ trait Api3TestTrait { * @param $id */ public function assertAPIDeleted($entity, $id) { - $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0); + $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0); } /** @@ -107,9 +107,9 @@ trait Api3TestTrait { */ 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); @@ -132,10 +132,10 @@ trait Api3TestTrait { * @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)) { @@ -164,10 +164,10 @@ trait Api3TestTrait { * @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)); @@ -197,9 +197,9 @@ trait Api3TestTrait { * @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); @@ -235,10 +235,10 @@ trait Api3TestTrait { * @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)); diff --git a/Civi/Test/CiviEnvBuilder.php b/Civi/Test/CiviEnvBuilder.php index 003e14545d..91fc4b7678 100644 --- a/Civi/Test/CiviEnvBuilder.php +++ b/Civi/Test/CiviEnvBuilder.php @@ -19,7 +19,7 @@ use RuntimeException; class CiviEnvBuilder { protected $name; - private $steps = array(); + private $steps = []; /** * @var string|NULL diff --git a/Civi/Test/CiviEnvBuilder/ExtensionsStep.php b/Civi/Test/CiviEnvBuilder/ExtensionsStep.php index 9b9440a235..3dcedfd770 100644 --- a/Civi/Test/CiviEnvBuilder/ExtensionsStep.php +++ b/Civi/Test/CiviEnvBuilder/ExtensionsStep.php @@ -20,7 +20,7 @@ class ExtensionsStep implements StepInterface { } 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) { diff --git a/Civi/Test/CiviEnvBuilder/SqlFileStep.php b/Civi/Test/CiviEnvBuilder/SqlFileStep.php index c901931721..b753761e23 100644 --- a/Civi/Test/CiviEnvBuilder/SqlFileStep.php +++ b/Civi/Test/CiviEnvBuilder/SqlFileStep.php @@ -14,11 +14,11 @@ class SqlFileStep implements StepInterface { public function getSig() { - return implode(' ', array( + return implode(' ', [ $this->file, filemtime($this->file), filectime($this->file), - )); + ]); } public function isValid() { diff --git a/Civi/Test/CiviTestListener.php b/Civi/Test/CiviTestListener.php index 2f50529ee6..8eca8cbf75 100644 --- a/Civi/Test/CiviTestListener.php +++ b/Civi/Test/CiviTestListener.php @@ -25,7 +25,7 @@ class CiviTestListener extends \PHPUnit_Framework_BaseTestListener { * 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 @@ -39,7 +39,7 @@ class CiviTestListener extends \PHPUnit_Framework_BaseTestListener { } public function endTestSuite(\PHPUnit_Framework_TestSuite $suite) { - $this->cache = array(); + $this->cache = []; } public function startTest(\PHPUnit_Framework_Test $test) { @@ -113,7 +113,7 @@ class CiviTestListener extends \PHPUnit_Framework_BaseTestListener { 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; @@ -147,7 +147,7 @@ class CiviTestListener extends \PHPUnit_Framework_BaseTestListener { /** @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]); } } @@ -208,7 +208,7 @@ class CiviTestListener extends \PHPUnit_Framework_BaseTestListener { */ 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__); @@ -243,7 +243,7 @@ class CiviTestListener extends \PHPUnit_Framework_BaseTestListener { * @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) { diff --git a/Civi/Test/Data.php b/Civi/Test/Data.php index a0c26df636..8b90b5d493 100644 --- a/Civi/Test/Data.php +++ b/Civi/Test/Data.php @@ -38,16 +38,16 @@ class Data { \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; } diff --git a/Civi/Test/Schema.php b/Civi/Test/Schema.php index 7c3bb4655d..b5a9aa525c 100644 --- a/Civi/Test/Schema.php +++ b/Civi/Test/Schema.php @@ -25,7 +25,7 @@ class Schema { $pdo->quote($type) ); $tables = $pdo->query($query); - $result = array(); + $result = []; foreach ($tables as $table) { $result[] = $table['table_name']; } @@ -35,20 +35,20 @@ class Schema { 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) { @@ -59,7 +59,7 @@ class Schema { } public function dropAll() { - $queries = array(); + $queries = []; foreach ($this->getTables('VIEW') as $table) { if (preg_match('/^(civicrm_|log_)/', $table)) { $queries[] = "DROP VIEW $table"; @@ -89,8 +89,8 @@ class Schema { 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_') { diff --git a/Civi/Token/AbstractTokenSubscriber.php b/Civi/Token/AbstractTokenSubscriber.php index 69a570f8f3..38d2875ce3 100644 --- a/Civi/Token/AbstractTokenSubscriber.php +++ b/Civi/Token/AbstractTokenSubscriber.php @@ -56,11 +56,11 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; 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', - ); + ]; } /** @@ -88,7 +88,7 @@ abstract class AbstractTokenSubscriber implements EventSubscriberInterface { * @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; } @@ -118,11 +118,11 @@ abstract class AbstractTokenSubscriber implements EventSubscriberInterface { return; } foreach ($this->tokenNames as $name => $label) { - $e->register(array( + $e->register([ 'entity' => $this->entity, 'field' => $name, 'label' => $label, - )); + ]); } } diff --git a/Civi/Token/Event/TokenRegisterEvent.php b/Civi/Token/Event/TokenRegisterEvent.php index ff9122543c..c7fdfa01fe 100644 --- a/Civi/Token/Event/TokenRegisterEvent.php +++ b/Civi/Token/Event/TokenRegisterEvent.php @@ -57,10 +57,10 @@ class TokenRegisterEvent extends TokenEvent { $params = $paramsOrField; } else { - $params = array( + $params = [ 'field' => $paramsOrField, 'label' => $label, - ); + ]; } $params = array_merge($this->defaults, $params); $this->tokenProcessor->addToken($params); diff --git a/Civi/Token/TokenCompatSubscriber.php b/Civi/Token/TokenCompatSubscriber.php index b4b41cfdab..2e8721e676 100644 --- a/Civi/Token/TokenCompatSubscriber.php +++ b/Civi/Token/TokenCompatSubscriber.php @@ -24,10 +24,10 @@ class TokenCompatSubscriber implements EventSubscriberInterface { * @inheritDoc */ public static function getSubscribedEvents() { - return array( + return [ Events::TOKEN_EVALUATE => 'onEvaluate', Events::TOKEN_RENDER => 'onRender', - ); + ]; } /** @@ -41,7 +41,7 @@ class TokenCompatSubscriber implements EventSubscriberInterface { // 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; @@ -55,9 +55,9 @@ class TokenCompatSubscriber implements EventSubscriberInterface { /** @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')) { @@ -69,10 +69,10 @@ class TokenCompatSubscriber implements EventSubscriberInterface { 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, - )); + ]); } } } @@ -87,7 +87,7 @@ class TokenCompatSubscriber implements EventSubscriberInterface { $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. diff --git a/Civi/Token/TokenProcessor.php b/Civi/Token/TokenProcessor.php index 5941d0809d..c989773435 100644 --- a/Civi/Token/TokenProcessor.php +++ b/Civi/Token/TokenProcessor.php @@ -105,11 +105,11 @@ class TokenProcessor { * @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; } @@ -120,11 +120,11 @@ class TokenProcessor { */ 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); } @@ -160,7 +160,7 @@ class TokenProcessor { * @return array */ public function getMessageTokens() { - $tokens = array(); + $tokens = []; foreach ($this->messages as $message) { $tokens = \CRM_Utils_Array::crmArrayMerge($tokens, $message['tokens']); } @@ -227,8 +227,8 @@ class TokenProcessor { */ 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; @@ -242,7 +242,7 @@ class TokenProcessor { */ public function listTokens() { if ($this->listTokens === NULL) { - $this->listTokens = array(); + $this->listTokens = []; foreach ($this->getTokens() as $token => $values) { $this->listTokens['{' . $token . '}'] = $values['label']; } @@ -280,9 +280,9 @@ class TokenProcessor { // 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); } diff --git a/Civi/Token/TokenRow.php b/Civi/Token/TokenRow.php index 883e29089a..a57a37b5d0 100644 --- a/Civi/Token/TokenRow.php +++ b/Civi/Token/TokenRow.php @@ -205,10 +205,10 @@ class TokenRow { } 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']; @@ -218,7 +218,7 @@ class TokenRow { 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

,