From a1e4f8fecd393df89e70ee9e8898f0e67729a4e5 Mon Sep 17 00:00:00 2001 From: Massimiliano Braglia Date: Fri, 8 Feb 2019 17:28:23 +0100 Subject: [PATCH 1/2] Introduced php-cs-fixer native_function_invocation rule and applied linting --- .php_cs.dist | 1 + lib/Elastica/AbstractUpdateAction.php | 8 +-- .../Aggregation/AbstractAggregation.php | 4 +- .../Aggregation/AbstractSimpleAggregation.php | 4 +- lib/Elastica/Aggregation/DateHistogram.php | 2 +- lib/Elastica/Aggregation/Filters.php | 8 +-- lib/Elastica/Aggregation/TopHits.php | 2 +- lib/Elastica/Bulk.php | 14 ++-- lib/Elastica/Bulk/Action.php | 6 +- lib/Elastica/Bulk/ResponseSet.php | 2 +- lib/Elastica/Client.php | 18 ++--- lib/Elastica/Cluster.php | 2 +- lib/Elastica/Cluster/Settings.php | 4 +- lib/Elastica/Connection.php | 4 +- .../Connection/Strategy/StrategyFactory.php | 6 +- lib/Elastica/Document.php | 10 +-- .../Exception/ElasticsearchException.php | 8 +-- lib/Elastica/Index.php | 16 ++--- lib/Elastica/Index/Settings.php | 6 +- lib/Elastica/Index/Stats.php | 2 +- lib/Elastica/IndexTemplate.php | 2 +- lib/Elastica/JSON.php | 12 ++-- lib/Elastica/Log.php | 6 +- lib/Elastica/Multi/MultiBuilder.php | 10 +-- lib/Elastica/Multi/ResultSet.php | 2 +- lib/Elastica/Multi/Search.php | 4 +- lib/Elastica/Node/Info.php | 16 ++--- lib/Elastica/Node/Stats.php | 4 +- lib/Elastica/Param.php | 6 +- lib/Elastica/Pipeline.php | 2 +- lib/Elastica/Query.php | 14 ++-- lib/Elastica/Query/AbstractGeoDistance.php | 4 +- lib/Elastica/Query/BoolQuery.php | 2 +- lib/Elastica/Query/DisMax.php | 2 +- lib/Elastica/Query/Fuzzy.php | 8 +-- lib/Elastica/Query/GeoPolygon.php | 2 +- lib/Elastica/Query/GeohashCell.php | 2 +- lib/Elastica/Query/Ids.php | 2 +- lib/Elastica/Query/MoreLikeThis.php | 4 +- lib/Elastica/Query/QueryString.php | 2 +- lib/Elastica/Query/SimpleQueryString.php | 2 +- lib/Elastica/Query/SpanFirst.php | 2 +- lib/Elastica/Query/SpanMulti.php | 2 +- lib/Elastica/Query/Terms.php | 2 +- lib/Elastica/QueryBuilder/Facade.php | 4 +- lib/Elastica/QueryBuilder/Version.php | 6 +- lib/Elastica/Reindex.php | 14 ++-- lib/Elastica/Rescore/Query.php | 2 +- lib/Elastica/Response.php | 8 +-- lib/Elastica/Result.php | 6 +- lib/Elastica/ResultSet.php | 4 +- lib/Elastica/Script/AbstractScript.php | 8 +-- lib/Elastica/Script/ScriptFields.php | 6 +- lib/Elastica/Scroll.php | 2 +- lib/Elastica/Search.php | 20 +++--- lib/Elastica/Status.php | 10 +-- lib/Elastica/Suggest.php | 2 +- lib/Elastica/Suggest/Phrase.php | 4 +- lib/Elastica/Task.php | 4 +- lib/Elastica/Transport/AbstractTransport.php | 16 ++--- lib/Elastica/Transport/AwsAuthV4.php | 2 +- lib/Elastica/Transport/Guzzle.php | 22 +++--- lib/Elastica/Transport/Http.php | 68 +++++++++---------- lib/Elastica/Transport/HttpAdapter.php | 8 +-- lib/Elastica/Type.php | 8 +-- lib/Elastica/Type/Mapping.php | 2 +- lib/Elastica/Util.php | 50 +++++++------- test/Elastica/Aggregation/ChildrenTest.php | 4 +- test/Elastica/Aggregation/DateRangeTest.php | 4 +- test/Elastica/Aggregation/IpRangeTest.php | 2 +- .../Aggregation/SignificantTermsTest.php | 2 +- test/Elastica/Base.php | 54 +++++++-------- test/Elastica/BasePipeline.php | 4 +- test/Elastica/BulkTest.php | 14 ++-- test/Elastica/ClientTest.php | 4 +- test/Elastica/Cluster/SettingsTest.php | 4 +- test/Elastica/ClusterTest.php | 4 +- .../Connection/Strategy/RoundRobinTest.php | 4 +- .../Connection/Strategy/SimpleTest.php | 4 +- .../Strategy/StrategyFactoryTest.php | 4 +- test/Elastica/DocumentTest.php | 2 +- test/Elastica/ErrorsCollector.php | 6 +- .../Exception/AbstractExceptionTest.php | 4 +- .../Connection/GuzzleExceptionTest.php | 2 +- .../PartialShardFailureExceptionTest.php | 2 +- test/Elastica/LogTest.php | 14 ++-- test/Elastica/Node/InfoTest.php | 2 +- test/Elastica/NodeTest.php | 6 +- test/Elastica/Processor/JsonTest.php | 2 +- test/Elastica/Query/BoolQueryTest.php | 2 +- test/Elastica/Query/InnerHitsTest.php | 10 +-- test/Elastica/Query/QueryStringTest.php | 6 +- test/Elastica/Query/SpanTermTest.php | 2 +- .../QueryBuilder/DSL/AbstractDSLTest.php | 12 ++-- test/Elastica/QueryBuilder/VersionTest.php | 12 ++-- test/Elastica/ReindexTest.php | 2 +- test/Elastica/ResponseTest.php | 18 ++--- test/Elastica/ResultTest.php | 2 +- test/Elastica/SearchTest.php | 2 +- test/Elastica/SnapshotTest.php | 2 +- test/Elastica/StatusTest.php | 4 +- test/Elastica/TaskTest.php | 4 +- test/Elastica/Transport/AwsAuthV4Test.php | 14 ++-- test/Elastica/Transport/GuzzleTest.php | 16 ++--- test/Elastica/Transport/HttpTest.php | 12 ++-- .../Transport/TransportBenchmarkTest.php | 20 +++--- test/Elastica/TypeTest.php | 4 +- test/Elastica/UtilTest.php | 4 +- test/bootstrap.php | 4 +- 109 files changed, 409 insertions(+), 408 deletions(-) diff --git a/.php_cs.dist b/.php_cs.dist index 19ff470165..08eb2b6ee4 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -18,6 +18,7 @@ $config = PhpCsFixer\Config::create() 'no_useless_else' => true, '@PHPUnit60Migration:risky' => true, 'php_unit_dedicate_assert' => ['target' => 'newest'], + 'native_function_invocation' => true, ]) ; diff --git a/lib/Elastica/AbstractUpdateAction.php b/lib/Elastica/AbstractUpdateAction.php index 1e14ea785f..99a902f109 100644 --- a/lib/Elastica/AbstractUpdateAction.php +++ b/lib/Elastica/AbstractUpdateAction.php @@ -264,8 +264,8 @@ public function hasRouting() */ public function setFields($fields) { - if (is_array($fields)) { - $fields = implode(',', $fields); + if (\is_array($fields)) { + $fields = \implode(',', $fields); } return $this->setParam('_fields', (string) $fields); @@ -465,7 +465,7 @@ public function getOptions(array $fields = [], $withUnderscore = false) if (!empty($fields)) { $data = []; foreach ($fields as $field) { - $key = '_'.ltrim($field, '_'); + $key = '_'.\ltrim($field, '_'); if ($this->hasParam($key) && '' !== (string) $this->getParam($key)) { $data[$key] = $this->getParam($key); } @@ -475,7 +475,7 @@ public function getOptions(array $fields = [], $withUnderscore = false) } if (!$withUnderscore) { foreach ($data as $key => $value) { - $data[ltrim($key, '_')] = $value; + $data[\ltrim($key, '_')] = $value; unset($data[$key]); } } diff --git a/lib/Elastica/Aggregation/AbstractAggregation.php b/lib/Elastica/Aggregation/AbstractAggregation.php index 539ba7a181..0121371deb 100644 --- a/lib/Elastica/Aggregation/AbstractAggregation.php +++ b/lib/Elastica/Aggregation/AbstractAggregation.php @@ -87,11 +87,11 @@ public function toArray(): array { $array = parent::toArray(); - if (array_key_exists('global_aggregation', $array)) { + if (\array_key_exists('global_aggregation', $array)) { // compensate for class name GlobalAggregation $array = ['global' => new \stdClass()]; } - if (sizeof($this->_aggs)) { + if (\sizeof($this->_aggs)) { $array['aggs'] = $this->_convertArrayable($this->_aggs); } diff --git a/lib/Elastica/Aggregation/AbstractSimpleAggregation.php b/lib/Elastica/Aggregation/AbstractSimpleAggregation.php index c68a003632..efea527b3c 100644 --- a/lib/Elastica/Aggregation/AbstractSimpleAggregation.php +++ b/lib/Elastica/Aggregation/AbstractSimpleAggregation.php @@ -44,12 +44,12 @@ public function toArray(): array $baseName = $this->_getBaseName(); - if (isset($array[$baseName]['script']) && is_array($array[$baseName]['script'])) { + if (isset($array[$baseName]['script']) && \is_array($array[$baseName]['script'])) { $script = $array[$baseName]['script']; unset($array[$baseName]['script']); - $array[$baseName] = array_merge($array[$baseName], $script); + $array[$baseName] = \array_merge($array[$baseName], $script); } return $array; diff --git a/lib/Elastica/Aggregation/DateHistogram.php b/lib/Elastica/Aggregation/DateHistogram.php index 86386e0a07..3c10add400 100644 --- a/lib/Elastica/Aggregation/DateHistogram.php +++ b/lib/Elastica/Aggregation/DateHistogram.php @@ -77,7 +77,7 @@ public function setExtendedBounds(string $min = '', string $max = ''): self $bounds['min'] = $min; $bounds['max'] = $max; // switch if min is higher then max - if (strtotime($min) > strtotime($max)) { + if (\strtotime($min) > \strtotime($max)) { $bounds['min'] = $max; $bounds['max'] = $min; } diff --git a/lib/Elastica/Aggregation/Filters.php b/lib/Elastica/Aggregation/Filters.php index 94c588cb04..1c273329ae 100644 --- a/lib/Elastica/Aggregation/Filters.php +++ b/lib/Elastica/Aggregation/Filters.php @@ -44,7 +44,7 @@ public function addFilter(AbstractQuery $filter, string $name = null): self } if ($this->hasParam('filters') - && count($this->getParam('filters')) + && \count($this->getParam('filters')) && $this->_type !== $type ) { throw new InvalidException('Mix named and anonymous keys are not allowed'); @@ -85,10 +85,10 @@ public function toArray(): array foreach ($filters as $filter) { if (self::NAMED_TYPE === $this->_type) { - $key = key($filter); - $array['filters']['filters'][$key] = current($filter)->toArray(); + $key = \key($filter); + $array['filters']['filters'][$key] = \current($filter)->toArray(); } else { - $array['filters']['filters'][] = current($filter)->toArray(); + $array['filters']['filters'][] = \current($filter)->toArray(); } } diff --git a/lib/Elastica/Aggregation/TopHits.php b/lib/Elastica/Aggregation/TopHits.php index ffb55f03a1..5b8fdaa7f3 100644 --- a/lib/Elastica/Aggregation/TopHits.php +++ b/lib/Elastica/Aggregation/TopHits.php @@ -109,7 +109,7 @@ public function setExplain(bool $explain): self */ public function setScriptFields($scriptFields): self { - if (is_array($scriptFields)) { + if (\is_array($scriptFields)) { $scriptFields = new ScriptFields($scriptFields); } diff --git a/lib/Elastica/Bulk.php b/lib/Elastica/Bulk.php index 732b6dfaa9..923416ecb0 100644 --- a/lib/Elastica/Bulk.php +++ b/lib/Elastica/Bulk.php @@ -228,7 +228,7 @@ public function addScripts(array $scripts, $opType = null): self */ public function addData($data, string $opType = null) { - if (!is_array($data)) { + if (!\is_array($data)) { $data = [$data]; } @@ -255,9 +255,9 @@ public function addData($data, string $opType = null) public function addRawData(array $data): self { foreach ($data as $row) { - if (is_array($row)) { - $opType = key($row); - $metadata = reset($row); + if (\is_array($row)) { + $opType = \key($row); + $metadata = \reset($row); if (Action::isValidOpType($opType)) { // add previous action if (isset($action)) { @@ -377,7 +377,7 @@ protected function _processResponse(Response $response): ResponseSet $bulkResponses = []; - if (isset($responseData['items']) && is_array($responseData['items'])) { + if (isset($responseData['items']) && \is_array($responseData['items'])) { foreach ($responseData['items'] as $key => $item) { if (!isset($actions[$key])) { throw new InvalidException('No response found for action #'.$key); @@ -385,8 +385,8 @@ protected function _processResponse(Response $response): ResponseSet $action = $actions[$key]; - $opType = key($item); - $bulkResponseData = reset($item); + $opType = \key($item); + $bulkResponseData = \reset($item); if ($action instanceof AbstractDocumentAction) { $data = $action->getData(); diff --git a/lib/Elastica/Bulk/Action.php b/lib/Elastica/Bulk/Action.php index 0dd31a1d7f..89244a3d69 100644 --- a/lib/Elastica/Bulk/Action.php +++ b/lib/Elastica/Bulk/Action.php @@ -203,9 +203,9 @@ public function toString(): string $string = JSON::stringify($this->getActionMetadata(), JSON_FORCE_OBJECT).Bulk::DELIMITER; if ($this->hasSource()) { $source = $this->getSource(); - if (is_string($source)) { + if (\is_string($source)) { $string .= $source; - } elseif (is_array($source) && array_key_exists('doc', $source) && is_string($source['doc'])) { + } elseif (\is_array($source) && \array_key_exists('doc', $source) && \is_string($source['doc'])) { if (isset($source['doc_as_upsert'])) { $docAsUpsert = ', "doc_as_upsert": '.($source['doc_as_upsert'] ? 'true' : 'false'); } else { @@ -228,6 +228,6 @@ public function toString(): string */ public static function isValidOpType(string $opType = null): bool { - return in_array($opType, self::$opTypes, true); + return \in_array($opType, self::$opTypes, true); } } diff --git a/lib/Elastica/Bulk/ResponseSet.php b/lib/Elastica/Bulk/ResponseSet.php index c1192bfd46..f7eb1735b4 100644 --- a/lib/Elastica/Bulk/ResponseSet.php +++ b/lib/Elastica/Bulk/ResponseSet.php @@ -140,6 +140,6 @@ public function rewind() */ public function count(): int { - return count($this->_bulkResponses); + return \count($this->_bulkResponses); } } diff --git a/lib/Elastica/Client.php b/lib/Elastica/Client.php index 4fe826440a..3c7686f7ee 100644 --- a/lib/Elastica/Client.php +++ b/lib/Elastica/Client.php @@ -160,7 +160,7 @@ protected function _prepareConnectionParams(array $config) $params = []; $params['config'] = []; foreach ($config as $key => $value) { - if (in_array($key, ['bigintConversion', 'curl', 'headers', 'url'])) { + if (\in_array($key, ['bigintConversion', 'curl', 'headers', 'url'])) { $params['config'][$key] = $value; } else { $params[$key] = $value; @@ -202,7 +202,7 @@ public function getConfig($key = '') return $this->_config; } - if (!array_key_exists($key, $this->_config)) { + if (!\array_key_exists($key, $this->_config)) { throw new InvalidException('Config key is not set: '.$key); } @@ -266,7 +266,7 @@ public function getIndex($name) */ public function addHeader($header, $headerValue) { - if (is_string($header) && is_string($headerValue)) { + if (\is_string($header) && \is_string($headerValue)) { $this->_config['headers'][$header] = $headerValue; } else { throw new InvalidException('Header must be a string'); @@ -286,8 +286,8 @@ public function addHeader($header, $headerValue) */ public function removeHeader($header) { - if (is_string($header)) { - if (array_key_exists($header, $this->_config['headers'])) { + if (\is_string($header)) { + if (\array_key_exists($header, $this->_config['headers'])) { unset($this->_config['headers'][$header]); } } else { @@ -461,11 +461,11 @@ protected function _populateDocumentFieldsFromResponse(Response $response, Docum { $responseData = $response->getData(); if ('_source' == $fields) { - if (isset($responseData['get']['_source']) && is_array($responseData['get']['_source'])) { + if (isset($responseData['get']['_source']) && \is_array($responseData['get']['_source'])) { $document->setData($responseData['get']['_source']); } } else { - $keys = explode(',', $fields); + $keys = \explode(',', $fields); $data = $document->getData(); foreach ($keys as $key) { if (isset($responseData['get']['fields'][$key])) { @@ -715,7 +715,7 @@ public function request($path, $method = Request::GET, $data = [], array $query public function requestEndpoint(AbstractEndpoint $endpoint) { return $this->request( - ltrim($endpoint->getURI(), '/'), + \ltrim($endpoint->getURI(), '/'), $endpoint->getMethod(), null === $endpoint->getBody() ? [] : $endpoint->getBody(), $endpoint->getParams() @@ -768,7 +768,7 @@ protected function _log($context) */ public function optimizeAll($args = []) { - trigger_error('Deprecated: Elastica\Client::optimizeAll() is deprecated and will be removed in further Elastica releases. Use Elastica\Client::forcemergeAll() instead.', E_USER_DEPRECATED); + \trigger_error('Deprecated: Elastica\Client::optimizeAll() is deprecated and will be removed in further Elastica releases. Use Elastica\Client::forcemergeAll() instead.', E_USER_DEPRECATED); return $this->forcemergeAll($args); } diff --git a/lib/Elastica/Cluster.php b/lib/Elastica/Cluster.php index c800f6f69d..baa25c9ea5 100644 --- a/lib/Elastica/Cluster.php +++ b/lib/Elastica/Cluster.php @@ -74,7 +74,7 @@ public function getResponse() */ public function getIndexNames() { - return array_keys($this->_data['metadata']['indices']); + return \array_keys($this->_data['metadata']['indices']); } /** diff --git a/lib/Elastica/Cluster/Settings.php b/lib/Elastica/Cluster/Settings.php index 359dd2dbc5..4c7e8a8b75 100644 --- a/lib/Elastica/Cluster/Settings.php +++ b/lib/Elastica/Cluster/Settings.php @@ -80,9 +80,9 @@ public function getTransient(string $setting = '') return $settings[$setting]; } - if (false !== strpos($setting, '.')) { + if (false !== \strpos($setting, '.')) { // convert dot notation to nested arrays - $keys = explode('.', $setting); + $keys = \explode('.', $setting); foreach ($keys as $key) { if (isset($settings[$key])) { $settings = $settings[$key]; diff --git a/lib/Elastica/Connection.php b/lib/Elastica/Connection.php index aabd07f5ac..26d44e467e 100644 --- a/lib/Elastica/Connection.php +++ b/lib/Elastica/Connection.php @@ -315,7 +315,7 @@ public function getConfig($key = '') return $config; } - if (!array_key_exists($key, $config)) { + if (!\array_key_exists($key, $config)) { throw new InvalidException('Config key is not set: '.$key); } @@ -331,7 +331,7 @@ public function getConfig($key = '') */ public static function create($params = []) { - if (is_array($params)) { + if (\is_array($params)) { return new self($params); } diff --git a/lib/Elastica/Connection/Strategy/StrategyFactory.php b/lib/Elastica/Connection/Strategy/StrategyFactory.php index 013925f23d..5b45adf5c6 100644 --- a/lib/Elastica/Connection/Strategy/StrategyFactory.php +++ b/lib/Elastica/Connection/Strategy/StrategyFactory.php @@ -28,15 +28,15 @@ public static function create($strategyName): StrategyInterface return new CallbackStrategy($strategyName); } - if (is_string($strategyName)) { + if (\is_string($strategyName)) { $requiredInterface = StrategyInterface::class; $predefinedStrategy = '\\Elastica\\Connection\\Strategy\\'.$strategyName; - if (class_exists($predefinedStrategy) && class_implements($predefinedStrategy, $requiredInterface)) { + if (\class_exists($predefinedStrategy) && \class_implements($predefinedStrategy, $requiredInterface)) { return new $predefinedStrategy(); } - if (class_exists($strategyName) && class_implements($strategyName, $requiredInterface)) { + if (\class_exists($strategyName) && \class_implements($strategyName, $requiredInterface)) { return new $strategyName(); } } diff --git a/lib/Elastica/Document.php b/lib/Elastica/Document.php index fdc6ccd569..1721ddb7c3 100644 --- a/lib/Elastica/Document.php +++ b/lib/Elastica/Document.php @@ -112,7 +112,7 @@ public function get($key) */ public function set($key, $value) { - if (!is_array($this->_data)) { + if (!\is_array($this->_data)) { throw new InvalidException('Document data is serialized data. Data creation is forbidden.'); } $this->_data[$key] = $value; @@ -127,7 +127,7 @@ public function set($key, $value) */ public function has($key) { - return is_array($this->_data) && array_key_exists($key, $this->_data); + return \is_array($this->_data) && \array_key_exists($key, $this->_data); } /** @@ -166,7 +166,7 @@ public function remove($key) */ public function addFile($key, $filepath, $mimeType = '') { - $value = base64_encode(file_get_contents($filepath)); + $value = \base64_encode(\file_get_contents($filepath)); if (!empty($mimeType)) { $value = ['_content_type' => $mimeType, '_name' => $filepath, '_content' => $value]; @@ -187,7 +187,7 @@ public function addFile($key, $filepath, $mimeType = '') */ public function addFileContent($key, $content) { - return $this->set($key, base64_encode($content)); + return $this->set($key, \base64_encode($content)); } /** @@ -330,7 +330,7 @@ public static function create($data) return $data; } - if (is_array($data)) { + if (\is_array($data)) { return new self('', $data); } diff --git a/lib/Elastica/Exception/ElasticsearchException.php b/lib/Elastica/Exception/ElasticsearchException.php index 2379d37666..62be48cacb 100644 --- a/lib/Elastica/Exception/ElasticsearchException.php +++ b/lib/Elastica/Exception/ElasticsearchException.php @@ -2,7 +2,7 @@ namespace Elastica\Exception; -trigger_error('Elastica\Exception\ElasticsearchException is deprecated. Use Elastica\Exception\ResponseException::getResponse::getFullError instead.', E_USER_DEPRECATED); +\trigger_error('Elastica\Exception\ElasticsearchException is deprecated. Use Elastica\Exception\ResponseException::getResponse::getFullError instead.', E_USER_DEPRECATED); /** * Elasticsearch exception. @@ -47,9 +47,9 @@ public function __construct(int $code, string $error) */ protected function _parseError(string $error) { - $errors = explode(']; nested: ', $error); + $errors = \explode(']; nested: ', $error); - if (1 === count($errors)) { + if (1 === \count($errors)) { $this->_exception = $this->_extractException($errors[0]); } else { if (self::REMOTE_TRANSPORT_EXCEPTION === $this->_extractException($errors[0])) { @@ -70,7 +70,7 @@ protected function _parseError(string $error) */ protected function _extractException(string $error) { - if (preg_match('/^(\w+)\[.*\]/', $error, $matches)) { + if (\preg_match('/^(\w+)\[.*\]/', $error, $matches)) { return $matches[1]; } diff --git a/lib/Elastica/Index.php b/lib/Elastica/Index.php index bf52d832ef..96deeb9c2e 100644 --- a/lib/Elastica/Index.php +++ b/lib/Elastica/Index.php @@ -61,7 +61,7 @@ public function __construct(Client $client, $name) { $this->_client = $client; - if (!is_scalar($name)) { + if (!\is_scalar($name)) { throw new InvalidException('Index name should be a scalar type'); } $this->_name = (string) $name; @@ -110,7 +110,7 @@ public function getMapping() $data = $response->getData(); // Get first entry as if index is an Alias, the name of the mapping is the real name and not alias name - $mapping = array_shift($data); + $mapping = \array_shift($data); if (isset($mapping['mappings'])) { return $mapping['mappings']; @@ -164,7 +164,7 @@ public function updateByQuery($query, AbstractScript $script, array $options = [ $query = Query::create($query)->getQuery(); $endpoint = new UpdateByQuery(); - $body = ['query' => is_array($query) + $body = ['query' => \is_array($query) ? $query : $query->toArray(), ]; @@ -209,7 +209,7 @@ public function deleteByQuery($query, array $options = []) $query = Query::create($query)->getQuery(); $endpoint = new DeleteByQuery(); - $endpoint->setBody(['query' => is_array($query) ? $query : $query->toArray()]); + $endpoint->setBody(['query' => \is_array($query) ? $query : $query->toArray()]); $endpoint->setParams($options); return $this->requestEndpoint($endpoint); @@ -291,13 +291,13 @@ public function refresh() */ public function create(array $args = [], $options = null) { - if (is_bool($options) && $options) { + if (\is_bool($options) && $options) { try { $this->delete(); } catch (ResponseException $e) { // Table can't be deleted, because doesn't exist } - } elseif (is_array($options)) { + } elseif (\is_array($options)) { foreach ($options as $key => $value) { switch ($key) { case 'recreate': @@ -489,7 +489,7 @@ public function getAliases() $data = $responseData[$this->getName()]; if (!empty($data['aliases'])) { - return array_keys($data['aliases']); + return \array_keys($data['aliases']); } return []; @@ -504,7 +504,7 @@ public function getAliases() */ public function hasAlias($name) { - return in_array($name, $this->getAliases()); + return \in_array($name, $this->getAliases()); } /** diff --git a/lib/Elastica/Index/Settings.php b/lib/Elastica/Index/Settings.php index d77ffa49d0..0d6546b27e 100644 --- a/lib/Elastica/Index/Settings.php +++ b/lib/Elastica/Index/Settings.php @@ -74,7 +74,7 @@ public function __construct(BaseIndex $index) public function get(string $setting = '') { $requestData = $this->request()->getData(); - $data = reset($requestData); + $data = \reset($requestData); if (empty($data['settings']) || empty($data['settings']['index'])) { // should not append, the request should throw a ResponseException @@ -91,9 +91,9 @@ public function get(string $setting = '') return $settings[$setting]; } - if (false !== strpos($setting, '.')) { + if (false !== \strpos($setting, '.')) { // translate old dot-notation settings to nested arrays - $keys = explode('.', $setting); + $keys = \explode('.', $setting); foreach ($keys as $key) { if (isset($settings[$key])) { $settings = $settings[$key]; diff --git a/lib/Elastica/Index/Stats.php b/lib/Elastica/Index/Stats.php index 7cfa2d1169..a1e2157361 100644 --- a/lib/Elastica/Index/Stats.php +++ b/lib/Elastica/Index/Stats.php @@ -66,7 +66,7 @@ public function get() { $data = $this->getData(); - foreach (func_get_args() as $arg) { + foreach (\func_get_args() as $arg) { if (isset($data[$arg])) { $data = $data[$arg]; } else { diff --git a/lib/Elastica/IndexTemplate.php b/lib/Elastica/IndexTemplate.php index 1b37c8e4e2..f766ad1860 100644 --- a/lib/Elastica/IndexTemplate.php +++ b/lib/Elastica/IndexTemplate.php @@ -39,7 +39,7 @@ public function __construct(Client $client, $name) { $this->_client = $client; - if (!is_scalar($name)) { + if (!\is_scalar($name)) { throw new InvalidException('Index template should be a scalar type'); } $this->_name = (string) $name; diff --git a/lib/Elastica/JSON.php b/lib/Elastica/JSON.php index 47754cb91f..19cddcedb0 100644 --- a/lib/Elastica/JSON.php +++ b/lib/Elastica/JSON.php @@ -24,15 +24,15 @@ class JSON public static function parse($args/* inherit from json_decode */) { // extract arguments - $args = func_get_args(); + $args = \func_get_args(); // default to decoding into an assoc array - if (1 === count($args)) { + if (1 === \count($args)) { $args[] = true; } // run decode - $array = call_user_func_array('json_decode', $args); + $array = \call_user_func_array('json_decode', $args); // turn errors into exceptions for easier catching if ($error = self::getJsonLastErrorMsg()) { @@ -58,10 +58,10 @@ public static function parse($args/* inherit from json_decode */) public static function stringify($args/* inherit from json_encode */) { // extract arguments - $args = func_get_args(); + $args = \func_get_args(); // run encode and output - $string = call_user_func_array('json_encode', $args); + $string = \call_user_func_array('json_encode', $args); // turn errors into exceptions for easier catching if ($error = self::getJsonLastErrorMsg()) { @@ -83,6 +83,6 @@ public static function stringify($args/* inherit from json_encode */) */ private static function getJsonLastErrorMsg() { - return JSON_ERROR_NONE !== json_last_error() ? json_last_error_msg() : false; + return JSON_ERROR_NONE !== \json_last_error() ? \json_last_error_msg() : false; } } diff --git a/lib/Elastica/Log.php b/lib/Elastica/Log.php index df6857e41d..d73d0a137e 100644 --- a/lib/Elastica/Log.php +++ b/lib/Elastica/Log.php @@ -49,10 +49,10 @@ public function log($level, $message, array $context = []) $context['error_message'] = $message; $this->_lastMessage = JSON::stringify($context); - if (!empty($this->_log) && is_string($this->_log)) { - error_log($this->_lastMessage.PHP_EOL, 3, $this->_log); + if (!empty($this->_log) && \is_string($this->_log)) { + \error_log($this->_lastMessage.PHP_EOL, 3, $this->_log); } else { - error_log($this->_lastMessage); + \error_log($this->_lastMessage); } } diff --git a/lib/Elastica/Multi/MultiBuilder.php b/lib/Elastica/Multi/MultiBuilder.php index f7cae45185..31baa8cc34 100644 --- a/lib/Elastica/Multi/MultiBuilder.php +++ b/lib/Elastica/Multi/MultiBuilder.php @@ -41,17 +41,17 @@ private function buildResultSet(Response $childResponse, BaseSearch $search): Ba private function buildResultSets(Response $response, $searches): array { $data = $response->getData(); - if (!isset($data['responses']) || !is_array($data['responses'])) { + if (!isset($data['responses']) || !\is_array($data['responses'])) { return []; } $resultSets = []; - reset($searches); + \reset($searches); foreach ($data['responses'] as $responseData) { - $search = current($searches); - $key = key($searches); - next($searches); + $search = \current($searches); + $key = \key($searches); + \next($searches); $resultSets[$key] = $this->buildResultSet(new Response($responseData), $search); } diff --git a/lib/Elastica/Multi/ResultSet.php b/lib/Elastica/Multi/ResultSet.php index a974de467b..a1be42db7e 100644 --- a/lib/Elastica/Multi/ResultSet.php +++ b/lib/Elastica/Multi/ResultSet.php @@ -125,7 +125,7 @@ public function rewind() */ public function count(): int { - return count($this->_resultSets); + return \count($this->_resultSets); } /** diff --git a/lib/Elastica/Multi/Search.php b/lib/Elastica/Multi/Search.php index 8d5e260733..f3eb4f63ff 100644 --- a/lib/Elastica/Multi/Search.php +++ b/lib/Elastica/Multi/Search.php @@ -185,7 +185,7 @@ protected function _getSearchData(BaseSearch $search): string $query = $search->getQuery(); // Keep other query options as part of the search body - $queryOptions = array_diff_key($search->getOptions(), array_flip(self::$HEADER_OPTIONS)); + $queryOptions = \array_diff_key($search->getOptions(), \array_flip(self::$HEADER_OPTIONS)); $data = JSON::stringify($header)."\n"; $data .= JSON::stringify($query->toArray() + $queryOptions)."\n"; @@ -211,6 +211,6 @@ protected function _getSearchDataHeader(BaseSearch $search): array } // Filter options accepted in the "header" - return array_intersect_key($header, array_flip(self::$HEADER_OPTIONS)); + return \array_intersect_key($header, \array_flip(self::$HEADER_OPTIONS)); } } diff --git a/lib/Elastica/Node/Info.php b/lib/Elastica/Node/Info.php index 9a2102cc5b..5e4e872de8 100644 --- a/lib/Elastica/Node/Info.php +++ b/lib/Elastica/Node/Info.php @@ -75,7 +75,7 @@ public function get() { $data = $this->getData(); - foreach (func_get_args() as $arg) { + foreach (\func_get_args() as $arg) { if (isset($data[$arg])) { $data = $data[$arg]; } else { @@ -95,8 +95,8 @@ public function getPort(): string { // Returns string in format: inet[/192.168.1.115:9201] $data = $this->get('http_address'); - $data = substr($data, 6, strlen($data) - 7); - $data = explode(':', $data); + $data = \substr($data, 6, \strlen($data) - 7); + $data = \explode(':', $data); return $data[1]; } @@ -110,8 +110,8 @@ public function getIp(): string { // Returns string in format: inet[/192.168.1.115:9201] $data = $this->get('http_address'); - $data = substr($data, 6, strlen($data) - 7); - $data = explode(':', $data); + $data = \substr($data, 6, \strlen($data) - 7); + $data = \explode(':', $data); return $data[0]; } @@ -125,7 +125,7 @@ public function getIp(): string */ public function getPlugins(): array { - if (!in_array('plugins', $this->_params, true)) { + if (!\in_array('plugins', $this->_params, true)) { //Plugin data was not retrieved when refresh() was called last. Get it now. $this->_params[] = 'plugins'; $this->refresh($this->_params); @@ -219,8 +219,8 @@ public function refresh(array $params = []): Response $this->_response = $this->getNode()->getClient()->requestEndpoint($endpoint); $data = $this->getResponse()->getData(); - $this->_data = reset($data['nodes']); - $this->_id = key($data['nodes']); + $this->_data = \reset($data['nodes']); + $this->_id = \key($data['nodes']); $this->getNode()->setId($this->getId()); return $this->_response; diff --git a/lib/Elastica/Node/Stats.php b/lib/Elastica/Node/Stats.php index c0f96dfc4e..c833045000 100644 --- a/lib/Elastica/Node/Stats.php +++ b/lib/Elastica/Node/Stats.php @@ -58,7 +58,7 @@ public function get() { $data = $this->getData(); - foreach (func_get_args() as $arg) { + foreach (\func_get_args() as $arg) { if (isset($data[$arg])) { $data = $data[$arg]; } else { @@ -111,7 +111,7 @@ public function refresh(): Response $this->_response = $this->getNode()->getClient()->requestEndpoint($endpoint); $data = $this->getResponse()->getData(); - $this->_data = reset($data['nodes']); + $this->_data = \reset($data['nodes']); return $this->_response; } diff --git a/lib/Elastica/Param.php b/lib/Elastica/Param.php index 0c765eb0b3..b0b7218e7f 100644 --- a/lib/Elastica/Param.php +++ b/lib/Elastica/Param.php @@ -39,7 +39,7 @@ public function toArray() $data = [$this->_getBaseName() => $this->getParams()]; if (!empty($this->_rawParams)) { - $data = array_merge($data, $this->_rawParams); + $data = \array_merge($data, $this->_rawParams); } return $this->_convertArrayable($data); @@ -59,7 +59,7 @@ protected function _convertArrayable(array $array) foreach ($array as $key => $value) { if ($value instanceof ArrayableInterface) { $arr[$value instanceof NameableInterface ? $value->getName() : $key] = $value->toArray(); - } elseif (is_array($value)) { + } elseif (\is_array($value)) { $arr[$key] = $this->_convertArrayable($value); } else { $arr[$key] = $value; @@ -189,6 +189,6 @@ public function getParams() */ public function count() { - return count($this->_params); + return \count($this->_params); } } diff --git a/lib/Elastica/Pipeline.php b/lib/Elastica/Pipeline.php index d26b72788a..f5af2f14da 100644 --- a/lib/Elastica/Pipeline.php +++ b/lib/Elastica/Pipeline.php @@ -147,7 +147,7 @@ public function addProcessor(AbstractProcessor $processor) $this->_processors['processors'] = $processor->toArray(); $this->_params['processors'] = []; } else { - $this->_processors['processors'] = array_merge($this->_processors['processors'], $processor->toArray()); + $this->_processors['processors'] = \array_merge($this->_processors['processors'], $processor->toArray()); } return $this; diff --git a/lib/Elastica/Query.php b/lib/Elastica/Query.php index 6af3ce3c87..3f07abb7c9 100644 --- a/lib/Elastica/Query.php +++ b/lib/Elastica/Query.php @@ -36,7 +36,7 @@ class Query extends Param */ public function __construct($query = null) { - if (is_array($query)) { + if (\is_array($query)) { $this->setRawQuery($query); } elseif ($query instanceof AbstractQuery) { $this->setQuery($query); @@ -65,9 +65,9 @@ public static function create($query) return new self($query); case empty($query): return new self(new MatchAll()); - case is_array($query): + case \is_array($query): return new self($query); - case is_string($query): + case \is_string($query): return new self(new QueryString($query)); case $query instanceof AbstractSuggest: return new self(new Suggest($query)); @@ -279,7 +279,7 @@ public function setFieldDataFields(array $fieldDataFields) */ public function setScriptFields($scriptFields) { - if (is_array($scriptFields)) { + if (\is_array($scriptFields)) { $scriptFields = new ScriptFields($scriptFields); } @@ -330,7 +330,7 @@ public function toArray() $this->setQuery(new MatchAll()); } - if (isset($this->_params['post_filter']) && 0 === count(($this->_params['post_filter'])->toArray())) { + if (isset($this->_params['post_filter']) && 0 === \count(($this->_params['post_filter'])->toArray())) { unset($this->_params['post_filter']); } @@ -354,7 +354,7 @@ public function toArray() */ public function setMinScore($minScore) { - if (!is_numeric($minScore)) { + if (!\is_numeric($minScore)) { throw new InvalidException('has to be numeric param'); } @@ -386,7 +386,7 @@ public function setSuggest(Suggest $suggest) */ public function setRescore($rescore) { - if (is_array($rescore)) { + if (\is_array($rescore)) { $buffer = []; foreach ($rescore as $rescoreQuery) { diff --git a/lib/Elastica/Query/AbstractGeoDistance.php b/lib/Elastica/Query/AbstractGeoDistance.php index 2037eddf11..24b74d75f0 100644 --- a/lib/Elastica/Query/AbstractGeoDistance.php +++ b/lib/Elastica/Query/AbstractGeoDistance.php @@ -90,7 +90,7 @@ public function setKey(string $key): self public function setLocation($location): self { // Location - if (is_array($location)) { // Latitude/Longitude + if (\is_array($location)) { // Latitude/Longitude // Latitude if (isset($location['lat'])) { $this->setLatitude($location['lat']); @@ -104,7 +104,7 @@ public function setLocation($location): self } else { throw new InvalidException('$location[\'lon\'] has to be set'); } - } elseif (is_string($location)) { // Geohash + } elseif (\is_string($location)) { // Geohash $this->setGeohash($location); } else { // Invalid location throw new InvalidException('$location has to be an array (latitude/longitude) or a string (geohash)'); diff --git a/lib/Elastica/Query/BoolQuery.php b/lib/Elastica/Query/BoolQuery.php index dfc30e2e56..9c8df96c63 100644 --- a/lib/Elastica/Query/BoolQuery.php +++ b/lib/Elastica/Query/BoolQuery.php @@ -73,7 +73,7 @@ public function addFilter(AbstractQuery $filter): self */ protected function _addQuery(string $type, $args): self { - if (!is_array($args) && !($args instanceof AbstractQuery)) { + if (!\is_array($args) && !($args instanceof AbstractQuery)) { throw new InvalidException('Invalid parameter. Has to be array or instance of Elastica\Query\AbstractQuery'); } diff --git a/lib/Elastica/Query/DisMax.php b/lib/Elastica/Query/DisMax.php index 7009b63d2a..fd88e57859 100644 --- a/lib/Elastica/Query/DisMax.php +++ b/lib/Elastica/Query/DisMax.php @@ -24,7 +24,7 @@ class DisMax extends AbstractQuery */ public function addQuery($args): self { - if (!is_array($args) && !($args instanceof AbstractQuery)) { + if (!\is_array($args) && !($args instanceof AbstractQuery)) { throw new InvalidException('Invalid parameter. Has to be array or instance of Elastica\Query\AbstractQuery'); } diff --git a/lib/Elastica/Query/Fuzzy.php b/lib/Elastica/Query/Fuzzy.php index b6c315b811..3a4ed5dc91 100644 --- a/lib/Elastica/Query/Fuzzy.php +++ b/lib/Elastica/Query/Fuzzy.php @@ -36,10 +36,10 @@ public function __construct(string $fieldName = null, string $value = null) */ public function setField(string $fieldName, string $value): self { - if (!is_string($value) || !is_string($fieldName)) { + if (!\is_string($value) || !\is_string($fieldName)) { throw new InvalidException('The field and value arguments must be of type string.'); } - if (count($this->getParams()) > 0 && key($this->getParams()) !== $fieldName) { + if (\count($this->getParams()) > 0 && \key($this->getParams()) !== $fieldName) { throw new InvalidException('Fuzzy query can only support a single field.'); } @@ -58,10 +58,10 @@ public function setFieldOption(string $option, $value): self { //Retrieve the single existing field for alteration. $params = $this->getParams(); - if (count($params) < 1) { + if (\count($params) < 1) { throw new InvalidException('No field has been set'); } - $key = key($params); + $key = \key($params); $params[$key][$option] = $value; return $this->setParam($key, $params[$key]); diff --git a/lib/Elastica/Query/GeoPolygon.php b/lib/Elastica/Query/GeoPolygon.php index da69927f54..9f8d6a06d5 100644 --- a/lib/Elastica/Query/GeoPolygon.php +++ b/lib/Elastica/Query/GeoPolygon.php @@ -56,6 +56,6 @@ public function toArray(): array */ public function count(): int { - return count($this->_key); + return \count($this->_key); } } diff --git a/lib/Elastica/Query/GeohashCell.php b/lib/Elastica/Query/GeohashCell.php index c36f15526a..ca81739286 100644 --- a/lib/Elastica/Query/GeohashCell.php +++ b/lib/Elastica/Query/GeohashCell.php @@ -2,7 +2,7 @@ namespace Elastica\Query; -trigger_error('Elastica\Query\GeohashCell is deprecated.', E_USER_DEPRECATED); +\trigger_error('Elastica\Query\GeohashCell is deprecated.', E_USER_DEPRECATED); /** * Class GeohashCell. diff --git a/lib/Elastica/Query/Ids.php b/lib/Elastica/Query/Ids.php index e23a405eb8..09c83b219b 100644 --- a/lib/Elastica/Query/Ids.php +++ b/lib/Elastica/Query/Ids.php @@ -46,7 +46,7 @@ public function addId(string $id): self */ public function setIds($ids): self { - if (is_array($ids)) { + if (\is_array($ids)) { $this->_params['values'] = $ids; } else { $this->_params['values'] = [$ids]; diff --git a/lib/Elastica/Query/MoreLikeThis.php b/lib/Elastica/Query/MoreLikeThis.php index ce1b66a145..9c9457961a 100644 --- a/lib/Elastica/Query/MoreLikeThis.php +++ b/lib/Elastica/Query/MoreLikeThis.php @@ -140,7 +140,7 @@ public function setBoostTerms(bool $boostTerms = false): self */ public function setAnalyzer(string $analyzer): self { - $analyzer = trim($analyzer); + $analyzer = \trim($analyzer); return $this->setParam('analyzer', $analyzer); } @@ -180,7 +180,7 @@ public function toArray(): array // If _source is provided, perform MLT on a document provided as an input if (!empty($array['more_like_this']['like']['_id'])) { $doc = $array['more_like_this']['like']; - $doc = array_intersect_key($doc, ['_index' => 1, '_type' => 1, '_id' => 1]); + $doc = \array_intersect_key($doc, ['_index' => 1, '_type' => 1, '_id' => 1]); $array['more_like_this']['like'] = $doc; } elseif (!empty($array['more_like_this']['like']['_source'])) { $doc = $array['more_like_this']['like']; diff --git a/lib/Elastica/Query/QueryString.php b/lib/Elastica/Query/QueryString.php index 8a0542c471..c6d9a0d488 100644 --- a/lib/Elastica/Query/QueryString.php +++ b/lib/Elastica/Query/QueryString.php @@ -262,6 +262,6 @@ public function setTimezone(string $timezone): self */ public function toArray(): array { - return ['query_string' => array_merge(['query' => $this->_queryString], $this->getParams())]; + return ['query_string' => \array_merge(['query' => $this->_queryString], $this->getParams())]; } } diff --git a/lib/Elastica/Query/SimpleQueryString.php b/lib/Elastica/Query/SimpleQueryString.php index bc4613fc7b..44189d3120 100644 --- a/lib/Elastica/Query/SimpleQueryString.php +++ b/lib/Elastica/Query/SimpleQueryString.php @@ -19,7 +19,7 @@ class SimpleQueryString extends AbstractQuery public function __construct(string $query, array $fields = []) { $this->setQuery($query); - if (0 < count($fields)) { + if (0 < \count($fields)) { $this->setFields($fields); } } diff --git a/lib/Elastica/Query/SpanFirst.php b/lib/Elastica/Query/SpanFirst.php index 4539b81ca0..ef661303a2 100644 --- a/lib/Elastica/Query/SpanFirst.php +++ b/lib/Elastica/Query/SpanFirst.php @@ -70,7 +70,7 @@ public function setEnd(int $end): self */ protected function _setQuery(string $type, $args): self { - if (!is_array($args) && !($args instanceof AbstractSpanQuery)) { + if (!\is_array($args) && !($args instanceof AbstractSpanQuery)) { throw new InvalidException('Invalid parameter. Has to be array or instance of Elastica\Query\AbstractSpanQuery'); } diff --git a/lib/Elastica/Query/SpanMulti.php b/lib/Elastica/Query/SpanMulti.php index 682a1ddfd6..84a813bc40 100644 --- a/lib/Elastica/Query/SpanMulti.php +++ b/lib/Elastica/Query/SpanMulti.php @@ -50,7 +50,7 @@ public function setMatch($args): self */ protected function _setQuery(string $type, $args): self { - if (!is_array($args) && !($args instanceof AbstractQuery)) { + if (!\is_array($args) && !($args instanceof AbstractQuery)) { throw new InvalidException('Invalid parameter. Has to be array or instance of Elastica\Query\AbstractQuery'); } diff --git a/lib/Elastica/Query/Terms.php b/lib/Elastica/Query/Terms.php index 1eae19caf8..0f0aff4e94 100644 --- a/lib/Elastica/Query/Terms.php +++ b/lib/Elastica/Query/Terms.php @@ -50,7 +50,7 @@ public function __construct(string $key = '', array $terms = []) public function setTerms(string $key, array $terms): self { $this->_key = $key; - $this->_terms = array_values($terms); + $this->_terms = \array_values($terms); return $this; } diff --git a/lib/Elastica/QueryBuilder/Facade.php b/lib/Elastica/QueryBuilder/Facade.php index b3254f7020..76dc6d2953 100644 --- a/lib/Elastica/QueryBuilder/Facade.php +++ b/lib/Elastica/QueryBuilder/Facade.php @@ -46,7 +46,7 @@ public function __construct(DSL $dsl, Version $version) public function __call(string $name, array $arguments) { // defined check - if (false === method_exists($this->_dsl, $name)) { + if (false === \method_exists($this->_dsl, $name)) { throw new QueryBuilderException( 'undefined '.$this->_dsl->getType().' "'.$name.'"' ); @@ -60,6 +60,6 @@ public function __call(string $name, array $arguments) ); } - return call_user_func_array([$this->_dsl, $name], $arguments); + return \call_user_func_array([$this->_dsl, $name], $arguments); } } diff --git a/lib/Elastica/QueryBuilder/Version.php b/lib/Elastica/QueryBuilder/Version.php index 69b0190221..41daa73501 100644 --- a/lib/Elastica/QueryBuilder/Version.php +++ b/lib/Elastica/QueryBuilder/Version.php @@ -49,11 +49,11 @@ public function supports(string $name, string $type): bool { switch ($type) { case DSL::TYPE_QUERY: - return in_array($name, $this->queries, true); + return \in_array($name, $this->queries, true); case DSL::TYPE_AGGREGATION: - return in_array($name, $this->aggregations, true); + return \in_array($name, $this->aggregations, true); case DSL::TYPE_SUGGEST: - return in_array($name, $this->suggesters, true); + return \in_array($name, $this->suggesters, true); } // disables version check in Facade for custom DSL objects diff --git a/lib/Elastica/Reindex.php b/lib/Elastica/Reindex.php index e5e6445a31..fd9ca0c6c9 100644 --- a/lib/Elastica/Reindex.php +++ b/lib/Elastica/Reindex.php @@ -54,7 +54,7 @@ public function run() protected function _getBody($oldIndex, $newIndex, $options) { - $body = array_merge([ + $body = \array_merge([ 'source' => $this->_getSourcePartBody($oldIndex, $options), 'dest' => $this->_getDestPartBody($newIndex, $options), ], $this->_resolveBodyOptions($options)); @@ -64,7 +64,7 @@ protected function _getBody($oldIndex, $newIndex, $options) protected function _getSourcePartBody(Index $index, array $options) { - $sourceBody = array_merge([ + $sourceBody = \array_merge([ 'index' => $index->getName(), ], $this->_resolveSourceOptions($options)); @@ -76,14 +76,14 @@ protected function _getSourcePartBody(Index $index, array $options) protected function _getDestPartBody(Index $index, array $options) { - return array_merge([ + return \array_merge([ 'index' => $index->getName(), ], $this->_resolveDestOptions($options)); } private function _resolveSourceOptions(array $options) { - return array_intersect_key($options, [ + return \array_intersect_key($options, [ self::TYPE => null, self::QUERY => null, ]); @@ -91,7 +91,7 @@ private function _resolveSourceOptions(array $options) private function _resolveDestOptions(array $options) { - return array_intersect_key($options, [ + return \array_intersect_key($options, [ self::VERSION_TYPE => null, self::OPERATION_TYPE => null, ]); @@ -99,7 +99,7 @@ private function _resolveDestOptions(array $options) private function _resolveBodyOptions(array $options) { - return array_intersect_key($options, [ + return \array_intersect_key($options, [ self::SIZE => null, self::CONFLICTS => null, ]); @@ -126,7 +126,7 @@ private function _setSourceQuery(array $sourceBody) */ private function _setSourceType(array $sourceBody) { - if (isset($sourceBody[self::TYPE]) && !is_array($sourceBody[self::TYPE])) { + if (isset($sourceBody[self::TYPE]) && !\is_array($sourceBody[self::TYPE])) { $sourceBody[self::TYPE] = [$sourceBody[self::TYPE]]; } if (isset($sourceBody[self::TYPE])) { diff --git a/lib/Elastica/Rescore/Query.php b/lib/Elastica/Rescore/Query.php index 4278d80261..a0a17b024d 100644 --- a/lib/Elastica/Rescore/Query.php +++ b/lib/Elastica/Rescore/Query.php @@ -35,7 +35,7 @@ public function toArray(): array $data = $this->getParams(); if (!empty($this->_rawParams)) { - $data = array_merge($data, $this->_rawParams); + $data = \array_merge($data, $this->_rawParams); } $array = $this->_convertArrayable($data); diff --git a/lib/Elastica/Response.php b/lib/Elastica/Response.php index a9dfb9789f..487e83cb39 100644 --- a/lib/Elastica/Response.php +++ b/lib/Elastica/Response.php @@ -64,7 +64,7 @@ class Response */ public function __construct($responseString, $responseStatus = null) { - if (is_array($responseString)) { + if (\is_array($responseString)) { $this->_response = $responseString; } else { $this->_responseString = $responseString; @@ -85,7 +85,7 @@ public function getError() return ''; } - if (is_string($error)) { + if (\is_string($error)) { return $error; } @@ -155,7 +155,7 @@ public function hasFailedShards() return false; } - return array_key_exists('failures', $shardsStatistics); + return \array_key_exists('failures', $shardsStatistics); } /** @@ -230,7 +230,7 @@ public function getData() $response = []; } - if (is_string($response)) { + if (\is_string($response)) { $response = ['message' => $response]; } diff --git a/lib/Elastica/Result.php b/lib/Elastica/Result.php index a20c54017d..5ef9907ed8 100644 --- a/lib/Elastica/Result.php +++ b/lib/Elastica/Result.php @@ -171,7 +171,7 @@ public function getData() { if (isset($this->_hit['fields'])) { return isset($this->_hit['_source']) - ? array_merge($this->getFields(), $this->getSource()) + ? \array_merge($this->getFields(), $this->getSource()) : $this->getFields(); } @@ -251,7 +251,7 @@ public function __get($key) { $source = $this->getData(); - return array_key_exists($key, $source) ? $source[$key] : null; + return \array_key_exists($key, $source) ? $source[$key] : null; } /** @@ -265,6 +265,6 @@ public function __isset($key) { $source = $this->getData(); - return array_key_exists($key, $source) && null !== $source[$key]; + return \array_key_exists($key, $source) && null !== $source[$key]; } } diff --git a/lib/Elastica/ResultSet.php b/lib/Elastica/ResultSet.php index e99d03ede8..1e4134f191 100644 --- a/lib/Elastica/ResultSet.php +++ b/lib/Elastica/ResultSet.php @@ -221,7 +221,7 @@ public function getQuery() */ public function count() { - return count($this->_results); + return \count($this->_results); } /** @@ -231,7 +231,7 @@ public function count() */ public function countSuggests() { - return sizeof($this->getSuggests()); + return \sizeof($this->getSuggests()); } /** diff --git a/lib/Elastica/Script/AbstractScript.php b/lib/Elastica/Script/AbstractScript.php index 3456db19a3..8c066b7505 100644 --- a/lib/Elastica/Script/AbstractScript.php +++ b/lib/Elastica/Script/AbstractScript.php @@ -42,12 +42,12 @@ public static function create($data) return $data; } - if (is_array($data)) { + if (\is_array($data)) { return self::_createFromArray($data); } - if (is_string($data)) { - $class = self::class === get_called_class() ? Script::class : get_called_class(); + if (\is_string($data)) { + $class = self::class === \get_called_class() ? Script::class : \get_called_class(); return new $class($data); } @@ -60,7 +60,7 @@ private static function _createFromArray(array $data) $params = $data['script']['params'] ?? []; $lang = $data['script']['lang'] ?? null; - if (!is_array($params)) { + if (!\is_array($params)) { throw new InvalidException('Script params must be an array'); } diff --git a/lib/Elastica/Script/ScriptFields.php b/lib/Elastica/Script/ScriptFields.php index a7dfb130ff..959c1888f5 100644 --- a/lib/Elastica/Script/ScriptFields.php +++ b/lib/Elastica/Script/ScriptFields.php @@ -32,9 +32,9 @@ public function __construct(array $scripts = []) * * @return $this */ - public function addScript(string $name, AbstractScript $script): ScriptFields + public function addScript(string $name, AbstractScript $script): self { - if (!strlen($name)) { + if (!\strlen($name)) { throw new InvalidException('The name of a Script is required and must be a string'); } $this->setParam($name, $script); @@ -47,7 +47,7 @@ public function addScript(string $name, AbstractScript $script): ScriptFields * * @return $this */ - public function setScripts(array $scripts): ScriptFields + public function setScripts(array $scripts): self { $this->_params = []; foreach ($scripts as $name => $script) { diff --git a/lib/Elastica/Scroll.php b/lib/Elastica/Scroll.php index 8a92fa31ee..f7be28edd8 100644 --- a/lib/Elastica/Scroll.php +++ b/lib/Elastica/Scroll.php @@ -159,7 +159,7 @@ public function clear() protected function _setScrollId(ResultSet $resultSet) { if (0 === $this->currentPage) { - $this->totalPages = $resultSet->count() > 0 ? ceil($resultSet->getTotalHits() / $resultSet->count()) : 0; + $this->totalPages = $resultSet->count() > 0 ? \ceil($resultSet->getTotalHits() / $resultSet->count()) : 0; } $this->_currentResultSet = $resultSet; diff --git a/lib/Elastica/Search.php b/lib/Elastica/Search.php index a2c4a8ea2a..b524d887ca 100644 --- a/lib/Elastica/Search.php +++ b/lib/Elastica/Search.php @@ -102,7 +102,7 @@ public function addIndex($index) $index = $index->getName(); } - if (!is_scalar($index)) { + if (!\is_scalar($index)) { throw new InvalidException('Invalid param type'); } @@ -142,7 +142,7 @@ public function addType($type) $type = $type->getName(); } - if (!is_string($type)) { + if (!\is_string($type)) { throw new InvalidException('Invalid type type'); } @@ -326,7 +326,7 @@ public function getIndices() */ public function hasIndices() { - return count($this->_indices) > 0; + return \count($this->_indices) > 0; } /** @@ -340,7 +340,7 @@ public function hasIndex($index) $index = $index->getName(); } - return in_array($index, $this->_indices); + return \in_array($index, $this->_indices); } /** @@ -358,7 +358,7 @@ public function getTypes() */ public function hasTypes() { - return count($this->_types) > 0; + return \count($this->_types) > 0; } /** @@ -372,7 +372,7 @@ public function hasType($type) $type = $type->getName(); } - return in_array($type, $this->_types); + return \in_array($type, $this->_types); } /** @@ -420,11 +420,11 @@ public function getPath() $path .= '_all'; } } else { - $path .= implode(',', $indices); + $path .= \implode(',', $indices); } if (!empty($types)) { - $path .= '/'.implode(',', $types); + $path .= '/'.\implode(',', $types); } // Add full path based on indices and types -> could be all @@ -506,9 +506,9 @@ public function setOptionsAndQuery($options = null, $query = '') $this->setQuery($query); } - if (is_int($options)) { + if (\is_int($options)) { $this->getQuery()->setSize($options); - } elseif (is_array($options)) { + } elseif (\is_array($options)) { if (isset($options['limit'])) { $this->getQuery()->setSize($options['limit']); unset($options['limit']); diff --git a/lib/Elastica/Status.php b/lib/Elastica/Status.php index c3fb90da57..5544b6267b 100644 --- a/lib/Elastica/Status.php +++ b/lib/Elastica/Status.php @@ -53,7 +53,7 @@ public function __construct(Client $client) */ public function getData() { - if (is_null($this->_data)) { + if (\is_null($this->_data)) { $this->refresh(); } @@ -69,7 +69,7 @@ public function getIndexNames() { $data = $this->getData(); - return array_keys($data['indices']); + return \array_keys($data['indices']); } /** @@ -81,7 +81,7 @@ public function getIndexNames() */ public function indexExists($name) { - return in_array($name, $this->getIndexNames()); + return \in_array($name, $this->getIndexNames()); } /** @@ -93,7 +93,7 @@ public function indexExists($name) */ public function aliasExists($name) { - return count($this->getIndicesWithAlias($name)) > 0; + return \count($this->getIndicesWithAlias($name)) > 0; } /** @@ -135,7 +135,7 @@ public function getIndicesWithAlias($alias) */ public function getResponse() { - if (is_null($this->_response)) { + if (\is_null($this->_response)) { $this->refresh(); } diff --git a/lib/Elastica/Suggest.php b/lib/Elastica/Suggest.php index d160abb81b..454dcb2473 100644 --- a/lib/Elastica/Suggest.php +++ b/lib/Elastica/Suggest.php @@ -17,7 +17,7 @@ class Suggest extends Param */ public function __construct(AbstractSuggest $suggestion = null) { - if (!is_null($suggestion)) { + if (!\is_null($suggestion)) { $this->addSuggestion($suggestion); } } diff --git a/lib/Elastica/Suggest/Phrase.php b/lib/Elastica/Suggest/Phrase.php index 20bd9795c3..48ac6be631 100644 --- a/lib/Elastica/Suggest/Phrase.php +++ b/lib/Elastica/Suggest/Phrase.php @@ -178,8 +178,8 @@ public function toArray(): array $generator = $array[$baseName]['candidate_generator']; unset($array[$baseName]['candidate_generator']); - $keys = array_keys($generator); - $values = array_values($generator); + $keys = \array_keys($generator); + $values = \array_values($generator); $array[$baseName][$keys[0]][] = $values[0]; } diff --git a/lib/Elastica/Task.php b/lib/Elastica/Task.php index 9fb74e129c..6dae049822 100644 --- a/lib/Elastica/Task.php +++ b/lib/Elastica/Task.php @@ -64,7 +64,7 @@ public function getId() */ public function getData(): array { - if (is_null($this->_data)) { + if (\is_null($this->_data)) { $this->refresh(); } @@ -78,7 +78,7 @@ public function getData(): array */ public function getResponse(): Response { - if (is_null($this->_response)) { + if (\is_null($this->_response)) { $this->refresh(); } diff --git a/lib/Elastica/Transport/AbstractTransport.php b/lib/Elastica/Transport/AbstractTransport.php index cefbd197da..29230aaa2d 100644 --- a/lib/Elastica/Transport/AbstractTransport.php +++ b/lib/Elastica/Transport/AbstractTransport.php @@ -73,7 +73,7 @@ abstract public function exec(Request $request, array $params): Response; public function sanityzeQueryStringBool(array $query) { foreach ($query as $key => $value) { - if (is_bool($value)) { + if (\is_bool($value)) { $query[$key] = ($value) ? 'true' : 'false'; } } @@ -101,28 +101,28 @@ public function sanityzeQueryStringBool(array $query) */ public static function create($transport, Connection $connection, array $params = []): AbstractTransport { - if (is_array($transport) && isset($transport['type'])) { + if (\is_array($transport) && isset($transport['type'])) { $transportParams = $transport; unset($transportParams['type']); - $params = array_replace($params, $transportParams); + $params = \array_replace($params, $transportParams); $transport = $transport['type']; } - if (is_string($transport)) { + if (\is_string($transport)) { $specialTransports = [ 'httpadapter' => 'HttpAdapter', 'nulltransport' => 'NullTransport', ]; - if (isset($specialTransports[strtolower($transport)])) { - $transport = $specialTransports[strtolower($transport)]; + if (isset($specialTransports[\strtolower($transport)])) { + $transport = $specialTransports[\strtolower($transport)]; } else { - $transport = ucfirst($transport); + $transport = \ucfirst($transport); } $classNames = ["Elastica\\Transport\\$transport", $transport]; foreach ($classNames as $className) { - if (class_exists($className)) { + if (\class_exists($className)) { $transport = new $className(); break; } diff --git a/lib/Elastica/Transport/AwsAuthV4.php b/lib/Elastica/Transport/AwsAuthV4.php index d93640fbf5..fb4593dc25 100644 --- a/lib/Elastica/Transport/AwsAuthV4.php +++ b/lib/Elastica/Transport/AwsAuthV4.php @@ -44,7 +44,7 @@ private function getSigningMiddleware() { $region = $this->getConnection()->hasParam('aws_region') ? $this->getConnection()->getParam('aws_region') - : getenv('AWS_REGION'); + : \getenv('AWS_REGION'); $signer = new SignatureV4('es', $region); $credProvider = $this->getCredentialProvider(); diff --git a/lib/Elastica/Transport/Guzzle.php b/lib/Elastica/Transport/Guzzle.php index 4ea52508b6..920e19da60 100644 --- a/lib/Elastica/Transport/Guzzle.php +++ b/lib/Elastica/Transport/Guzzle.php @@ -66,20 +66,20 @@ public function exec(Request $request, array $params): Response $proxy = $connection->getProxy(); // See: https://github.com/facebook/hhvm/issues/4875 - if (is_null($proxy) && defined('HHVM_VERSION')) { - $proxy = getenv('http_proxy') ?: null; + if (\is_null($proxy) && \defined('HHVM_VERSION')) { + $proxy = \getenv('http_proxy') ?: null; } - if (!is_null($proxy)) { + if (!\is_null($proxy)) { $options['proxy'] = $proxy; } $req = $this->_createPsr7Request($request, $connection); try { - $start = microtime(true); + $start = \microtime(true); $res = $client->send($req, $options); - $end = microtime(true); + $end = \microtime(true); } catch (TransferException $ex) { throw new GuzzleException($ex, $request, new Response($ex->getMessage())); } @@ -120,7 +120,7 @@ protected function _createPsr7Request(Request $request, Connection $connection) $req = new Psr7\Request( $request->getMethod(), $this->_getActionPath($request), - $connection->hasConfig('headers') && is_array($connection->getConfig('headers')) + $connection->hasConfig('headers') && \is_array($connection->getConfig('headers')) ? $connection->getConfig('headers') : [] ); @@ -137,7 +137,7 @@ protected function _createPsr7Request(Request $request, Connection $connection) } $req = $req->withBody( - Psr7\stream_for(is_array($data) + Psr7\stream_for(\is_array($data) ? JSON::stringify($data, JSON_UNESCAPED_UNICODE) : $data ) @@ -189,11 +189,11 @@ protected function _getBaseUrl(Connection $connection): string 'scheme' => $this->_scheme, 'host' => $connection->getHost(), 'port' => $connection->getPort(), - 'path' => ltrim('/', $connection->getPath()), + 'path' => \ltrim('/', $connection->getPath()), ]); } - return rtrim($baseUri, '/'); + return \rtrim($baseUri, '/'); } /** @@ -207,7 +207,7 @@ protected function _getActionPath(Request $request): string { $action = $request->getPath(); if ($action) { - $action = '/'.ltrim($action, '/'); + $action = '/'.\ltrim($action, '/'); } if (!Util::isDateMathEscaped($action)) { @@ -217,7 +217,7 @@ protected function _getActionPath(Request $request): string $query = $request->getQuery(); if (!empty($query)) { - $action .= '?'.http_build_query( + $action .= '?'.\http_build_query( $this->sanityzeQueryStringBool($query) ); } diff --git a/lib/Elastica/Transport/Http.php b/lib/Elastica/Transport/Http.php index ff320e690e..ef7fe03c67 100644 --- a/lib/Elastica/Transport/Http.php +++ b/lib/Elastica/Transport/Http.php @@ -71,42 +71,42 @@ public function exec(Request $request, array $params): Response $query = $request->getQuery(); if (!empty($query)) { - $baseUri .= '?'.http_build_query( + $baseUri .= '?'.\http_build_query( $this->sanityzeQueryStringBool($query) ); } - curl_setopt($conn, CURLOPT_URL, $baseUri); - curl_setopt($conn, CURLOPT_TIMEOUT, $connection->getTimeout()); - curl_setopt($conn, CURLOPT_FORBID_REUSE, 0); + \curl_setopt($conn, CURLOPT_URL, $baseUri); + \curl_setopt($conn, CURLOPT_TIMEOUT, $connection->getTimeout()); + \curl_setopt($conn, CURLOPT_FORBID_REUSE, 0); // Tell ES that we support the compressed responses // An "Accept-Encoding" header containing all supported encoding types is sent // curl will decode the response automatically if the response is encoded - curl_setopt($conn, CURLOPT_ENCODING, ''); + \curl_setopt($conn, CURLOPT_ENCODING, ''); /* @see Connection::setConnectTimeout() */ $connectTimeout = $connection->getConnectTimeout(); if ($connectTimeout > 0) { - curl_setopt($conn, CURLOPT_CONNECTTIMEOUT, $connectTimeout); + \curl_setopt($conn, CURLOPT_CONNECTTIMEOUT, $connectTimeout); } $proxy = $connection->getProxy(); // See: https://github.com/facebook/hhvm/issues/4875 - if (is_null($proxy) && defined('HHVM_VERSION')) { - $proxy = getenv('http_proxy') ?: null; + if (\is_null($proxy) && \defined('HHVM_VERSION')) { + $proxy = \getenv('http_proxy') ?: null; } - if (!is_null($proxy)) { - curl_setopt($conn, CURLOPT_PROXY, $proxy); + if (!\is_null($proxy)) { + \curl_setopt($conn, CURLOPT_PROXY, $proxy); } $username = $connection->getUsername(); $password = $connection->getPassword(); - if (!is_null($username) && !is_null($password)) { - curl_setopt($conn, CURLOPT_HTTPAUTH, CURLAUTH_ANY); - curl_setopt($conn, CURLOPT_USERPWD, "$username:$password"); + if (!\is_null($username) && !\is_null($password)) { + \curl_setopt($conn, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + \curl_setopt($conn, CURLOPT_USERPWD, "$username:$password"); } $this->_setupCurl($conn); @@ -118,7 +118,7 @@ public function exec(Request $request, array $params): Response if (!empty($headersConfig)) { $headers = []; foreach ($headersConfig as $header => $headerValue) { - array_push($headers, $header.': '.$headerValue); + \array_push($headers, $header.': '.$headerValue); } } @@ -131,50 +131,50 @@ public function exec(Request $request, array $params): Response $httpMethod = Request::POST; } - if (is_array($data)) { + if (\is_array($data)) { $content = JSON::stringify($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } else { $content = $data; // Escaping of / not necessary. Causes problems in base64 encoding of files - $content = str_replace('\/', '/', $content); + $content = \str_replace('\/', '/', $content); } - array_push($headers, sprintf('Content-Type: %s', $request->getContentType())); + \array_push($headers, \sprintf('Content-Type: %s', $request->getContentType())); if ($connection->hasCompression()) { // Compress the body of the request ... - curl_setopt($conn, CURLOPT_POSTFIELDS, gzencode($content)); + \curl_setopt($conn, CURLOPT_POSTFIELDS, \gzencode($content)); // ... and tell ES that it is compressed - array_push($headers, 'Content-Encoding: gzip'); + \array_push($headers, 'Content-Encoding: gzip'); } else { - curl_setopt($conn, CURLOPT_POSTFIELDS, $content); + \curl_setopt($conn, CURLOPT_POSTFIELDS, $content); } } else { - curl_setopt($conn, CURLOPT_POSTFIELDS, ''); + \curl_setopt($conn, CURLOPT_POSTFIELDS, ''); } - curl_setopt($conn, CURLOPT_HTTPHEADER, $headers); + \curl_setopt($conn, CURLOPT_HTTPHEADER, $headers); - curl_setopt($conn, CURLOPT_NOBODY, 'HEAD' == $httpMethod); + \curl_setopt($conn, CURLOPT_NOBODY, 'HEAD' == $httpMethod); - curl_setopt($conn, CURLOPT_CUSTOMREQUEST, $httpMethod); + \curl_setopt($conn, CURLOPT_CUSTOMREQUEST, $httpMethod); - $start = microtime(true); + $start = \microtime(true); // cURL opt returntransfer leaks memory, therefore OB instead. - ob_start(); - curl_exec($conn); - $responseString = ob_get_clean(); + \ob_start(); + \curl_exec($conn); + $responseString = \ob_get_clean(); - $end = microtime(true); + $end = \microtime(true); // Checks if error exists - $errorNumber = curl_errno($conn); + $errorNumber = \curl_errno($conn); - $response = new Response($responseString, curl_getinfo($conn, CURLINFO_HTTP_CODE)); + $response = new Response($responseString, \curl_getinfo($conn, CURLINFO_HTTP_CODE)); $response->setQueryTime($end - $start); - $response->setTransferInfo(curl_getinfo($conn)); + $response->setTransferInfo(\curl_getinfo($conn)); if ($connection->hasConfig('bigintConversion')) { $response->setJsonBigintConversion($connection->getConfig('bigintConversion')); } @@ -203,7 +203,7 @@ protected function _setupCurl($curlConnection) { if ($this->getConnection()->hasConfig('curl')) { foreach ($this->getConnection()->getConfig('curl') as $key => $param) { - curl_setopt($curlConnection, $key, $param); + \curl_setopt($curlConnection, $key, $param); } } } @@ -218,7 +218,7 @@ protected function _setupCurl($curlConnection) protected function _getConnection(bool $persistent = true) { if (!$persistent || !self::$_curlConnection) { - self::$_curlConnection = curl_init(); + self::$_curlConnection = \curl_init(); } return self::$_curlConnection; diff --git a/lib/Elastica/Transport/HttpAdapter.php b/lib/Elastica/Transport/HttpAdapter.php index 736e9a0c86..14190acd2b 100644 --- a/lib/Elastica/Transport/HttpAdapter.php +++ b/lib/Elastica/Transport/HttpAdapter.php @@ -63,9 +63,9 @@ public function exec(ElasticaRequest $elasticaRequest, array $params): Response $httpAdapterRequest = $this->_createHttpAdapterRequest($elasticaRequest, $connection); - $start = microtime(true); + $start = \microtime(true); $httpAdapterResponse = $this->httpAdapter->sendRequest($httpAdapterRequest); - $end = microtime(true); + $end = \microtime(true); $elasticaResponse = $this->_createElasticaResponse($httpAdapterResponse); $elasticaResponse->setQueryTime($end - $start); @@ -120,7 +120,7 @@ protected function _createHttpAdapterRequest(ElasticaRequest $elasticaRequest, C $method = ElasticaRequest::POST; } - if (is_array($data)) { + if (\is_array($data)) { $body = JSON::stringify($data, JSON_UNESCAPED_UNICODE); } else { $body = $data; @@ -159,7 +159,7 @@ protected function _getUri(ElasticaRequest $request, Connection $connection): st $query = $request->getQuery(); if (!empty($query)) { - $baseUri .= '?'.http_build_query($query); + $baseUri .= '?'.\http_build_query($query); } return $baseUri; diff --git a/lib/Elastica/Type.php b/lib/Elastica/Type.php index e3eaa451cb..fbd610034a 100644 --- a/lib/Elastica/Type.php +++ b/lib/Elastica/Type.php @@ -125,7 +125,7 @@ public function addObject($object, Document $doc = null) throw new RuntimeException('No serializer defined'); } - $data = call_user_func($this->_serializer, $object); + $data = \call_user_func($this->_serializer, $object); if (!$doc) { $doc = new Document(); } @@ -221,7 +221,7 @@ public function addObjects(array $objects, array $options = []) $docs = []; foreach ($objects as $object) { - $data = call_user_func($this->_serializer, $object); + $data = \call_user_func($this->_serializer, $object); $doc = new Document(); $doc->setData($data); $doc->setType($this->getName()); @@ -319,7 +319,7 @@ public function getMapping() $response = $this->requestEndpoint(new Get()); $data = $response->getData(); - $mapping = array_shift($data); + $mapping = \array_shift($data); if (isset($mapping['mappings'])) { return $mapping['mappings']; } @@ -443,7 +443,7 @@ public function deleteDocuments(array $docs) */ public function deleteById($id, array $options = []) { - if (empty($id) || !trim($id)) { + if (empty($id) || !\trim($id)) { throw new \InvalidArgumentException(); } diff --git a/lib/Elastica/Type/Mapping.php b/lib/Elastica/Type/Mapping.php index ebd52ae3fd..33207c4224 100644 --- a/lib/Elastica/Type/Mapping.php +++ b/lib/Elastica/Type/Mapping.php @@ -225,7 +225,7 @@ public function send(array $query = []): Response */ public static function create($mapping): Mapping { - if (is_array($mapping)) { + if (\is_array($mapping)) { $mappingObject = new self(); $mappingObject->setProperties($mapping); diff --git a/lib/Elastica/Util.php b/lib/Elastica/Util.php index 26f0a98994..761e048926 100644 --- a/lib/Elastica/Util.php +++ b/lib/Elastica/Util.php @@ -28,7 +28,7 @@ class Util public static function isDateMathEscaped($requestUri) { // In practice, the only symbol that really needs to be escaped in URI is '/' => '%2F' - return false !== strpos(strtoupper($requestUri), '%2F'); + return false !== \strpos(\strtoupper($requestUri), '%2F'); } /** @@ -47,29 +47,29 @@ public static function escapeDateMath($requestUri) } // Check if date math if used at all. Find last '>'. E.g. /,log-2011.12.01/log/_refresh - $pos1 = strrpos($requestUri, '>'); + $pos1 = \strrpos($requestUri, '>'); if (false === $pos1) { return $requestUri; } // Find the position up to which we should escape. // Should be next slash '/' after last '>' E.g. /,log-2011.12.01/log/_refresh - $pos2 = strpos($requestUri, '/', $pos1); - $pos2 = false !== $pos2 ? $pos2 : strlen($requestUri); + $pos2 = \strpos($requestUri, '/', $pos1); + $pos2 = false !== $pos2 ? $pos2 : \strlen($requestUri); // Cut out the bit we need to escape: /,log-2011.12.01 - $uriSegment = substr($requestUri, 0, $pos2); + $uriSegment = \substr($requestUri, 0, $pos2); // Escape using character map - $escapedUriSegment = str_replace(static::$dateMathSymbols, static::$escapedDateMathSymbols, $uriSegment); + $escapedUriSegment = \str_replace(static::$dateMathSymbols, static::$escapedDateMathSymbols, $uriSegment); // '\\{' and '\\}' should not be escaped - if (false !== strpos($uriSegment, '\\\\')) { - $escapedUriSegment = str_replace(['\\\\%7B', '\\\\%7D'], ['\\\\{', '\\\\}'], $escapedUriSegment); + if (false !== \strpos($uriSegment, '\\\\')) { + $escapedUriSegment = \str_replace(['\\\\%7B', '\\\\%7D'], ['\\\\{', '\\\\}'], $escapedUriSegment); } // Replace part of the string. E.g. /%3Clog-%7Bnow%2Fd%7D%3E%2Clog-2011.12.01/log/_refresh - return substr_replace($requestUri, $escapedUriSegment, 0, $pos2); + return \substr_replace($requestUri, $escapedUriSegment, 0, $pos2); } /** @@ -110,7 +110,7 @@ public static function escapeTerm($term) $escapableChars = ['\\', '+', '-', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '/']; foreach ($escapableChars as $char) { - $result = str_replace($char, '\\'.$char, $result); + $result = \str_replace($char, '\\'.$char, $result); } // < and > cannot be escaped, so they should be removed @@ -118,7 +118,7 @@ public static function escapeTerm($term) $nonEscapableChars = ['<', '>']; foreach ($nonEscapableChars as $char) { - $result = str_replace($char, '', $result); + $result = \str_replace($char, '', $result); } return $result; @@ -137,7 +137,7 @@ public static function escapeTerm($term) public static function replaceBooleanWords($term) { $replacementMap = [' AND ' => ' && ', ' OR ' => ' || ', ' NOT ' => ' !']; - $result = strtr($term, $replacementMap); + $result = \strtr($term, $replacementMap); return $result; } @@ -153,7 +153,7 @@ public static function replaceBooleanWords($term) */ public static function toCamelCase($string) { - return str_replace(' ', '', ucwords(str_replace('_', ' ', $string))); + return \str_replace(' ', '', \ucwords(\str_replace('_', ' ', $string))); } /** @@ -167,9 +167,9 @@ public static function toCamelCase($string) */ public static function toSnakeCase($string) { - $string = preg_replace('/([A-Z])/', '_$1', $string); + $string = \preg_replace('/([A-Z])/', '_$1', $string); - return strtolower(substr($string, 1)); + return \strtolower(\substr($string, 1)); } /** @@ -183,12 +183,12 @@ public static function toSnakeCase($string) */ public static function convertDate($date) { - if (is_int($date)) { + if (\is_int($date)) { $timestamp = $date; } else { - $timestamp = strtotime($date); + $timestamp = \strtotime($date); } - $string = date('Y-m-d\TH:i:s\Z', $timestamp); + $string = \date('Y-m-d\TH:i:s\Z', $timestamp); return $string; } @@ -221,13 +221,13 @@ public static function convertDateTimeObject(\DateTime $dateTime, $includeTimezo */ public static function getParamName($class) { - if (is_object($class)) { - $class = get_class($class); + if (\is_object($class)) { + $class = \get_class($class); } - $parts = explode('\\', $class); - $last = array_pop($parts); - $last = preg_replace('/Query$/', '', $last); // for BoolQuery + $parts = \explode('\\', $class); + $last = \array_pop($parts); + $last = \preg_replace('/Query$/', '', $last); // for BoolQuery return self::toSnakeCase($last); } @@ -241,13 +241,13 @@ public static function getParamName($class) */ public static function convertRequestToCurlCommand(Request $request) { - $message = 'curl -X'.strtoupper($request->getMethod()).' '; + $message = 'curl -X'.\strtoupper($request->getMethod()).' '; $message .= '\'http://'.$request->getConnection()->getHost().':'.$request->getConnection()->getPort().'/'; $message .= $request->getPath(); $query = $request->getQuery(); if (!empty($query)) { - $message .= '?'.http_build_query($query); + $message .= '?'.\http_build_query($query); } $message .= '\''; diff --git a/test/Elastica/Aggregation/ChildrenTest.php b/test/Elastica/Aggregation/ChildrenTest.php index 5369398f39..00699b346c 100644 --- a/test/Elastica/Aggregation/ChildrenTest.php +++ b/test/Elastica/Aggregation/ChildrenTest.php @@ -17,8 +17,8 @@ protected function _getIndexForTest(): Index $index = $client->getIndex('testaggregationchildren'); $index->create(['index' => ['number_of_shards' => 2, 'number_of_replicas' => 1]], true); - $type = $index->getType(strtolower( - 'typechildren'.uniqid() + $type = $index->getType(\strtolower( + 'typechildren'.\uniqid() )); $mapping = new Mapping(); diff --git a/test/Elastica/Aggregation/DateRangeTest.php b/test/Elastica/Aggregation/DateRangeTest.php index 4b761b8697..0ce3c4186d 100644 --- a/test/Elastica/Aggregation/DateRangeTest.php +++ b/test/Elastica/Aggregation/DateRangeTest.php @@ -45,9 +45,9 @@ public function testDateRangeAggregation() $results = $this->_getIndexForTest()->search($query)->getAggregation('date'); foreach ($results['buckets'] as $bucket) { - if (array_key_exists('to', $bucket)) { + if (\array_key_exists('to', $bucket)) { $this->assertEquals(1, $bucket['doc_count']); - } elseif (array_key_exists('from', $bucket)) { + } elseif (\array_key_exists('from', $bucket)) { $this->assertEquals(2, $bucket['doc_count']); } } diff --git a/test/Elastica/Aggregation/IpRangeTest.php b/test/Elastica/Aggregation/IpRangeTest.php index 61ab1a1cde..9ae1ce16cc 100644 --- a/test/Elastica/Aggregation/IpRangeTest.php +++ b/test/Elastica/Aggregation/IpRangeTest.php @@ -47,7 +47,7 @@ public function testIpRangeAggregation() $results = $this->_getIndexForTest()->search($query)->getAggregation('ip'); foreach ($results['buckets'] as $bucket) { - if (array_key_exists('key', $bucket) && $bucket['key'] == $cidrRange) { + if (\array_key_exists('key', $bucket) && $bucket['key'] == $cidrRange) { // the CIDR mask $this->assertEquals(3, $bucket['doc_count']); } else { diff --git a/test/Elastica/Aggregation/SignificantTermsTest.php b/test/Elastica/Aggregation/SignificantTermsTest.php index 8fbccce3d8..aaef71f3e0 100644 --- a/test/Elastica/Aggregation/SignificantTermsTest.php +++ b/test/Elastica/Aggregation/SignificantTermsTest.php @@ -25,7 +25,7 @@ protected function _getIndexForTest(): Index $docs = []; for ($i = 0; $i < 250; ++$i) { - $docs[] = new Document($i, ['color' => $colors[$i % count($colors)], 'temperature' => $temperatures[$i % count($temperatures)]]); + $docs[] = new Document($i, ['color' => $colors[$i % \count($colors)], 'temperature' => $temperatures[$i % \count($temperatures)]]); } $index->getType('_doc')->addDocuments($docs); $index->refresh(); diff --git a/test/Elastica/Base.php b/test/Elastica/Base.php index 30c768b736..92d58aee13 100644 --- a/test/Elastica/Base.php +++ b/test/Elastica/Base.php @@ -14,25 +14,25 @@ class Base extends TestCase { protected static function hideDeprecated() { - error_reporting(error_reporting() & ~E_USER_DEPRECATED); + \error_reporting(\error_reporting() & ~E_USER_DEPRECATED); } protected static function showDeprecated() { - error_reporting(error_reporting() | E_USER_DEPRECATED); + \error_reporting(\error_reporting() | E_USER_DEPRECATED); } protected function assertFileDeprecated($file, $deprecationMessage) { - $content = file_get_contents($file); - $content = preg_replace('/^(abstract class|class) ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+)/m', '${1} ${2}'.uniqid(), $content); - $newFile = tempnam(sys_get_temp_dir(), 'elastica-test-'); - file_put_contents($newFile, $content); + $content = \file_get_contents($file); + $content = \preg_replace('/^(abstract class|class) ([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+)/m', '${1} ${2}'.\uniqid(), $content); + $newFile = \tempnam(\sys_get_temp_dir(), 'elastica-test-'); + \file_put_contents($newFile, $content); $errorsCollector = $this->startCollectErrors(); require $newFile; - unlink($newFile); + \unlink($newFile); $this->finishCollectErrors(); $errorsCollector->assertOnlyOneDeprecatedError($deprecationMessage); @@ -45,8 +45,8 @@ protected function startCollectErrors() { $errorsCollector = new ErrorsCollector($this); - set_error_handler(function () use ($errorsCollector) { - $errorsCollector->add(func_get_args()); + \set_error_handler(function () use ($errorsCollector) { + $errorsCollector->add(\func_get_args()); }); return $errorsCollector; @@ -54,7 +54,7 @@ protected function startCollectErrors() protected function finishCollectErrors() { - restore_error_handler(); + \restore_error_handler(); } /** @@ -71,7 +71,7 @@ protected function _getClient(array $params = [], $callback = null, LoggerInterf 'port' => $this->_getPort(), ]; - $config = array_merge($config, $params); + $config = \array_merge($config, $params); return new Client($config, $callback, $logger); } @@ -81,7 +81,7 @@ protected function _getClient(array $params = [], $callback = null, LoggerInterf */ protected function _getHost() { - return getenv('ES_HOST') ?: Connection::DEFAULT_HOST; + return \getenv('ES_HOST') ?: Connection::DEFAULT_HOST; } /** @@ -89,7 +89,7 @@ protected function _getHost() */ protected function _getPort() { - return getenv('ES_PORT') ?: Connection::DEFAULT_PORT; + return \getenv('ES_PORT') ?: Connection::DEFAULT_PORT; } /** @@ -97,7 +97,7 @@ protected function _getPort() */ protected function _getProxyUrl() { - $proxyHost = getenv('PROXY_HOST') ?: Connection::DEFAULT_HOST; + $proxyHost = \getenv('PROXY_HOST') ?: Connection::DEFAULT_HOST; return 'http://'.$proxyHost.':12345'; } @@ -107,7 +107,7 @@ protected function _getProxyUrl() */ protected function _getProxyUrl403() { - $proxyHost = getenv('PROXY_HOST') ?: Connection::DEFAULT_HOST; + $proxyHost = \getenv('PROXY_HOST') ?: Connection::DEFAULT_HOST; return 'http://'.$proxyHost.':12346'; } @@ -121,14 +121,14 @@ protected function _getProxyUrl403() */ protected function _createIndex($name = null, $delete = true, $shards = 1) { - if (is_null($name)) { - $name = preg_replace('/[^a-z]/i', '', strtolower(get_called_class()).uniqid()); + if (\is_null($name)) { + $name = \preg_replace('/[^a-z]/i', '', \strtolower(\get_called_class()).\uniqid()); } $client = $this->_getClient(); $index = $client->getIndex('elastica_'.$name); - if ('elasticsearch' === getenv('ES_HOST')) { + if ('elasticsearch' === \getenv('ES_HOST')) { $index->create(['index' => ['number_of_shards' => $shards, 'number_of_replicas' => 1]], $delete); } @@ -168,7 +168,7 @@ protected function _getVersion() { $data = $this->_getClient()->request('/')->getData(); - return substr($data['version']['number'], 0, 1); + return \substr($data['version']['number'], 0, 1); } protected function _checkVersion($version) @@ -176,14 +176,14 @@ protected function _checkVersion($version) $data = $this->_getClient()->request('/')->getData(); $installedVersion = $data['version']['number']; - if (version_compare($installedVersion, $version) < 0) { + if (\version_compare($installedVersion, $version) < 0) { $this->markTestSkipped('Test require '.$version.'+ version of Elasticsearch'); } } protected function _checkConnection($host, $port) { - $fp = @pfsockopen($host, $port); + $fp = @\pfsockopen($host, $port); if (!$fp) { $this->markTestSkipped('Connection to '.$host.':'.$port.' failed'); @@ -226,22 +226,22 @@ protected function tearDown() protected function _isUnitGroup() { - $groups = TestUtil::getGroups(get_class($this), $this->getName(false)); + $groups = TestUtil::getGroups(\get_class($this), $this->getName(false)); - return in_array('unit', $groups); + return \in_array('unit', $groups); } protected function _isFunctionalGroup() { - $groups = TestUtil::getGroups(get_class($this), $this->getName(false)); + $groups = TestUtil::getGroups(\get_class($this), $this->getName(false)); - return in_array('functional', $groups); + return \in_array('functional', $groups); } protected function _isBenchmarkGroup() { - $groups = TestUtil::getGroups(get_class($this), $this->getName(false)); + $groups = TestUtil::getGroups(\get_class($this), $this->getName(false)); - return in_array('benchmark', $groups); + return \in_array('benchmark', $groups); } } diff --git a/test/Elastica/BasePipeline.php b/test/Elastica/BasePipeline.php index 45695bce2d..4ba33a0350 100644 --- a/test/Elastica/BasePipeline.php +++ b/test/Elastica/BasePipeline.php @@ -17,8 +17,8 @@ class BasePipeline extends BaseTest */ protected function _createPipeline(string $id = null, string $description = '') { - if (is_null($id)) { - $id = preg_replace('/[^a-z]/i', '', strtolower(get_called_class()).uniqid()); + if (\is_null($id)) { + $id = \preg_replace('/[^a-z]/i', '', \strtolower(\get_called_class()).\uniqid()); } $pipeline = new Pipeline($this->_getClient()); diff --git a/test/Elastica/BulkTest.php b/test/Elastica/BulkTest.php index 1477befebe..2b24642a31 100644 --- a/test/Elastica/BulkTest.php +++ b/test/Elastica/BulkTest.php @@ -88,8 +88,8 @@ public function testSend() {"name":"The Thing"} '; - $expected = str_replace(PHP_EOL, "\n", $expected); - $this->assertEquals($expected, (string) str_replace(PHP_EOL, "\n", (string) $bulk)); + $expected = \str_replace(PHP_EOL, "\n", $expected); + $this->assertEquals($expected, (string) \str_replace(PHP_EOL, "\n", (string) $bulk)); $response = $bulk->send(); @@ -401,7 +401,7 @@ public function testRawDocumentDataRequest() {"index":{}} {"name":"The Human Torch"} '; - $expectedJson = str_replace(PHP_EOL, "\n", $expectedJson); + $expectedJson = \str_replace(PHP_EOL, "\n", $expectedJson); $this->assertEquals($expectedJson, $bulk->toString()); $response = $bulk->send(); @@ -564,7 +564,7 @@ public function testUpsert() $doc2 = $type->createDocument(2, ['name' => 'Beckenbauer']); $doc3 = $type->createDocument(3, ['name' => 'Baggio']); $doc4 = $type->createDocument(4, ['name' => 'Cruyff']); - $documents = array_map(function ($d) { + $documents = \array_map(function ($d) { $d->setDocAsUpsert(true); return $d; @@ -684,13 +684,13 @@ public function testMemoryUsage() 'text3' => 'random or not random?', ]; - $startMemory = memory_get_usage(); + $startMemory = \memory_get_usage(); for ($n = 1; $n < 10; ++$n) { $docs = []; for ($i = 1; $i <= 3000; ++$i) { - $docs[] = new Document(uniqid(), $data); + $docs[] = new Document(\uniqid(), $data); } $type->addDocuments($docs); @@ -699,7 +699,7 @@ public function testMemoryUsage() unset($docs); - $endMemory = memory_get_usage(); + $endMemory = \memory_get_usage(); $this->markTestIncomplete('Failed asserting that 2.2414096568375803 is less than 1.3.'); $this->assertLessThan(1.3, $endMemory / $startMemory); diff --git a/test/Elastica/ClientTest.php b/test/Elastica/ClientTest.php index 269d56514a..20a103b951 100644 --- a/test/Elastica/ClientTest.php +++ b/test/Elastica/ClientTest.php @@ -72,7 +72,7 @@ public function testGetVersion() { $client = $this->_getClient(); $this->assertNotEmpty($client->getVersion()); - $this->assertTrue(version_compare($client->getVersion(), $_SERVER['ELASTICSEARCH_VERSION'], '>=')); + $this->assertTrue(\version_compare($client->getVersion(), $_SERVER['ELASTICSEARCH_VERSION'], '>=')); } /** @@ -1432,7 +1432,7 @@ public function testEndpointParamsRequest() $this->assertEquals( ['_doc'], - array_keys($response->getData()['indices'][$index->getName()]['total']['indexing']['types']) + \array_keys($response->getData()['indices'][$index->getName()]['total']['indexing']['types']) ); } diff --git a/test/Elastica/Cluster/SettingsTest.php b/test/Elastica/Cluster/SettingsTest.php index 2e1b7ab115..1e20f3c5e9 100644 --- a/test/Elastica/Cluster/SettingsTest.php +++ b/test/Elastica/Cluster/SettingsTest.php @@ -16,7 +16,7 @@ public function testSetTransient() { $index = $this->_createIndex(); - if (count($index->getClient()->getCluster()->getNodes()) < 2) { + if (\count($index->getClient()->getCluster()->getNodes()) < 2) { $this->markTestSkipped('At least two master nodes have to be running for this test'); } @@ -38,7 +38,7 @@ public function testSetPersistent() { $index = $this->_createIndex(); - if (count($index->getClient()->getCluster()->getNodes()) < 2) { + if (\count($index->getClient()->getCluster()->getNodes()) < 2) { $this->markTestSkipped('At least two master nodes have to be running for this test'); } diff --git a/test/Elastica/ClusterTest.php b/test/Elastica/ClusterTest.php index ffbb437d67..f218150b56 100644 --- a/test/Elastica/ClusterTest.php +++ b/test/Elastica/ClusterTest.php @@ -28,7 +28,7 @@ public function testGetNodeNames() $rawNodeNames[] = $rawNode['name']; } - $this->assertEquals(asort($rawNodeNames), asort($cluster->getNodeNames())); + $this->assertEquals(\asort($rawNodeNames), \asort($cluster->getNodeNames())); } /** @@ -42,7 +42,7 @@ public function testGetNodes() $nodes = $cluster->getNodes(); $this->assertContainsOnlyInstancesOf(Node::class, $nodes); - $this->assertGreaterThan(0, count($nodes)); + $this->assertGreaterThan(0, \count($nodes)); } /** diff --git a/test/Elastica/Connection/Strategy/RoundRobinTest.php b/test/Elastica/Connection/Strategy/RoundRobinTest.php index 1eeac98be3..f9f8c788b0 100644 --- a/test/Elastica/Connection/Strategy/RoundRobinTest.php +++ b/test/Elastica/Connection/Strategy/RoundRobinTest.php @@ -87,7 +87,7 @@ public function testWithOneFailConnection() $this->_checkStrategy($client); - $this->assertLessThan(count($connections), $count); + $this->assertLessThan(\count($connections), $count); } /** @@ -112,7 +112,7 @@ public function testWithNoValidConnection() $client->request('_aliases'); $this->fail('Should throw exception as no connection valid'); } catch (ConnectionException $e) { - $this->assertEquals(count($connections), $count); + $this->assertEquals(\count($connections), $count); $this->_checkStrategy($client); } } diff --git a/test/Elastica/Connection/Strategy/SimpleTest.php b/test/Elastica/Connection/Strategy/SimpleTest.php index 5ec6fa5686..a3a52fa2dd 100644 --- a/test/Elastica/Connection/Strategy/SimpleTest.php +++ b/test/Elastica/Connection/Strategy/SimpleTest.php @@ -74,7 +74,7 @@ public function testWithOneFailConnection() $this->_checkStrategy($client); - $this->assertLessThan(count($connections), $count); + $this->assertLessThan(\count($connections), $count); } /** @@ -99,7 +99,7 @@ public function testWithNoValidConnection() $client->request('_aliases'); $this->fail('Should throw exception as no connection valid'); } catch (ConnectionException $e) { - $this->assertEquals(count($connections), $count); + $this->assertEquals(\count($connections), $count); } } diff --git a/test/Elastica/Connection/Strategy/StrategyFactoryTest.php b/test/Elastica/Connection/Strategy/StrategyFactoryTest.php index 2872ed6961..019cbdd088 100644 --- a/test/Elastica/Connection/Strategy/StrategyFactoryTest.php +++ b/test/Elastica/Connection/Strategy/StrategyFactoryTest.php @@ -77,8 +77,8 @@ public function testFailCreate() public function testNoCollisionWithGlobalNamespace() { // create collision - if (!class_exists('Simple')) { - class_alias('Elastica\Util', 'Simple'); + if (!\class_exists('Simple')) { + \class_alias('Elastica\Util', 'Simple'); } $strategy = StrategyFactory::create('Simple'); $this->assertInstanceOf(Simple::class, $strategy); diff --git a/test/Elastica/DocumentTest.php b/test/Elastica/DocumentTest.php index 8e7cf79b88..9871d893c3 100644 --- a/test/Elastica/DocumentTest.php +++ b/test/Elastica/DocumentTest.php @@ -15,7 +15,7 @@ class DocumentTest extends BaseTest public function testAddFile() { $fileName = '/dev/null'; - if (!file_exists($fileName)) { + if (!\file_exists($fileName)) { $this->markTestSkipped("File {$fileName} does not exist."); } $doc = new Document(); diff --git a/test/Elastica/ErrorsCollector.php b/test/Elastica/ErrorsCollector.php index eeb942a460..39a586d3a5 100644 --- a/test/Elastica/ErrorsCollector.php +++ b/test/Elastica/ErrorsCollector.php @@ -30,7 +30,7 @@ public function add($error) public function getCount() { - return count($this->errors); + return \count($this->errors); } public function assertOnlyOneDeprecatedError($deprecationMessage) @@ -42,8 +42,8 @@ public function assertOnlyOneDeprecatedError($deprecationMessage) public function assertOnlyDeprecatedErrors(array $deprecationMessages) { - $this->testCase->assertSame(count($deprecationMessages), $this->getCount()); - $this->testCase->assertSame(count($deprecationMessages), $this->getDeprecatedCount()); + $this->testCase->assertSame(\count($deprecationMessages), $this->getCount()); + $this->testCase->assertSame(\count($deprecationMessages), $this->getDeprecatedCount()); foreach ($deprecationMessages as $index => $message) { $this->testCase->assertSame($message, $this->getMessage($index)); diff --git a/test/Elastica/Exception/AbstractExceptionTest.php b/test/Elastica/Exception/AbstractExceptionTest.php index e9514ddbfb..e57372d3ff 100644 --- a/test/Elastica/Exception/AbstractExceptionTest.php +++ b/test/Elastica/Exception/AbstractExceptionTest.php @@ -12,10 +12,10 @@ protected function _getExceptionClass() $reflection = new \ReflectionObject($this); // Elastica\Test\Exception\RuntimeExceptionTest => Elastica\Exception\RuntimeExceptionTest - $name = preg_replace('/^Elastica\\\\Test/', 'Elastica', $reflection->getName()); + $name = \preg_replace('/^Elastica\\\\Test/', 'Elastica', $reflection->getName()); // Elastica\Exception\RuntimeExceptionTest => Elastica\Exception\RuntimeException - $name = preg_replace('/Test$/', '', $name); + $name = \preg_replace('/Test$/', '', $name); return $name; } diff --git a/test/Elastica/Exception/Connection/GuzzleExceptionTest.php b/test/Elastica/Exception/Connection/GuzzleExceptionTest.php index 643f1d5cc8..c4c15816ce 100644 --- a/test/Elastica/Exception/Connection/GuzzleExceptionTest.php +++ b/test/Elastica/Exception/Connection/GuzzleExceptionTest.php @@ -8,7 +8,7 @@ class GuzzleExceptionTest extends AbstractExceptionTest { public static function setUpBeforeClass() { - if (!class_exists('GuzzleHttp\\Client')) { + if (!\class_exists('GuzzleHttp\\Client')) { self::markTestSkipped('guzzlehttp/guzzle package should be installed to run guzzle transport tests'); } } diff --git a/test/Elastica/Exception/PartialShardFailureExceptionTest.php b/test/Elastica/Exception/PartialShardFailureExceptionTest.php index 3c43bfe5e8..09fce26d8b 100644 --- a/test/Elastica/Exception/PartialShardFailureExceptionTest.php +++ b/test/Elastica/Exception/PartialShardFailureExceptionTest.php @@ -55,7 +55,7 @@ public function testPartialFailure() $message = JSON::parse($e->getMessage()); $this->assertArrayHasKey('failures', $message, 'Failures are absent'); - $this->assertGreaterThan(0, count($message['failures']), 'Failures are empty'); + $this->assertGreaterThan(0, \count($message['failures']), 'Failures are empty'); } } } diff --git a/test/Elastica/LogTest.php b/test/Elastica/LogTest.php index 46434d3f64..bc854f695b 100644 --- a/test/Elastica/LogTest.php +++ b/test/Elastica/LogTest.php @@ -13,7 +13,7 @@ class LogTest extends BaseTest public static function setUpBeforeClass() { - if (!class_exists('Psr\Log\AbstractLogger')) { + if (!\class_exists('Psr\Log\AbstractLogger')) { self::markTestSkipped('The Psr extension is not available.'); } } @@ -75,7 +75,7 @@ public function testGetLastMessage() $log->log(LogLevel::DEBUG, $this->_message, $this->_context); $this->_context['error_message'] = $this->_message; - $message = json_encode($this->_context); + $message = \json_encode($this->_context); $this->assertEquals($message, $log->getLastMessage()); } @@ -89,14 +89,14 @@ public function testGetLastMessage2() $log = new Log($client); // Set log path temp path as otherwise test fails with output - $errorLog = ini_get('error_log'); - ini_set('error_log', sys_get_temp_dir().DIRECTORY_SEPARATOR.'php.log'); + $errorLog = \ini_get('error_log'); + \ini_set('error_log', \sys_get_temp_dir().DIRECTORY_SEPARATOR.'php.log'); $this->_context['error_message'] = $this->_message; - $message = json_encode($this->_context); + $message = \json_encode($this->_context); $log->log(LogLevel::DEBUG, $this->_message, $this->_context); - ini_set('error_log', $errorLog); + \ini_set('error_log', $errorLog); $this->assertEquals($message, $log->getLastMessage()); } @@ -192,6 +192,6 @@ private function getMessage() { $this->_context['error_message'] = $this->_message; - return json_encode($this->_context); + return \json_encode($this->_context); } } diff --git a/test/Elastica/Node/InfoTest.php b/test/Elastica/Node/InfoTest.php index d82df48b94..a3f95810eb 100644 --- a/test/Elastica/Node/InfoTest.php +++ b/test/Elastica/Node/InfoTest.php @@ -15,7 +15,7 @@ public function testGet() { $client = $this->_getClient(); $names = $client->getCluster()->getNodeNames(); - $name = reset($names); + $name = \reset($names); $node = new Node($name, $client); $info = new NodeInfo($node); diff --git a/test/Elastica/NodeTest.php b/test/Elastica/NodeTest.php index fda95f589a..1add01eca3 100644 --- a/test/Elastica/NodeTest.php +++ b/test/Elastica/NodeTest.php @@ -16,7 +16,7 @@ public function testCreateNode() { $client = $this->_getClient(); $names = $client->getCluster()->getNodeNames(); - $name = reset($names); + $name = \reset($names); $node = new Node($name, $client); $this->assertInstanceOf(Node::class, $node); @@ -29,7 +29,7 @@ public function testGetInfo() { $client = $this->_getClient(); $names = $client->getCluster()->getNodeNames(); - $name = reset($names); + $name = \reset($names); $node = new Node($name, $client); @@ -45,7 +45,7 @@ public function testGetStats() { $client = $this->_getClient(); $names = $client->getCluster()->getNodeNames(); - $name = reset($names); + $name = \reset($names); $node = new Node($name, $client); diff --git a/test/Elastica/Processor/JsonTest.php b/test/Elastica/Processor/JsonTest.php index 3121cffe07..f0531bb921 100644 --- a/test/Elastica/Processor/JsonTest.php +++ b/test/Elastica/Processor/JsonTest.php @@ -61,7 +61,7 @@ public function testJsonField() $type = $index->getType('_doc'); // Add document to normal index - $doc1 = new Document(null, ['name' => json_encode(['foo' => 2000])]); + $doc1 = new Document(null, ['name' => \json_encode(['foo' => 2000])]); $bulk = new Bulk($index->getClient()); $bulk->setIndex($index); diff --git a/test/Elastica/Query/BoolQueryTest.php b/test/Elastica/Query/BoolQueryTest.php index bc0ab7267d..0a8b2c34d4 100644 --- a/test/Elastica/Query/BoolQueryTest.php +++ b/test/Elastica/Query/BoolQueryTest.php @@ -79,7 +79,7 @@ public function testToArrayStructure() $boolQuery->addShould($term1)->addShould($term2); $jsonString = '{"bool":{"should":[{"term":{"interests":84}},{"term":{"interests":92}}]}}'; - $this->assertEquals($jsonString, json_encode($boolQuery->toArray())); + $this->assertEquals($jsonString, \json_encode($boolQuery->toArray())); } /** diff --git a/test/Elastica/Query/InnerHitsTest.php b/test/Elastica/Query/InnerHitsTest.php index 9bed412c83..def26006b9 100644 --- a/test/Elastica/Query/InnerHitsTest.php +++ b/test/Elastica/Query/InnerHitsTest.php @@ -343,7 +343,7 @@ public function testInnerHitsNested() $innerHits = new InnerHits(); $results = $this->getNestedQuery($queryString, $innerHits); - $firstResult = current($results->getResults()); + $firstResult = \current($results->getResults()); $innerHitsResults = $firstResult->getInnerHits(); @@ -360,7 +360,7 @@ public function testInnerHitsParentChildren() $innerHits = new InnerHits(); $results = $this->getParentChildQuery($queryString, $innerHits); - $firstResult = current($results->getResults()); + $firstResult = \current($results->getResults()); $innerHits = $firstResult->getInnerHits(); @@ -406,13 +406,13 @@ public function testInnerHitsWithOffset() $innerHits->setFrom(1); $results = $this->getParentChildQuery($queryString, $innerHits); - $firstResult = current($results->getResults()); + $firstResult = \current($results->getResults()); $innerHits = $firstResult->getInnerHits(); $responses = $innerHits['answers']['hits']['hits']; - $this->assertEquals(count($responses), 1); + $this->assertEquals(\count($responses), 1); $this->assertEquals(7, $responses[0]['_id']); } @@ -426,7 +426,7 @@ public function testInnerHitsWithSort() $innerHits->setSort(['answer' => 'asc']); $results = $this->getParentChildQuery($queryString, $innerHits); - $firstResult = current($results->getResults()); + $firstResult = \current($results->getResults()); $innerHits = $firstResult->getInnerHits(); diff --git a/test/Elastica/Query/QueryStringTest.php b/test/Elastica/Query/QueryStringTest.php index de59c1cb9a..a67e08155c 100644 --- a/test/Elastica/Query/QueryStringTest.php +++ b/test/Elastica/Query/QueryStringTest.php @@ -14,7 +14,7 @@ class QueryStringTest extends BaseTest */ public function testSearchMultipleFields() { - $str = md5(rand()); + $str = \md5(\rand()); $query = new QueryString($str); $expected = [ @@ -24,9 +24,9 @@ public function testSearchMultipleFields() $this->assertEquals(['query_string' => $expected], $query->toArray()); $fields = []; - $max = rand() % 10 + 1; + $max = \rand() % 10 + 1; for ($i = 0; $i < $max; ++$i) { - $fields[] = md5(rand()); + $fields[] = \md5(\rand()); } $query->setFields($fields); diff --git a/test/Elastica/Query/SpanTermTest.php b/test/Elastica/Query/SpanTermTest.php index dba4155af0..b9cdd27fcc 100644 --- a/test/Elastica/Query/SpanTermTest.php +++ b/test/Elastica/Query/SpanTermTest.php @@ -48,7 +48,7 @@ public function testSpanTerm() $query = new SpanTerm([$field => $value]); $resultSet = $type->search($query); $results = $resultSet->getResults(); - $hitData = reset($results)->getData(); + $hitData = \reset($results)->getData(); $this->assertEquals($docHitData, $hitData); } diff --git a/test/Elastica/QueryBuilder/DSL/AbstractDSLTest.php b/test/Elastica/QueryBuilder/DSL/AbstractDSLTest.php index 74fcc00894..12a54f57ca 100644 --- a/test/Elastica/QueryBuilder/DSL/AbstractDSLTest.php +++ b/test/Elastica/QueryBuilder/DSL/AbstractDSLTest.php @@ -17,16 +17,16 @@ abstract class AbstractDSLTest extends BaseTest protected function _assertImplemented(DSL $dsl, string $methodName, string $className, array $arguments) { // Check method existence - $this->assertTrue(method_exists($dsl, $methodName)); + $this->assertTrue(\method_exists($dsl, $methodName)); // Check returned value - $return = call_user_func_array([$dsl, $methodName], $arguments); - $this->assertTrue(class_exists($className), 'Class not exists but NotImplementedException is not thrown'); + $return = \call_user_func_array([$dsl, $methodName], $arguments); + $this->assertTrue(\class_exists($className), 'Class not exists but NotImplementedException is not thrown'); $this->assertInstanceOf($className, $return); // Check method signature $class = new \ReflectionClass($className); - $method = new \ReflectionMethod(get_class($dsl), $methodName); + $method = new \ReflectionMethod(\get_class($dsl), $methodName); if (!$class->hasMethod('__construct')) { $this->assertEmpty($method->getParameters(), 'Constructor is not defined, but method has some parameters'); } else { @@ -42,7 +42,7 @@ protected function _assertImplemented(DSL $dsl, string $methodName, string $clas protected function _assertNotImplemented(DSL $dsl, string $methodName, array $arguments) { try { - call_user_func([$dsl, $methodName], $arguments); + \call_user_func([$dsl, $methodName], $arguments); $this->fail('NotImplementedException is not thrown'); } catch (NotImplementedException $ex) { // expected @@ -55,7 +55,7 @@ protected function _assertNotImplemented(DSL $dsl, string $methodName, array $ar */ protected function _assertParametersEquals(array $left, array $right) { - $countLeft = count($left); + $countLeft = \count($left); $this->assertCount($countLeft, $right, 'Parameters count mismatch'); for ($i = 0; $i < $countLeft; ++$i) { diff --git a/test/Elastica/QueryBuilder/VersionTest.php b/test/Elastica/QueryBuilder/VersionTest.php index 7e479a121d..8482f132ee 100644 --- a/test/Elastica/QueryBuilder/VersionTest.php +++ b/test/Elastica/QueryBuilder/VersionTest.php @@ -33,22 +33,22 @@ private function assertVersions(Version $version, array $dsl) { foreach ($version->getQueries() as $query) { $this->assertTrue( - method_exists($dsl[0], $query), - 'query "'.$query.'" in '.get_class($version).' must be defined in '.get_class($dsl[0]) + \method_exists($dsl[0], $query), + 'query "'.$query.'" in '.\get_class($version).' must be defined in '.\get_class($dsl[0]) ); } foreach ($version->getAggregations() as $aggregation) { $this->assertTrue( - method_exists($dsl[1], $aggregation), - 'aggregation "'.$aggregation.'" in '.get_class($version).' must be defined in '.get_class($dsl[2]) + \method_exists($dsl[1], $aggregation), + 'aggregation "'.$aggregation.'" in '.\get_class($version).' must be defined in '.\get_class($dsl[2]) ); } foreach ($version->getSuggesters() as $suggester) { $this->assertTrue( - method_exists($dsl[2], $suggester), - 'suggester "'.$suggester.'" in '.get_class($version).' must be defined in '.get_class($dsl[2]) + \method_exists($dsl[2], $suggester), + 'suggester "'.$suggester.'" in '.\get_class($version).' must be defined in '.\get_class($dsl[2]) ); } } diff --git a/test/Elastica/ReindexTest.php b/test/Elastica/ReindexTest.php index 200a2060aa..e800baa33a 100644 --- a/test/Elastica/ReindexTest.php +++ b/test/Elastica/ReindexTest.php @@ -78,7 +78,7 @@ public function testReindexOpTypeOptionWithProceedSetOnConflicts() $docs1 = $this->_addDocs($type1, 10); - $subDocs1 = array_splice($docs1, 0, 5); + $subDocs1 = \array_splice($docs1, 0, 5); $newIndex = $this->_createIndex('idx2', true, 2); $newIndex->addDocuments($subDocs1); diff --git a/test/Elastica/ResponseTest.php b/test/Elastica/ResponseTest.php index 171aa27f2b..9f68c445d1 100644 --- a/test/Elastica/ResponseTest.php +++ b/test/Elastica/ResponseTest.php @@ -85,7 +85,7 @@ public function testIsOkMultiple() */ public function testIsOkBulkWithErrorsField() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'took' => 213, 'errors' => false, 'items' => [ @@ -102,7 +102,7 @@ public function testIsOkBulkWithErrorsField() */ public function testIsNotOkBulkWithErrorsField() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'took' => 213, 'errors' => true, 'items' => [ @@ -119,7 +119,7 @@ public function testIsNotOkBulkWithErrorsField() */ public function testIsOkBulkItemsWithOkField() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'took' => 213, 'items' => [ ['index' => ['_index' => 'rohlik', '_type' => 'grocery', '_id' => '707891', '_version' => 4, 'ok' => true]], @@ -135,7 +135,7 @@ public function testIsOkBulkItemsWithOkField() */ public function testStringErrorMessage() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'error' => 'a', ])); @@ -147,7 +147,7 @@ public function testStringErrorMessage() */ public function testArrayErrorMessage() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'error' => ['a', 'b'], ])); @@ -159,7 +159,7 @@ public function testArrayErrorMessage() */ public function testIsNotOkBulkItemsWithOkField() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'took' => 213, 'items' => [ ['index' => ['_index' => 'rohlik', '_type' => 'grocery', '_id' => '707891', '_version' => 4, 'ok' => true]], @@ -175,7 +175,7 @@ public function testIsNotOkBulkItemsWithOkField() */ public function testIsOkBulkItemsWithStatusField() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'took' => 213, 'items' => [ ['index' => ['_index' => 'rohlik', '_type' => 'grocery', '_id' => '707891', '_version' => 4, 'status' => 200]], @@ -191,7 +191,7 @@ public function testIsOkBulkItemsWithStatusField() */ public function testIsNotOkBulkItemsWithStatusField() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'took' => 213, 'items' => [ ['index' => ['_index' => 'rohlik', '_type' => 'grocery', '_id' => '707891', '_version' => 4, 'status' => 200]], @@ -207,7 +207,7 @@ public function testIsNotOkBulkItemsWithStatusField() */ public function testDecodeResponseWithBigIntSetToTrue() { - $response = new Response(json_encode([ + $response = new Response(\json_encode([ 'took' => 213, 'items' => [ ['index' => ['_index' => 'rohlik', '_type' => 'grocery', '_id' => '707891', '_version' => 4, 'status' => 200]], diff --git a/test/Elastica/ResultTest.php b/test/Elastica/ResultTest.php index 16d51156d1..ba5e55072f 100644 --- a/test/Elastica/ResultTest.php +++ b/test/Elastica/ResultTest.php @@ -108,7 +108,7 @@ public function testGetTotalTimeReturnsExpectedResults() $this->assertNotNull($resultSet->getTotalTime(), 'Get Total Time should never be a null value'); $this->assertEquals( 'integer', - gettype($resultSet->getTotalTime()), + \gettype($resultSet->getTotalTime()), 'Total Time should be an integer' ); } diff --git a/test/Elastica/SearchTest.php b/test/Elastica/SearchTest.php index 6f9a13f4f6..4e466c5527 100644 --- a/test/Elastica/SearchTest.php +++ b/test/Elastica/SearchTest.php @@ -407,7 +407,7 @@ public function testArrayConfigSearch() $this->assertNotEmpty($resultSet->getSuggests(), 'term#name_suggest'); //Timeout - this one is a bit more tricky to test - $mockResponse = new Response(json_encode(['timed_out' => true])); + $mockResponse = new Response(\json_encode(['timed_out' => true])); $client = $this->createMock(Client::class); $client->method('request') ->will($this->returnValue($mockResponse)); diff --git a/test/Elastica/SnapshotTest.php b/test/Elastica/SnapshotTest.php index f643b4a9fe..8fddca115b 100644 --- a/test/Elastica/SnapshotTest.php +++ b/test/Elastica/SnapshotTest.php @@ -100,7 +100,7 @@ public function testSnapshotAndRestore() // ensure that the index has been restored $count = $this->_index->getType('_doc')->count(); - $this->assertEquals(sizeof($this->_docs), $count); + $this->assertEquals(\sizeof($this->_docs), $count); // delete the snapshot $response = $this->_snapshot->deleteSnapshot($repositoryName, $snapshotName); diff --git a/test/Elastica/StatusTest.php b/test/Elastica/StatusTest.php index f247f1152c..08f5fcac39 100644 --- a/test/Elastica/StatusTest.php +++ b/test/Elastica/StatusTest.php @@ -64,7 +64,7 @@ public function testIndexExists() $this->assertFalse($status->indexExists($indexName)); $index->create(); - usleep(10000); + \usleep(10000); $status->refresh(); $this->assertTrue($status->indexExists($indexName)); } @@ -92,7 +92,7 @@ public function testAliasExists() $this->assertTrue($status->aliasExists($aliasName)); $indicesWithAlias = $status->getIndicesWithAlias($aliasName); - $this->assertEquals([$indexName], array_map( + $this->assertEquals([$indexName], \array_map( function ($index) { return $index->getName(); }, $indicesWithAlias)); diff --git a/test/Elastica/TaskTest.php b/test/Elastica/TaskTest.php index 4e1322aa43..796a30dc7e 100644 --- a/test/Elastica/TaskTest.php +++ b/test/Elastica/TaskTest.php @@ -29,7 +29,7 @@ public function testGetId() $data = $task->getData(); $this->assertNotEmpty($task->getId()); - $this->assertEquals($task->getId(), sprintf('%s:%s', $data['task']['node'], $data['task']['id'])); + $this->assertEquals($task->getId(), \sprintf('%s:%s', $data['task']['node'], $data['task']['id'])); } /** @@ -43,7 +43,7 @@ public function testIsComplete() if ($task->isCompleted()) { break; } - sleep(1); // wait for task to complete + \sleep(1); // wait for task to complete $task->refresh(); } diff --git a/test/Elastica/Transport/AwsAuthV4Test.php b/test/Elastica/Transport/AwsAuthV4Test.php index 0241d9f12d..cb15a16d65 100644 --- a/test/Elastica/Transport/AwsAuthV4Test.php +++ b/test/Elastica/Transport/AwsAuthV4Test.php @@ -9,7 +9,7 @@ class AwsAuthV4Test extends GuzzleTest { public static function setUpBeforeClass() { - if (!class_exists('Aws\\Sdk')) { + if (!\class_exists('Aws\\Sdk')) { self::markTestSkipped('aws/aws-sdk-php package should be installed to run SignatureV4 transport tests'); } } @@ -37,7 +37,7 @@ public function testSignsWithProvidedCredentials() if ($guzzleException instanceof RequestException) { $request = $guzzleException->getRequest(); $expected = 'AWS4-HMAC-SHA256 Credential=foo/' - .date('Ymd').'/us-east-1/es/aws4_request, '; + .\date('Ymd').'/us-east-1/es/aws4_request, '; $this->assertStringStartsWith( $expected, $request->getHeaderLine('Authorization') @@ -107,10 +107,10 @@ public function testSignsWithEnvironmentalCredentials() 'persistent' => false, 'transport' => 'AwsAuthV4', ]; - putenv('AWS_REGION=us-east-1'); - putenv('AWS_ACCESS_KEY_ID=foo'); - putenv('AWS_SECRET_ACCESS_KEY=bar'); - putenv('AWS_SESSION_TOKEN=baz'); + \putenv('AWS_REGION=us-east-1'); + \putenv('AWS_ACCESS_KEY_ID=foo'); + \putenv('AWS_SECRET_ACCESS_KEY=bar'); + \putenv('AWS_SESSION_TOKEN=baz'); $client = $this->_getClient($config); try { @@ -120,7 +120,7 @@ public function testSignsWithEnvironmentalCredentials() if ($guzzleException instanceof RequestException) { $request = $guzzleException->getRequest(); $expected = 'AWS4-HMAC-SHA256 Credential=foo/' - .date('Ymd').'/us-east-1/es/aws4_request, '; + .\date('Ymd').'/us-east-1/es/aws4_request, '; $this->assertStringStartsWith( $expected, $request->getHeaderLine('Authorization') diff --git a/test/Elastica/Transport/GuzzleTest.php b/test/Elastica/Transport/GuzzleTest.php index 3ec6e67c12..7f28186b0b 100644 --- a/test/Elastica/Transport/GuzzleTest.php +++ b/test/Elastica/Transport/GuzzleTest.php @@ -11,7 +11,7 @@ class GuzzleTest extends BaseTest { public static function setUpBeforeClass() { - if (!class_exists('GuzzleHttp\\Client')) { + if (!\class_exists('GuzzleHttp\\Client')) { self::markTestSkipped('guzzlehttp/guzzle package should be installed to run guzzle transport tests'); } } @@ -76,7 +76,7 @@ public function testDynamicHttpMethodOnlyAffectsRequestsWithBody(array $config, public function testWithEnvironmentalProxy() { $this->checkProxy($this->_getProxyUrl()); - putenv('http_proxy='.$this->_getProxyUrl().'/'); + \putenv('http_proxy='.$this->_getProxyUrl().'/'); $client = $this->_getClient(['transport' => 'Guzzle', 'persistent' => false]); $transferInfo = $client->request('/_nodes')->getTransferInfo(); @@ -86,7 +86,7 @@ public function testWithEnvironmentalProxy() $transferInfo = $client->request('/_nodes')->getTransferInfo(); $this->assertEquals(200, $transferInfo['http_code']); - putenv('http_proxy='); + \putenv('http_proxy='); } /** @@ -95,7 +95,7 @@ public function testWithEnvironmentalProxy() public function testWithEnabledEnvironmentalProxy() { $this->checkProxy($this->_getProxyUrl403()); - putenv('http_proxy='.$this->_getProxyUrl403().'/'); + \putenv('http_proxy='.$this->_getProxyUrl403().'/'); $client = $this->_getClient(['transport' => 'Guzzle', 'persistent' => false]); $transferInfo = $client->request('/_nodes')->getTransferInfo(); @@ -106,7 +106,7 @@ public function testWithEnabledEnvironmentalProxy() $transferInfo = $client->request('/_nodes')->getTransferInfo(); $this->assertEquals(200, $transferInfo['http_code']); - putenv('http_proxy='); + \putenv('http_proxy='); } /** @@ -181,18 +181,18 @@ public function testInvalidConnection() protected function checkProxy($url) { - $url = parse_url($url); + $url = \parse_url($url); $this->_checkConnection($url['host'], $url['port']); } protected function setUp() { - putenv('http_proxy='); + \putenv('http_proxy='); } protected function tearDown() { parent::tearDown(); - putenv('http_proxy='); + \putenv('http_proxy='); } } diff --git a/test/Elastica/Transport/HttpTest.php b/test/Elastica/Transport/HttpTest.php index 60a843137a..da41d59653 100644 --- a/test/Elastica/Transport/HttpTest.php +++ b/test/Elastica/Transport/HttpTest.php @@ -138,7 +138,7 @@ public function testUnicodeData() public function testWithEnvironmentalProxy() { $this->checkProxy($this->_getProxyUrl()); - putenv('http_proxy='.$this->_getProxyUrl().'/'); + \putenv('http_proxy='.$this->_getProxyUrl().'/'); $client = $this->_getClient(); $transferInfo = $client->request('_nodes')->getTransferInfo(); @@ -148,7 +148,7 @@ public function testWithEnvironmentalProxy() $transferInfo = $client->request('_nodes')->getTransferInfo(); $this->assertEquals(200, $transferInfo['http_code']); - putenv('http_proxy='); + \putenv('http_proxy='); } /** @@ -157,7 +157,7 @@ public function testWithEnvironmentalProxy() public function testWithEnabledEnvironmentalProxy() { $this->checkProxy($this->_getProxyUrl403()); - putenv('http_proxy='.$this->_getProxyUrl403().'/'); + \putenv('http_proxy='.$this->_getProxyUrl403().'/'); $client = $this->_getClient(); $transferInfo = $client->request('_nodes')->getTransferInfo(); $this->assertEquals(403, $transferInfo['http_code']); @@ -165,7 +165,7 @@ public function testWithEnabledEnvironmentalProxy() $client->getConnection()->setProxy(''); $transferInfo = $client->request('_nodes')->getTransferInfo(); $this->assertEquals(200, $transferInfo['http_code']); - putenv('http_proxy='); + \putenv('http_proxy='); } /** @@ -261,13 +261,13 @@ public function testRequestSuccessWithHttpCompressionDisabled() protected function checkProxy($url) { - $url = parse_url($url); + $url = \parse_url($url); $this->_checkConnection($url['host'], $url['port']); } protected function tearDown() { parent::tearDown(); - putenv('http_proxy='); + \putenv('http_proxy='); } } diff --git a/test/Elastica/Transport/TransportBenchmarkTest.php b/test/Elastica/Transport/TransportBenchmarkTest.php index 2c15c38874..997eb52c2c 100644 --- a/test/Elastica/Transport/TransportBenchmarkTest.php +++ b/test/Elastica/Transport/TransportBenchmarkTest.php @@ -37,7 +37,7 @@ public static function tearDownAfterClass() protected function getType(array $config) { $client = $this->_getClient($config); - $index = $client->getIndex('benchmark'.uniqid()); + $index = $client->getIndex('benchmark'.\uniqid()); $index->create(['index' => ['number_of_shards' => 1, 'number_of_replicas' => 0]], true); return $index->getType('_doc'); @@ -84,7 +84,7 @@ public function testRandomRead(array $config, $transport) $times = []; for ($i = 0; $i < $this->_max; ++$i) { - $test = rand(1, $this->_max); + $test = \rand(1, $this->_max); $query = new Query(); $query->setQuery(new MatchAll()); $query->setPostFilter(new Term(['test' => $test])); @@ -200,7 +200,7 @@ protected function getData($test) 'name' => [], ]; for ($i = 0; $i < $this->_maxData; ++$i) { - $data['name'][] = uniqid(); + $data['name'][] = \uniqid(); } return $data; @@ -214,16 +214,16 @@ protected function getData($test) protected static function logResults($name, $transport, array $times) { self::$_results[$name][$transport] = [ - 'count' => count($times), - 'max' => max($times) * 1000, - 'min' => min($times) * 1000, - 'mean' => (array_sum($times) / count($times)) * 1000, + 'count' => \count($times), + 'max' => \max($times) * 1000, + 'min' => \min($times) * 1000, + 'mean' => (\array_sum($times) / \count($times)) * 1000, ]; } protected static function printResults() { - echo sprintf( + echo \sprintf( "\n%-12s | %-20s | %-12s | %-12s | %-12s | %-12s\n\n", 'NAME', 'TRANSPORT', @@ -238,7 +238,7 @@ protected static function printResults() foreach ($values as $times) { $means[] = $times['mean']; } - $minMean = min($means); + $minMean = \min($means); foreach ($values as $transport => $times) { $perc = 0; @@ -246,7 +246,7 @@ protected static function printResults() $perc = (($times['mean'] - $minMean) / $minMean) * 100; } - echo sprintf( + echo \sprintf( "%-12s | %-20s | %-12d | %-12.2f | %-12.2f | %-12.2f | %+03.2f\n", $name, $transport, diff --git a/test/Elastica/TypeTest.php b/test/Elastica/TypeTest.php index 25734b4d7b..a661f5515c 100644 --- a/test/Elastica/TypeTest.php +++ b/test/Elastica/TypeTest.php @@ -938,7 +938,7 @@ public function testExists() $index->forcemerge(); // sleep a moment to be sure that all nodes in cluster has new type - sleep(5); + \sleep(5); //Test if type exists $this->assertTrue($type->exists()); @@ -1013,7 +1013,7 @@ public function testRequestEndpoint() $response = $type->requestEndpoint($endpoint); $data = $response->getData(); - $mapping = array_shift($data); + $mapping = \array_shift($data); $this->assertEquals( ['_doc' => ['properties' => $expect]], diff --git a/test/Elastica/UtilTest.php b/test/Elastica/UtilTest.php index df7a00b030..5057d5e399 100644 --- a/test/Elastica/UtilTest.php +++ b/test/Elastica/UtilTest.php @@ -171,7 +171,7 @@ public function testConvertDateTimeObjectWithTimezone() $convertedString = Util::convertDateTimeObject($dateTimeObject); - $date = date('Y-m-d\TH:i:sP', $timestamp); + $date = \date('Y-m-d\TH:i:sP', $timestamp); $this->assertEquals($convertedString, $date); } @@ -186,7 +186,7 @@ public function testConvertDateTimeObjectWithoutTimezone() $convertedString = Util::convertDateTimeObject($dateTimeObject, false); - $date = date('Y-m-d\TH:i:s\Z', $timestamp); + $date = \date('Y-m-d\TH:i:s\Z', $timestamp); $this->assertEquals($convertedString, $date); } diff --git a/test/bootstrap.php b/test/bootstrap.php index 8a29cf0fae..afd9bb0b39 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -1,5 +1,5 @@ Date: Tue, 12 Feb 2019 09:43:17 +0100 Subject: [PATCH 2/2] Update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90359bfeae..46e380243d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project will be documented in this file based on the ### Added ### Improvements +* Added `native_function_invocation` CS rule [#1606](https://github.com/ruflin/Elastica/pull/1606) ### Deprecated