From efb3e4e1ea4970f3e666b68cf570d1d1817b42a1 Mon Sep 17 00:00:00 2001 From: Moritz Friedrich Date: Fri, 18 Sep 2020 16:39:45 +0200 Subject: [PATCH] Fixed type issues --- src/Classes/Search.php | 4 +- src/Collection.php | 4 +- src/Commands/CreateIndexCommand.php | 10 +-- src/Commands/DropIndexCommand.php | 10 +-- src/Commands/ListIndicesCommand.php | 13 ++-- src/Commands/ReindexCommand.php | 13 ++-- src/Commands/UpdateIndexCommand.php | 10 +-- src/Connection.php | 1 + src/ElasticsearchServiceProvider.php | 7 ++- src/Index.php | 10 +-- src/Model.php | 62 ++++++++++++------- src/Pagination.php | 31 ++++++---- src/Query.php | 93 +++++++++++++++------------- src/Request.php | 5 +- src/ScoutEngine.php | 25 +++++--- src/helpers.php | 22 +------ 16 files changed, 178 insertions(+), 142 deletions(-) diff --git a/src/Classes/Search.php b/src/Classes/Search.php index 7f4a6bb..7b78f89 100755 --- a/src/Classes/Search.php +++ b/src/Classes/Search.php @@ -4,6 +4,8 @@ use Matchory\Elasticsearch\Query; +use function is_callable; + /** * Class Search * @@ -60,7 +62,7 @@ public function __construct( $this->query = $query; $this->queryString = $queryString; - if (is_callback_function($settings)) { + if (is_callable($settings)) { $settings($this); } diff --git a/src/Collection.php b/src/Collection.php index f5bff3b..238a697 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -23,7 +23,7 @@ class Collection extends BaseCollection protected $maxScore; /** - * @var int|null + * @var float|null */ protected $duration; @@ -98,7 +98,7 @@ public function getMaxScore(): ?int return $this->maxScore; } - public function getDuration(): ?int + public function getDuration(): ?float { return $this->duration; } diff --git a/src/Commands/CreateIndexCommand.php b/src/Commands/CreateIndexCommand.php index 0035df4..4559d84 100755 --- a/src/Commands/CreateIndexCommand.php +++ b/src/Commands/CreateIndexCommand.php @@ -7,6 +7,11 @@ use Matchory\Elasticsearch\Connection; use RuntimeException; +use function app; +use function array_keys; +use function config; +use function is_null; + class CreateIndexCommand extends Command { /** @@ -47,11 +52,6 @@ public function handle(): void { $connectionName = $this->option("connection") ?: config('es.default'); $connection = $this->es->connection($connectionName); - - if ( ! $connection) { - throw new RuntimeException('No connection'); - } - $client = $connection->raw(); $indices = ! is_null($this->argument('index')) ? [$this->argument('index')] diff --git a/src/Commands/DropIndexCommand.php b/src/Commands/DropIndexCommand.php index 9f59285..e8b539d 100755 --- a/src/Commands/DropIndexCommand.php +++ b/src/Commands/DropIndexCommand.php @@ -7,6 +7,11 @@ use Matchory\Elasticsearch\Connection; use RuntimeException; +use function app; +use function array_keys; +use function config; +use function is_null; + class DropIndexCommand extends Command { /** @@ -48,11 +53,6 @@ public function handle(): void { $connectionName = $this->option("connection") ?: config('es.default'); $connection = $this->es->connection($connectionName); - - if ( ! $connection) { - throw new RuntimeException('No connection'); - } - $force = $this->option("force") ?: 0; $client = $connection->raw(); $indices = ! is_null($this->argument('index')) diff --git a/src/Commands/ListIndicesCommand.php b/src/Commands/ListIndicesCommand.php index 7a3d053..b3a59c5 100755 --- a/src/Commands/ListIndicesCommand.php +++ b/src/Commands/ListIndicesCommand.php @@ -8,6 +8,14 @@ use Matchory\Elasticsearch\Connection; use RuntimeException; +use function app; +use function array_key_exists; +use function config; +use function count; +use function explode; +use function is_array; +use function trim; + /** * Class ListIndicesCommand * @@ -71,11 +79,6 @@ public function handle(): void { $connectionName = $this->option("connection") ?: config('es.default'); $connection = $this->es->connection($connectionName); - - if ( ! $connection) { - throw new RuntimeException('No connection'); - } - $indices = $connection->raw()->cat()->indices(); $indices = is_array($indices) ? $this->getIndicesFromArrayResponse($indices) diff --git a/src/Commands/ReindexCommand.php b/src/Commands/ReindexCommand.php index 7eb65c9..8c06e35 100755 --- a/src/Commands/ReindexCommand.php +++ b/src/Commands/ReindexCommand.php @@ -7,6 +7,13 @@ use Matchory\Elasticsearch\Connection; use RuntimeException; +use function app; +use function array_key_exists; +use function ceil; +use function config; +use function count; +use function json_encode; + /** * Class ReindexCommand * @@ -83,7 +90,7 @@ public function handle(): void $this->size = (int)$this->option("bulk-size"); $this->scroll = $this->option("scroll"); - if ($this->size <= 0 || ! is_numeric($this->size)) { + if ($this->size <= 0) { $this->warn("Invalid size value"); return; @@ -128,10 +135,6 @@ public function migrate( ): void { $connection = $this->es->connection($this->connection); - if ( ! $connection) { - throw new RuntimeException('No connection'); - } - if ($page === 1) { $pages = (int)ceil( $connection diff --git a/src/Commands/UpdateIndexCommand.php b/src/Commands/UpdateIndexCommand.php index 7d62580..fc3416a 100755 --- a/src/Commands/UpdateIndexCommand.php +++ b/src/Commands/UpdateIndexCommand.php @@ -7,6 +7,11 @@ use Matchory\Elasticsearch\Connection; use RuntimeException; +use function app; +use function array_keys; +use function config; +use function is_null; + class UpdateIndexCommand extends Command { /** @@ -46,11 +51,6 @@ public function handle(): void { $connectionName = $this->option("connection") ?: config('es.default'); $connection = $this->es->connection($connectionName); - - if ( ! $connection) { - throw new RuntimeException('No connection'); - } - $client = $connection->raw(); $indices = ! is_null($this->argument('index')) ? [$this->argument('index')] diff --git a/src/Connection.php b/src/Connection.php index 713866d..dff3f22 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -11,6 +11,7 @@ use Monolog\Logger; use RuntimeException; +use function app; use function array_key_exists; use function call_user_func_array; use function method_exists; diff --git a/src/ElasticsearchServiceProvider.php b/src/ElasticsearchServiceProvider.php index 00b6114..1003a7c 100755 --- a/src/ElasticsearchServiceProvider.php +++ b/src/ElasticsearchServiceProvider.php @@ -16,7 +16,9 @@ use RuntimeException; use function class_exists; +use function config; use function config_path; +use function method_exists; use function str_starts_with; use function version_compare; @@ -46,7 +48,10 @@ public function boot(): void // Auto configuration with lumen framework. - if (Str::contains($this->app->version(), 'Lumen')) { + if ( + method_exists($this->app, 'configure') && + Str::contains($this->app->version(), 'Lumen') + ) { $this->app->configure('es'); } diff --git a/src/Index.php b/src/Index.php index 259077a..40e1bef 100755 --- a/src/Index.php +++ b/src/Index.php @@ -9,7 +9,6 @@ use function count; use function func_get_args; use function is_array; -use function is_callback_function; /** * Class Index @@ -42,7 +41,7 @@ class Index /** * Index create callback * - * @var null + * @var callable|null */ public $callback; @@ -63,7 +62,7 @@ class Index /** * Index mapping * - * @var int + * @var array */ public $mappings = []; @@ -152,10 +151,7 @@ public function exists(): bool public function create(): array { $callback = $this->callback; - - if (is_callback_function($callback)) { - $callback($this); - } + $callback($this); $params = [ 'index' => $this->name, diff --git a/src/Model.php b/src/Model.php index 4f2fd8b..5419409 100755 --- a/src/Model.php +++ b/src/Model.php @@ -1,13 +1,18 @@ toArray(), $options); + return json_encode( + $this->toArray(), + JSON_THROW_ON_ERROR | $options + ); } /** * Delete model record * * @return $this + * @throws InvalidArgumentException + * @throws RuntimeException */ public function delete(): ?self { @@ -393,9 +404,11 @@ public function delete(): ?self /** * Save data to model * - * @return string + * @return $this + * @throws InvalidArgumentException + * @throws RuntimeException */ - public function save(): string + public function save(): self { $fields = array_diff($this->attributes, [ '_index', @@ -411,29 +424,30 @@ public function save(): string ->newQuery() ->id($this->getID()) ->update($fields); + + return $this; + } + + // Check if model key exists in items + if (array_key_exists('_id', $this->attributes)) { + $created = $this + ->newQuery() + ->id($this->attributes['_id']) + ->insert($fields); + $this->_id = $this->attributes['_id']; } else { - // Check if model key exists in items - - if (array_key_exists('_id', $this->attributes)) { - $created = $this - ->newQuery() - ->id($this->attributes['_id']) - ->insert($fields); - $this->_id = $this->attributes['_id']; - } else { - $created = $this->newQuery()->insert($fields); - $this->_id = $created->_id; - } + $created = $this->newQuery()->insert($fields); + $this->_id = $created->_id; + } - $this->setConnection($this->getConnection()); - $this->setIndex($created->_index); + $this->setConnection($this->getConnection()); + $this->setIndex($created->_index); - // Match earlier versions - $this->_index = $created->_index; - $this->_type = $this->type; + // Match earlier versions + $this->_index = $created->_index; + $this->_type = $this->type; - $this->exists = true; - } + $this->exists = true; return $this; } @@ -465,6 +479,8 @@ public function getID() * @param array $parameters * * @return mixed + * @throws InvalidArgumentException + * @throws RuntimeException */ public function __call(string $method, array $parameters) { diff --git a/src/Pagination.php b/src/Pagination.php index 81b0255..a28fce5 100755 --- a/src/Pagination.php +++ b/src/Pagination.php @@ -1,45 +1,52 @@ elements(); + $html = ''; switch ($view) { case 'bootstrap-4': - return require __DIR__ . '/pagination/bootstrap-4.php'; + $html = require __DIR__ . '/pagination/bootstrap-4.php'; + break; case 'default': - return require __DIR__ . '/pagination/default.php'; + $html = require __DIR__ . '/pagination/default.php'; + break; case 'simple-bootstrap-4': - return require __DIR__ . '/pagination/simple-bootstrap-4.php'; + $html = require __DIR__ . '/pagination/simple-bootstrap-4.php'; + break; case 'simple-default': - return require __DIR__ . '/pagination/simple-default.php'; - - default: - return ''; + $html = require __DIR__ . '/pagination/simple-default.php'; + break; } + + return new HtmlString($html); } } diff --git a/src/Query.php b/src/Query.php index bd9a42c..c7058c2 100755 --- a/src/Query.php +++ b/src/Query.php @@ -11,16 +11,19 @@ use Matchory\Elasticsearch\Classes\Search; use stdClass; +use function app; use function array_filter; use function array_key_exists; use function array_merge; use function array_unique; use function array_values; +use function config; use function count; use function func_get_args; +use function get_class; use function in_array; use function is_array; -use function is_callback_function; +use function is_callable; use function is_null; use function json_encode; use function md5; @@ -139,7 +142,7 @@ class Query /** * Elastic model instance * - * @var Model&string + * @var Model */ public $model; @@ -225,9 +228,9 @@ class Query /** * Query search type * - * @var int + * @var 'query_then_fetch'|'dfs_query_then_fetch' */ - protected $search_type; + protected $searchType; /** * Query limit @@ -366,7 +369,7 @@ public function scrollID(string $scroll): self */ public function searchType(string $type): self { - $this->search_type = $type; + $this->searchType = $type; return $this; } @@ -374,11 +377,11 @@ public function searchType(string $type): self /** * get the query search type * - * @return int|null + * @return string|null */ - public function getSearchType(): ?int + public function getSearchType(): ?string { - return $this->search_type; + return $this->searchType; } /** @@ -565,18 +568,18 @@ public function id(?string $_id = null): self /** * Set the query where clause * - * @param string $name - * @param string $operator - * @param mixed|null $value + * @param string|callable $name + * @param string $operator + * @param mixed|null $value * * @return $this */ public function where( - string $name, + $name, $operator = self::OPERATOR_EQUAL, $value = null ): self { - if (is_callback_function($name)) { + if (is_callable($name)) { $name($this); return $this; @@ -626,9 +629,9 @@ public function where( /** * Set the query inverse where clause * - * @param $name - * @param string $operator - * @param null $value + * @param string|callable $name + * @param string $operator + * @param null $value * * @return $this */ @@ -637,7 +640,7 @@ public function whereNot( $operator = self::OPERATOR_EQUAL, $value = null ): self { - if (is_callback_function($name)) { + if (is_callable($name)) { $name($this); return $this; @@ -740,14 +743,14 @@ public function whereNotBetween( /** * Set the query where in clause * - * @param $name - * @param array $value + * @param string|callable $name + * @param array $value * * @return $this */ public function whereIn($name, $value = []): self { - if (is_callback_function($name)) { + if (is_callable($name)) { $name($this); return $this; @@ -763,14 +766,14 @@ public function whereIn($name, $value = []): self /** * Set the query where not in clause * - * @param $name - * @param array $value + * @param string|callable $name + * @param array $value * * @return $this */ public function whereNotIn($name, $value = []): self { - if (is_callback_function($name)) { + if (is_callable($name)) { $name($this); return $this; @@ -812,19 +815,19 @@ public function whereExists(string $name, bool $exists = true): self * * @see https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-geo-distance-query.html * - * @param string $name A name of the field. - * @param mixed $value A starting geo point which can be represented by - * a string 'lat,lon', an object like - * `{'lat': lat, 'lon': lon}` or an array - * like `[lon,lat]`. - * @param string $distance A distance from the starting geo point. It can be - * for example '20km'. + * @param string|callable $name A name of the field. + * @param mixed $value A starting geo point which can be + * represented by a string 'lat,lon', an + * object like `{'lat': lat, 'lon': lon}` + * or an array like `[lon,lat]`. + * @param string $distance A distance from the starting geo point. + * It can be for example '20km'. * * @return $this */ - public function distance(string $name, $value, string $distance): self + public function distance($name, $value, string $distance): self { - if (is_callback_function($name)) { + if (is_callable($name)) { $name($this); return $this; @@ -857,7 +860,7 @@ public function search(?string $queryString = null, $settings = null): self $settings ); - if ( ! is_callback_function($settings)) { + if ( ! is_callable($settings)) { $search->boost($settings ?: 1); } @@ -949,6 +952,8 @@ public function query(): array // TODO: What should be happening here? if ($this->model && $this->useGlobalScopes) { + // False Positive by PhpStorm + /** @noinspection PhpUndefinedMethodInspection */ $this->model->boot($this); } @@ -960,10 +965,10 @@ public function query(): array $query['client'] = ['ignore' => $this->ignores]; } - $search_type = $this->getSearchType(); + $searchType = $this->getSearchType(); - if ($search_type) { - $query['search_type'] = $search_type; + if ($searchType) { + $query['search_type'] = $searchType; } $scroll = $this->getScroll(); @@ -1011,9 +1016,9 @@ public function get(?string $scrollId = null): Collection * * @param string|null $scroll_id * - * @return Model|object + * @return Model|null */ - public function first(?string $scroll_id = null) + public function first(?string $scroll_id = null): ?Model { $this->take(1); @@ -1190,7 +1195,7 @@ public function insert($data, ?string $_id = null): object */ public function bulk($data): object { - if (is_callback_function($data)) { + if (is_callable($data)) { $bulk = new Bulk($this); $data($bulk); @@ -1665,7 +1670,9 @@ protected function getAll(array $result = []): Collection foreach ($result[self::FIELD_HITS][self::FIELD_NESTED_HITS] as $row) { // Fallback to default model class - $modelClass = $this->model ?? Model::class; + $modelClass = $this->model + ? get_class($this->model) + : Model::class; $model = new $modelClass($row[self::FIELD_SOURCE], true); $model->setConnection($model->getConnection()); @@ -1702,9 +1709,9 @@ protected function getFirst(array $result = []): ?Model } $data = $result[self::FIELD_HITS][self::FIELD_NESTED_HITS]; - $modelClass = $this->model ?? Model::class; - - /** @var Model $model */ + $modelClass = $this->model + ? get_class($this->model) + : Model::class; $model = new $modelClass($data[0][self::FIELD_SOURCE], true); $model->setConnection($model->getConnection()); diff --git a/src/Request.php b/src/Request.php index 2c9edcf..911d333 100755 --- a/src/Request.php +++ b/src/Request.php @@ -13,10 +13,13 @@ class Request { /** * Get the request url + * TODO: Replace this class by the Laravel-supplied helper functions. + * + * @param string|null $host * * @return string */ - public static function url(): string + public static function url(?string $host = null): string { $server = $_SERVER; $ssl = ( ! empty($server['HTTPS']) && $server['HTTPS'] === 'on'); diff --git a/src/ScoutEngine.php b/src/ScoutEngine.php index bda0e35..8a7dedb 100755 --- a/src/ScoutEngine.php +++ b/src/ScoutEngine.php @@ -50,7 +50,7 @@ public function delete($models): void { $params['body'] = []; - $models->each(function ($model) use (&$params) { + $models->each(function (Model $model) use (&$params) { $params['body'][] = [ 'delete' => [ '_id' => $model->getKey(), @@ -124,7 +124,9 @@ public function map(Builder $builder, $results, $model): Collection $collection = new Collection($results['hits']['hits']); - return $collection->map(function ($hit) use ($models) { + return $collection->map(static function ( + array $hit + ) use ($models) { return $models[$hit['_id']]; }); } @@ -185,9 +187,11 @@ public function search(Builder $builder) */ public function update($models): void { - $params['body'] = []; + $params = [ + 'body' => [], + ]; - $models->each(function ($model) use (&$params) { + $models->each(function (Model $model) use (&$params) { $params['body'][] = [ 'update' => [ '_id' => $model->getKey(), @@ -265,9 +269,16 @@ protected function performSearch(Builder $builder, array $options = []) protected function filters(Builder $builder): array { return collect($builder->wheres) - ->map(function ($value, $key) { - return ['match_phrase' => [$key => $value]]; - }) + ->map( + /** + * @param mixed $value + * @param string|int $key + * + * @return array + */ + static function ($value, $key): array { + return ['match_phrase' => [$key => $value]]; + }) ->values() ->all(); } diff --git a/src/helpers.php b/src/helpers.php index bdba1dd..e7cc3c5 100755 --- a/src/helpers.php +++ b/src/helpers.php @@ -12,25 +12,7 @@ */ function config_path(string $path = ''): string { - return app()->basePath() . '/config' . ($path ? '/' . $path : $path); - } -} - -if ( ! function_exists('is_callback_function')) { - /** - * Check if a callback function. - * - * @param string|callable|Closure $callback - * - * @return bool - */ - function is_callback_function($callback): bool - { - return ( - is_callable($callback) && - is_object($callback) && - $callback instanceof Closure - ); + return \app()->basePath() . '/config' . ($path ? '/' . $path : $path); } } @@ -44,7 +26,7 @@ function is_callback_function($callback): bool */ function base_path(string $path = ''): string { - return app()->basePath() . ($path ? '/' . $path : $path); + return \app()->basePath() . ($path ? '/' . $path : $path); } }