From fa01d30e89964d35d4c98256128fec5acd6eda5c Mon Sep 17 00:00:00 2001 From: yuki kato Date: Tue, 26 Jul 2016 17:43:44 +0700 Subject: [PATCH 1/6] PSR-2 code formatted, php syntax to >=5.4 --- src/ElasticquentClientTrait.php | 2 + src/ElasticquentCollectionTrait.php | 33 ++-- src/ElasticquentConfigTrait.php | 15 +- src/ElasticquentElasticsearchFacade.php | 1 + src/ElasticquentInterface.php | 26 ++- src/ElasticquentPaginator.php | 26 +-- src/ElasticquentResultCollection.php | 42 +++-- src/ElasticquentServiceProvider.php | 4 +- src/ElasticquentSupport.php | 2 + src/ElasticquentTrait.php | 171 +++++++++++++------ src/config/elasticquent.php | 8 +- tests/ElasticSearchMethodsTest.php | 58 ++++--- tests/ElasticquentClientTraitTest.php | 2 + tests/ElasticquentConfigTraitTest.php | 2 + tests/ElasticquentTraitTest.php | 19 ++- tests/models/CustomTestModel.php | 8 +- tests/models/SearchTestModel.php | 24 +-- tests/models/TestModel.php | 5 +- tests/models/TestModelWithCustomTypeName.php | 6 +- tests/stubs/parameters.php | 16 +- tests/stubs/results.php | 44 ++--- 21 files changed, 327 insertions(+), 187 deletions(-) diff --git a/src/ElasticquentClientTrait.php b/src/ElasticquentClientTrait.php index 63045a5..8dbecbe 100644 --- a/src/ElasticquentClientTrait.php +++ b/src/ElasticquentClientTrait.php @@ -4,8 +4,10 @@ trait ElasticquentClientTrait { + use ElasticquentConfigTrait; + /** * Get ElasticSearch Client * diff --git a/src/ElasticquentCollectionTrait.php b/src/ElasticquentCollectionTrait.php index ae51d51..9d10b11 100644 --- a/src/ElasticquentCollectionTrait.php +++ b/src/ElasticquentCollectionTrait.php @@ -8,8 +8,10 @@ */ trait ElasticquentCollectionTrait { + use ElasticquentClientTrait; + /** * Add To Index * @@ -23,16 +25,16 @@ public function addToIndex() return null; } - $params = array(); + $params = []; foreach ($this->all() as $item) { - $params['body'][] = array( - 'index' => array( - '_id' => $item->getKey(), - '_type' => $item->getTypeName(), + $params['body'][] = [ + 'index' => [ + '_id' => $item->getKey(), + '_type' => $item->getTypeName(), '_index' => $item->getIndexName(), - ), - ); + ], + ]; $params['body'][] = $item->getIndexDocumentData(); } @@ -40,6 +42,7 @@ public function addToIndex() return $this->getElasticSearchClient()->bulk($params); } + /** * Delete From Index * @@ -49,21 +52,22 @@ public function deleteFromIndex() { $all = $this->all(); - $params = array(); + $params = []; foreach ($all as $item) { - $params['body'][] = array( - 'delete' => array( - '_id' => $item->getKey(), - '_type' => $item->getTypeName(), + $params['body'][] = [ + 'delete' => [ + '_id' => $item->getKey(), + '_type' => $item->getTypeName(), '_index' => $item->getIndexName(), - ), - ); + ], + ]; } return $this->getElasticSearchClient()->bulk($params); } + /** * Reindex * @@ -74,6 +78,7 @@ public function deleteFromIndex() public function reindex() { $this->deleteFromIndex(); + return $this->addToIndex(); } diff --git a/src/ElasticquentConfigTrait.php b/src/ElasticquentConfigTrait.php index 80f8e3f..9b1fca1 100644 --- a/src/ElasticquentConfigTrait.php +++ b/src/ElasticquentConfigTrait.php @@ -4,6 +4,7 @@ trait ElasticquentConfigTrait { + /** * Get Index Name * @@ -15,7 +16,7 @@ public function getIndexName() // config file and if there is a default index. $index_name = $this->getElasticConfig('default_index'); - if (!empty($index_name)) { + if ( ! empty($index_name)) { return $index_name; } @@ -23,11 +24,13 @@ public function getIndexName() return 'default'; } + /** * Get the Elasticquent config * - * @param string $key the configuration key + * @param string $key the configuration key * @param string $prefix filename of configuration file + * * @return array configuration */ public function getElasticConfig($key = 'config', $prefix = 'elasticquent') @@ -48,6 +51,7 @@ public function getElasticConfig($key = 'config', $prefix = 'elasticquent') return $config_helper->get($key); } + /** * Inject given config file into an instance of Laravel's config * @@ -58,18 +62,19 @@ protected function getConfigHelper() { $config_file = $this->getConfigFile(); - if (!file_exists($config_file)) { + if ( ! file_exists($config_file)) { throw new \Exception('Config file not found.'); } - return new \Illuminate\Config\Repository(array('elasticquent' => require($config_file))); + return new \Illuminate\Config\Repository(['elasticquent' => require($config_file)]); } + /** * Get the config path and file name to use when Laravel framework isn't present * e.g. using Eloquent stand-alone or running unit tests * - * @return string config file path + * @return string config file path */ protected function getConfigFile() { diff --git a/src/ElasticquentElasticsearchFacade.php b/src/ElasticquentElasticsearchFacade.php index bcdb911..f5a64fe 100644 --- a/src/ElasticquentElasticsearchFacade.php +++ b/src/ElasticquentElasticsearchFacade.php @@ -9,6 +9,7 @@ */ class ElasticquentElasticsearchFacade extends Facade { + /** * Get the registered name of the component. * diff --git a/src/ElasticquentInterface.php b/src/ElasticquentInterface.php index b5ecba7..36cba6b 100644 --- a/src/ElasticquentInterface.php +++ b/src/ElasticquentInterface.php @@ -2,6 +2,7 @@ interface ElasticquentInterface { + /** * Get ElasticSearch Client * @@ -9,13 +10,16 @@ interface ElasticquentInterface */ public function getElasticSearchClient(); + /** * New Collection * * @param array $models + * * @return Collection */ - public function newCollection(array $models = array()); + public function newCollection(array $models = []); + /** * Get Index Name @@ -24,6 +28,7 @@ public function newCollection(array $models = array()); */ public function getIndexName(); + /** * Get Type Name * @@ -31,11 +36,13 @@ public function getIndexName(); */ public function getTypeName(); + /** * Uses Timestamps In Index. */ public function usesTimestampsInIndex(); + /** * Get Mapping Properties * @@ -43,6 +50,7 @@ public function usesTimestampsInIndex(); */ public function getMappingProperties(); + /** * Set Mapping Properties * @@ -50,6 +58,7 @@ public function getMappingProperties(); */ public function setMappingProperties(array $mapping = null); + /** * Get Index Document Data * @@ -60,6 +69,7 @@ public function setMappingProperties(array $mapping = null); */ public function getIndexDocumentData(); + /** * Index Documents * @@ -69,10 +79,12 @@ public function getIndexDocumentData(); */ public static function addAllToIndex(); + /** * Search a Type. */ - public static function search($query = array()); + public static function search($query = []); + /** * Add to Search Index @@ -81,6 +93,7 @@ public static function search($query = array()); */ public function addToIndex(); + /** * Remove From Search Index * @@ -88,6 +101,7 @@ public function addToIndex(); */ public function removeFromIndex(); + /** * Get Search Document * @@ -98,6 +112,7 @@ public function removeFromIndex(); */ public function getIndexedDocument(); + /** * Get Basic Elasticsearch Params * @@ -110,6 +125,7 @@ public function getIndexedDocument(); */ public function getBasicEsParams($getIdIfPossible = true); + /** * Is Elasticsearch Document. * @@ -120,6 +136,7 @@ public function getBasicEsParams($getIdIfPossible = true); */ public function isDocument(); + /** * Get Document Score * @@ -127,6 +144,7 @@ public function isDocument(); */ public function documentScore(); + /** * Put Mapping. * @@ -136,6 +154,7 @@ public function documentScore(); */ public static function putMapping($ignoreConflicts = false); + /** * Delete Mapping * @@ -143,6 +162,7 @@ public static function putMapping($ignoreConflicts = false); */ public static function deleteMapping(); + /** * Rebuild Mapping * @@ -153,6 +173,7 @@ public static function deleteMapping(); */ public static function rebuildMapping(); + /** * Get Mapping * @@ -163,6 +184,7 @@ public static function rebuildMapping(); */ public static function getMapping(); + /** * Type Exists * diff --git a/src/ElasticquentPaginator.php b/src/ElasticquentPaginator.php index 84de151..46013cf 100644 --- a/src/ElasticquentPaginator.php +++ b/src/ElasticquentPaginator.php @@ -5,30 +5,32 @@ class ElasticquentPaginator extends Paginator { + /** * Create a new paginator instance. * - * @param mixed $items - * @param mixed $hits - * @param int $total - * @param int $perPage - * @param int|null $currentPage - * @param array $options (path, query, fragment, pageName) + * @param mixed $items + * @param mixed $hits + * @param int $total + * @param int $perPage + * @param int|null $currentPage + * @param array $options (path, query, fragment, pageName) */ public function __construct($items, $hits, $total, $perPage, $currentPage = null, array $options = []) { foreach ($options as $key => $value) { $this->{$key} = $value; } - $this->total = $total; - $this->perPage = $perPage; - $this->lastPage = (int) ceil($total / $perPage); + $this->total = $total; + $this->perPage = $perPage; + $this->lastPage = (int)ceil($total / $perPage); $this->currentPage = $this->setCurrentPage($currentPage, $this->lastPage); - $this->path = $this->path != '/' ? rtrim($this->path, '/') . '/' : $this->path; - $this->items = $items instanceof Collection ? $items : Collection::make($items); - $this->hits = $hits; + $this->path = $this->path != '/' ? rtrim($this->path, '/') . '/' : $this->path; + $this->items = $items instanceof Collection ? $items : Collection::make($items); + $this->hits = $hits; } + /** * Get the instance as an array. * diff --git a/src/ElasticquentResultCollection.php b/src/ElasticquentResultCollection.php index 100ede6..cee4f8e 100644 --- a/src/ElasticquentResultCollection.php +++ b/src/ElasticquentResultCollection.php @@ -4,21 +4,28 @@ class ElasticquentResultCollection extends \Illuminate\Database\Eloquent\Collection { + protected $took; + protected $timed_out; + protected $shards; + protected $hits; + protected $aggregations = null; + /** * Create a new instance containing Elasticsearch results * - * @todo Remove backwards compatible detection at further point + * @todo Remove backwards compatible detection at further point * @deprecated Initialize with params ($results, $instance) is deprecated, * please use Model::hydrateElasticsearchResult($results). * - * @param mixed $items - * @param array $meta + * @param mixed $items + * @param array $meta + * * @return void */ public function __construct($items, $meta = null) @@ -26,8 +33,8 @@ public function __construct($items, $meta = null) // Detect if arguments are old deprecated version ($results, $instance) if (isset($items['hits']) and $meta instanceof \Illuminate\Database\Eloquent\Model) { $instance = $meta; - $meta = $items; - $items = $instance::hydrateElasticsearchResult($meta); + $meta = $items; + $items = $instance::hydrateElasticsearchResult($meta); } parent::__construct($items); @@ -39,23 +46,26 @@ public function __construct($items, $meta = null) } } + /** * Set the result meta. * * @param array $meta + * * @return $this */ public function setMeta(array $meta) { - $this->took = isset($meta['took']) ? $meta['took'] : null; - $this->timed_out = isset($meta['timed_out']) ? $meta['timed_out'] : null; - $this->shards = isset($meta['_shards']) ? $meta['_shards'] : null; - $this->hits = isset($meta['hits']) ? $meta['hits'] : null; + $this->took = isset($meta['took']) ? $meta['took'] : null; + $this->timed_out = isset($meta['timed_out']) ? $meta['timed_out'] : null; + $this->shards = isset($meta['_shards']) ? $meta['_shards'] : null; + $this->hits = isset($meta['hits']) ? $meta['hits'] : null; $this->aggregations = isset($meta['aggregations']) ? $meta['aggregations'] : []; return $this; } + /** * Total Hits * @@ -66,6 +76,7 @@ public function totalHits() return $this->hits['total']; } + /** * Max Score * @@ -76,6 +87,7 @@ public function maxScore() return $this->hits['max_score']; } + /** * Get Shards * @@ -86,6 +98,7 @@ public function getShards() return $this->shards; } + /** * Took * @@ -96,6 +109,7 @@ public function took() return $this->took; } + /** * Timed Out * @@ -103,9 +117,10 @@ public function took() */ public function timedOut() { - return (bool) $this->timed_out; + return (bool)$this->timed_out; } + /** * Get Hits * @@ -119,6 +134,7 @@ public function getHits() return $this->hits; } + /** * Get aggregations * @@ -132,6 +148,7 @@ public function getAggregations() return $this->aggregations; } + /** * Paginate Collection * @@ -142,7 +159,8 @@ public function getAggregations() public function paginate($pageLimit = 25) { $page = Paginator::resolveCurrentPage() ?: 1; - - return new Paginator($this->items, $this->hits, $this->totalHits(), $pageLimit, $page, ['path' => Paginator::resolveCurrentPath()]); + + return new Paginator($this->items, $this->hits, $this->totalHits(), $pageLimit, $page, + ['path' => Paginator::resolveCurrentPath()]); } } diff --git a/src/ElasticquentServiceProvider.php b/src/ElasticquentServiceProvider.php index 45958d0..52c608c 100644 --- a/src/ElasticquentServiceProvider.php +++ b/src/ElasticquentServiceProvider.php @@ -6,6 +6,7 @@ class ElasticquentServiceProvider extends ServiceProvider { + /** * Bootstrap services. * @@ -15,11 +16,12 @@ public function boot() { if (ElasticquentSupport::isLaravel5()) { $this->publishes([ - __DIR__.'/config/elasticquent.php' => config_path('elasticquent.php'), + __DIR__ . '/config/elasticquent.php' => config_path('elasticquent.php'), ]); } } + /** * Register services. * diff --git a/src/ElasticquentSupport.php b/src/ElasticquentSupport.php index a4afaed..51f2829 100644 --- a/src/ElasticquentSupport.php +++ b/src/ElasticquentSupport.php @@ -6,8 +6,10 @@ class ElasticquentSupport { + use ElasticquentClientTrait; + public static function isLaravel5() { return version_compare(Application::VERSION, '5', '>'); diff --git a/src/ElasticquentTrait.php b/src/ElasticquentTrait.php index a23e7c4..e6745cf 100644 --- a/src/ElasticquentTrait.php +++ b/src/ElasticquentTrait.php @@ -15,6 +15,7 @@ */ trait ElasticquentTrait { + use ElasticquentClientTrait; /** @@ -53,17 +54,20 @@ trait ElasticquentTrait */ protected $documentVersion = null; + /** * New Collection * * @param array $models + * * @return ElasticquentCollection */ - public function newCollection(array $models = array()) + public function newCollection(array $models = []) { return new ElasticquentCollection($models); } + /** * Get Type Name * @@ -74,6 +78,7 @@ public function getTypeName() return $this->getTable(); } + /** * Uses Timestamps In Index. */ @@ -82,6 +87,7 @@ public function usesTimestampsInIndex() return $this->usesTimestampsInIndex; } + /** * Use Timestamps In Index. */ @@ -90,6 +96,7 @@ public function useTimestampsInIndex($shouldUse = true) $this->usesTimestampsInIndex = $shouldUse; } + /** * Don't Use Timestamps In Index. * @@ -100,6 +107,7 @@ public function dontUseTimestampsInIndex() $this->useTimestampsInIndex(false); } + /** * Get Mapping Properties * @@ -110,10 +118,12 @@ public function getMappingProperties() return $this->mappingProperties; } + /** * Set Mapping Properties * * @param array $mapping + * * @internal param array $mapping */ public function setMappingProperties(array $mapping = null) @@ -121,6 +131,7 @@ public function setMappingProperties(array $mapping = null) $this->mappingProperties = $mapping; } + /** * Get Index Settings * @@ -131,6 +142,7 @@ public function getIndexSettings() return $this->indexSettings; } + /** * Is Elasticsearch Document * @@ -144,6 +156,7 @@ public function isDocument() return $this->isDocument; } + /** * Get Document Score * @@ -154,6 +167,7 @@ public function documentScore() return $this->documentScore; } + /** * Document Version * @@ -164,6 +178,7 @@ public function documentVersion() return $this->documentVersion; } + /** * Get Index Document Data * @@ -177,6 +192,7 @@ public function getIndexDocumentData() return $this->toArray(); } + /** * Index Documents * @@ -188,11 +204,12 @@ public static function addAllToIndex() { $instance = new static; - $all = $instance->newQuery()->get(array('*')); + $all = $instance->newQuery()->get(['*']); return $all->addToIndex(); } + /** * Re-Index All Content * @@ -202,11 +219,12 @@ public static function reindex() { $instance = new static; - $all = $instance->newQuery()->get(array('*')); + $all = $instance->newQuery()->get(['*']); return $all->reindex(); } + /** * Search By Query * @@ -221,25 +239,31 @@ public static function reindex() * * @return ElasticquentResultCollection */ - public static function searchByQuery($query = null, $aggregations = null, $sourceFields = null, $limit = null, $offset = null, $sort = null) - { + public static function searchByQuery( + $query = null, + $aggregations = null, + $sourceFields = null, + $limit = null, + $offset = null, + $sort = null + ) { $instance = new static; $params = $instance->getBasicEsParams(true, true, true, $limit, $offset); - if (!empty($sourceFields)) { + if ( ! empty($sourceFields)) { $params['body']['_source']['include'] = $sourceFields; } - if (!empty($query)) { + if ( ! empty($query)) { $params['body']['query'] = $query; } - if (!empty($aggregations)) { + if ( ! empty($aggregations)) { $params['body']['aggs'] = $aggregations; } - if (!empty($sort)) { + if ( ! empty($sort)) { $params['body']['sort'] = $sort; } @@ -248,12 +272,14 @@ public static function searchByQuery($query = null, $aggregations = null, $sourc return static::hydrateElasticsearchResult($result); } + /** * Perform a "complex" or custom search. * * Using this method, a custom query can be sent to Elasticsearch. * * @param $params parameters to be passed directly to Elasticsearch + * * @return ElasticquentResultCollection */ public static function complexSearch($params) @@ -265,6 +291,7 @@ public static function complexSearch($params) return static::hydrateElasticsearchResult($result); } + /** * Search * @@ -287,6 +314,7 @@ public static function search($term = '') return static::hydrateElasticsearchResult($result); } + /** * Add to Search Index * @@ -295,7 +323,7 @@ public static function search($term = '') */ public function addToIndex() { - if (!$this->exists) { + if ( ! $this->exists) { throw new Exception('Document does not exist.'); } @@ -314,6 +342,7 @@ public function addToIndex() return $this->getElasticSearchClient()->index($params); } + /** * Remove From Search Index * @@ -324,6 +353,7 @@ public function removeFromIndex() return $this->getElasticSearchClient()->delete($this->getBasicEsParams()); } + /** * Partial Update to Indexed Document * @@ -339,6 +369,7 @@ public function updateIndex() return $this->getElasticSearchClient()->update($params); } + /** * Get Search Document * @@ -352,6 +383,7 @@ public function getIndexedDocument() return $this->getElasticSearchClient()->get($this->getBasicEsParams()); } + /** * Get Basic Elasticsearch Params * @@ -366,19 +398,24 @@ public function getIndexedDocument() * * @return array */ - public function getBasicEsParams($getIdIfPossible = true, $getSourceIfPossible = false, $getTimestampIfPossible = false, $limit = null, $offset = null) - { - $params = array( + public function getBasicEsParams( + $getIdIfPossible = true, + $getSourceIfPossible = false, + $getTimestampIfPossible = false, + $limit = null, + $offset = null + ) { + $params = [ 'index' => $this->getIndexName(), - 'type' => $this->getTypeName(), - ); + 'type' => $this->getTypeName(), + ]; if ($getIdIfPossible && $this->getKey()) { $params['id'] = $this->getKey(); } $fields = $this->buildFieldsParameter($getSourceIfPossible, $getTimestampIfPossible); - if (!empty($fields)) { + if ( ! empty($fields)) { $params['fields'] = implode(',', $fields); } @@ -393,16 +430,18 @@ public function getBasicEsParams($getIdIfPossible = true, $getSourceIfPossible = return $params; } + /** * Build the 'fields' parameter depending on given options. * - * @param bool $getSourceIfPossible - * @param bool $getTimestampIfPossible + * @param bool $getSourceIfPossible + * @param bool $getTimestampIfPossible + * * @return array */ private function buildFieldsParameter($getSourceIfPossible, $getTimestampIfPossible) { - $fieldsParam = array(); + $fieldsParam = []; if ($getSourceIfPossible) { $fieldsParam[] = '_source'; @@ -415,6 +454,7 @@ private function buildFieldsParameter($getSourceIfPossible, $getTimestampIfPossi return $fieldsParam; } + /** * Mapping Exists * @@ -429,6 +469,7 @@ public static function mappingExists() return (empty($mapping)) ? false : true; } + /** * Get Mapping * @@ -443,6 +484,7 @@ public static function getMapping() return $instance->getElasticSearchClient()->indices()->getMapping($params); } + /** * Put Mapping. * @@ -456,16 +498,17 @@ public static function putMapping($ignoreConflicts = false) $mapping = $instance->getBasicEsParams(); - $params = array( - '_source' => array('enabled' => true), + $params = [ + '_source' => ['enabled' => true], 'properties' => $instance->getMappingProperties(), - ); + ]; $mapping['body'][$instance->getTypeName()] = $params; return $instance->getElasticSearchClient()->indices()->putMapping($mapping); } + /** * Delete Mapping * @@ -480,6 +523,7 @@ public static function deleteMapping() return $instance->getElasticSearchClient()->indices()->deleteMapping($params); } + /** * Rebuild Mapping * @@ -503,6 +547,7 @@ public static function rebuildMapping() return $instance->putMapping(); } + /** * Create Index * @@ -517,27 +562,27 @@ public static function createIndex($shards = null, $replicas = null) $client = $instance->getElasticSearchClient(); - $index = array( + $index = [ 'index' => $instance->getIndexName(), - ); + ]; $settings = $instance->getIndexSettings(); - if (!is_null($settings)) { + if ( ! is_null($settings)) { $index['body']['settings'] = $settings; } - if (!is_null($shards)) { + if ( ! is_null($shards)) { $index['body']['settings']['number_of_shards'] = $shards; } - if (!is_null($replicas)) { + if ( ! is_null($replicas)) { $index['body']['settings']['number_of_replicas'] = $replicas; } $mappingProperties = $instance->getMappingProperties(); - if (!is_null($mappingProperties)) { + if ( ! is_null($mappingProperties)) { $index['body']['mappings'][$instance->getTypeName()] = [ - '_source' => array('enabled' => true), + '_source' => ['enabled' => true], 'properties' => $mappingProperties, ]; } @@ -545,6 +590,7 @@ public static function createIndex($shards = null, $replicas = null) return $client->indices()->create($index); } + /** * Delete Index * @@ -556,13 +602,14 @@ public static function deleteIndex() $client = $instance->getElasticSearchClient(); - $index = array( + $index = [ 'index' => $instance->getIndexName(), - ); + ]; return $client->indices()->delete($index); } + /** * Type Exists. * @@ -579,6 +626,7 @@ public static function typeExists() return $instance->getElasticSearchClient()->indices()->existsType($params); } + /** * New From Hit Builder * @@ -588,16 +636,16 @@ public static function typeExists() * * @return static */ - public function newFromHitBuilder($hit = array()) + public function newFromHitBuilder($hit = []) { $key_name = $this->getKeyName(); - + $attributes = $hit['_source']; if (isset($hit['_id'])) { $attributes[$key_name] = is_numeric($hit['_id']) ? intval($hit['_id']) : $hit['_id']; } - + // Add fields to attributes if (isset($hit['fields'])) { foreach ($hit['fields'] as $key => $value) { @@ -623,23 +671,28 @@ public function newFromHitBuilder($hit = array()) return $instance; } + /** * Create a elacticquent result collection of models from plain elasticsearch result. * - * @param array $result + * @param array $result + * * @return \Elasticquent\ElasticquentResultCollection */ public static function hydrateElasticsearchResult(array $result) { $items = $result['hits']['hits']; + return static::hydrateElasticquentResult($items, $meta = $result); } + /** * Create a elacticquent result collection of models from plain arrays. * - * @param array $items - * @param array $meta + * @param array $items + * @param array $meta + * * @return \Elasticquent\ElasticquentResultCollection */ public static function hydrateElasticquentResult(array $items, $meta = null) @@ -653,16 +706,21 @@ public static function hydrateElasticquentResult(array $items, $meta = null) return $instance->newElasticquentResultCollection($items, $meta); } + /** * Create a new model instance that is existing recursive. * - * @param \Illuminate\Database\Eloquent\Model $model - * @param array $attributes - * @param \Illuminate\Database\Eloquent\Relations\Relation $parentRelation + * @param \Illuminate\Database\Eloquent\Model $model + * @param array $attributes + * @param \Illuminate\Database\Eloquent\Relations\Relation $parentRelation + * * @return static */ - public static function newFromBuilderRecursive(Model $model, array $attributes = [], Relation $parentRelation = null) - { + public static function newFromBuilderRecursive( + Model $model, + array $attributes = [], + Relation $parentRelation = null + ) { $instance = $model->newInstance([], $exists = true); $instance->setRawAttributes((array)$attributes, $sync = true); @@ -675,12 +733,14 @@ public static function newFromBuilderRecursive(Model $model, array $attributes = return $instance; } + /** * Create a collection of models from plain arrays recursive. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model * @param \Illuminate\Database\Eloquent\Relations\Relation $parentRelation - * @param array $items + * @param array $items + * * @return \Illuminate\Database\Eloquent\Collection */ public static function hydrateRecursive(Model $model, array $items, Relation $parentRelation = null) @@ -690,13 +750,14 @@ public static function hydrateRecursive(Model $model, array $items, Relation $pa $items = array_map(function ($item) use ($instance, $parentRelation) { // Convert all null relations into empty arrays $item = $item ?: []; - + return static::newFromBuilderRecursive($instance, $item, $parentRelation); }, $items); return $instance->newCollection($items); } + /** * Get the relations attributes from a model. * @@ -715,7 +776,7 @@ public static function loadRelationsAttributesRecursive(Model $model) if ($relation instanceof Relation) { // Check if the relation field is single model or collections - if (is_null($value) === true || !static::isMultiLevelArray($value)) { + if (is_null($value) === true || ! static::isMultiLevelArray($value)) { $value = [$value]; } @@ -730,11 +791,12 @@ public static function loadRelationsAttributesRecursive(Model $model) } } + /** * Get the pivot attribute from a model. * - * @param \Illuminate\Database\Eloquent\Model $model - * @param \Illuminate\Database\Eloquent\Relations\Relation $parentRelation + * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Relations\Relation $parentRelation */ public static function loadPivotAttribute(Model $model, Relation $parentRelation = null) { @@ -749,11 +811,13 @@ public static function loadPivotAttribute(Model $model, Relation $parentRelation } } + /** * Create a new Elasticquent Result Collection instance. * - * @param array $models - * @param array $meta + * @param array $models + * @param array $meta + * * @return \Elasticquent\ElasticquentResultCollection */ public function newElasticquentResultCollection(array $models = [], $meta = null) @@ -761,21 +825,24 @@ public function newElasticquentResultCollection(array $models = [], $meta = null return new ElasticquentResultCollection($models, $meta); } + /** * Check if an array is multi-level array like [[id], [id], [id]]. * * For detect if a relation field is single model or collections. * - * @param array $array + * @param array $array + * * @return boolean */ private static function isMultiLevelArray(array $array) { foreach ($array as $key => $value) { - if (!is_array($value)) { + if ( ! is_array($value)) { return false; } } + return true; } } diff --git a/src/config/elasticquent.php b/src/config/elasticquent.php index 7562a61..b894f04 100644 --- a/src/config/elasticquent.php +++ b/src/config/elasticquent.php @@ -1,6 +1,6 @@ [ - 'hosts' => ['localhost:9200'], - 'retries' => 1, + 'hosts' => ['localhost:9200'], + 'retries' => 1, ], /* @@ -29,4 +29,4 @@ 'default_index' => 'my_custom_index_name', -); +]; diff --git a/tests/ElasticSearchMethodsTest.php b/tests/ElasticSearchMethodsTest.php index 2fbd0a9..a6c868c 100644 --- a/tests/ElasticSearchMethodsTest.php +++ b/tests/ElasticSearchMethodsTest.php @@ -14,38 +14,41 @@ * * The Elasticquent method will then format the response and we test that the resulting * Elasticquent results collection methods return the results we expect to verify this. - */ + */ class ElasticSearchMethodsTest extends PHPUnit_Framework_TestCase { + protected $expectedHits = [ - 'total' => 2, - 'max_score' => 0.7768564, - 'hits' => [ - [ - '_index' => 'my_custom_index_name', - '_type' => 'test_table', - '_score' => 0.7768564, - '_source' => [ - 'name' => 'foo', - ] - ], - [ - '_index' => 'my_custom_index_name', - '_type' => 'test_table', - '_score' => 0.5634561, - '_source' => [ - 'name' => 'bar', - ] - ], - ] - ]; + 'total' => 2, + 'max_score' => 0.7768564, + 'hits' => [ + [ + '_index' => 'my_custom_index_name', + '_type' => 'test_table', + '_score' => 0.7768564, + '_source' => [ + 'name' => 'foo', + ] + ], + [ + '_index' => 'my_custom_index_name', + '_type' => 'test_table', + '_score' => 0.5634561, + '_source' => [ + 'name' => 'bar', + ] + ], + ] + ]; + public function setUp() { $this->model = new SearchTestModel; } + public function testSuccessfulSearch() { $result = $this->model->search('with results'); @@ -53,33 +56,35 @@ public function testSuccessfulSearch() $this->assertInstanceOf('Elasticquent\ElasticquentResultCollection', $result); $this->assertEquals(2, $result->totalHits()); $this->assertEquals(0.7768564, $result->maxScore()); - $this->assertEquals(['total' => 5,'successful' => 5,'unsuccessful' => 0], $result->getShards()); + $this->assertEquals(['total' => 5, 'successful' => 5, 'unsuccessful' => 0], $result->getShards()); $this->assertEquals(8, $result->took()); $this->assertFalse($result->timedOut()); $this->assertEquals($this->expectedHits, $result->getHits()); $this->assertEmpty($result->getAggregations()); } + public function testUnsuccessfulSearch() { $result = $this->model->search('with no results'); $expectedHits = [ - 'total' => 0, + 'total' => 0, 'max_score' => null, - 'hits' => [] + 'hits' => [] ]; $this->assertInstanceOf('Elasticquent\ElasticquentResultCollection', $result); $this->assertEquals(0, $result->totalHits()); $this->assertNull($result->maxScore()); - $this->assertEquals(['total' => 5,'successful' => 5,'unsuccessful' => 0], $result->getShards()); + $this->assertEquals(['total' => 5, 'successful' => 5, 'unsuccessful' => 0], $result->getShards()); $this->assertEquals(4, $result->took()); $this->assertFalse($result->timedOut()); $this->assertEquals($expectedHits, $result->getHits()); $this->assertEmpty($result->getAggregations()); } + public function testSearchWithEmptyParamters() { $this->model->search(); @@ -89,6 +94,7 @@ public function testSearchWithEmptyParamters() $this->addToAssertionCount(3); // does not throw an exception } + public function testComplexSearch() { $params = complexParameters(); diff --git a/tests/ElasticquentClientTraitTest.php b/tests/ElasticquentClientTraitTest.php index 34db6c8..a2ee6da 100644 --- a/tests/ElasticquentClientTraitTest.php +++ b/tests/ElasticquentClientTraitTest.php @@ -2,11 +2,13 @@ class ElasticquentClientTraitTest extends PHPUnit_Framework_TestCase { + public function setUp() { $this->model = new TestModel; } + public function testClient() { $this->assertInstanceOf('ElasticSearch\Client', $this->model->getElasticSearchClient()); diff --git a/tests/ElasticquentConfigTraitTest.php b/tests/ElasticquentConfigTraitTest.php index f36da79..307b30a 100644 --- a/tests/ElasticquentConfigTraitTest.php +++ b/tests/ElasticquentConfigTraitTest.php @@ -2,11 +2,13 @@ class ElasticquentConfigTraitTest extends PHPUnit_Framework_TestCase { + public function setUp() { $this->model = new TestModel; } + public function testAccesssToConfig() { $this->assertEquals(['localhost:9200'], $this->model->getElasticConfig('config.hosts')); diff --git a/tests/ElasticquentTraitTest.php b/tests/ElasticquentTraitTest.php index 5939857..b94bfed 100644 --- a/tests/ElasticquentTraitTest.php +++ b/tests/ElasticquentTraitTest.php @@ -1,8 +1,10 @@ 'Test Name']; - public $modelData = array('name' => 'Test Name'); /** * Testing Model @@ -15,6 +17,7 @@ public function setup() $this->model->fill($this->modelData); } + /** * Test type name inferred from table name */ @@ -23,8 +26,9 @@ public function testTypeNameInferredFromTableName() $this->assertEquals('test_table', $this->model->getTypeName()); } + /** - * Test type name overrides table name + * Test type name overrides table name */ public function testTypeNameOverridesTableName() { @@ -32,6 +36,7 @@ public function testTypeNameOverridesTableName() $this->assertEquals('test_type_name', $model->getTypeName()); } + /** * Test Basic Properties Getters */ @@ -44,17 +49,19 @@ public function testBasicPropertiesGetters() $this->assertFalse($this->model->usesTimestampsInIndex()); } + /** * Testing Mapping Setup */ public function testMappingSetup() { - $mapping = array('foo' => 'bar'); + $mapping = ['foo' => 'bar']; $this->model->setMappingProperties($mapping); $this->assertEquals($mapping, $this->model->getMappingProperties()); } + /** * Test Index Document Data */ @@ -67,10 +74,10 @@ public function testIndexDocumentData() $custom = new CustomTestModel(); $custom->fill($this->modelData); - $this->assertEquals( - array('foo' => 'bar'), $custom->getIndexDocumentData()); + $this->assertEquals(['foo' => 'bar'], $custom->getIndexDocumentData()); } + /** * Test Document Null States */ diff --git a/tests/models/CustomTestModel.php b/tests/models/CustomTestModel.php index a348552..1e520dd 100644 --- a/tests/models/CustomTestModel.php +++ b/tests/models/CustomTestModel.php @@ -4,14 +4,16 @@ use Elasticquent\ElasticquentTrait; use Illuminate\Database\Eloquent\Model as Eloquent; -class CustomTestModel extends Eloquent implements ElasticquentInterface { +class CustomTestModel extends Eloquent implements ElasticquentInterface +{ use ElasticquentTrait; - protected $fillable = array('name'); + protected $fillable = ['name']; + function getIndexDocumentData() { - return array('foo' => 'bar'); + return ['foo' => 'bar']; } } diff --git a/tests/models/SearchTestModel.php b/tests/models/SearchTestModel.php index 63d6044..df9eb34 100644 --- a/tests/models/SearchTestModel.php +++ b/tests/models/SearchTestModel.php @@ -7,34 +7,24 @@ class SearchTestModel extends Eloquent implements ElasticquentInterface { + use ElasticquentTrait; protected $table = 'test_table'; + public function getElasticSearchClient() { $elasticClient = m::mock('Elasticsearch\Client'); - $elasticClient - ->shouldReceive('search') - ->with(searchParams('with results')) - ->andReturn(successfulResults()); + $elasticClient->shouldReceive('search')->with(searchParams('with results'))->andReturn(successfulResults()); - $elasticClient - ->shouldReceive('search') - ->with(searchParams('with no results')) - ->andReturn(unsuccessfulResults()); + $elasticClient->shouldReceive('search')->with(searchParams('with no results'))->andReturn(unsuccessfulResults()); - $elasticClient - ->shouldReceive('search') - ->with(searchParams('')) - ->andReturn(unsuccessfulResults()); + $elasticClient->shouldReceive('search')->with(searchParams(''))->andReturn(unsuccessfulResults()); - $elasticClient - ->shouldReceive('search') - ->with(complexParameters()) - ->andReturn(successfulResults()); + $elasticClient->shouldReceive('search')->with(complexParameters())->andReturn(successfulResults()); - return $elasticClient; + return $elasticClient; } } diff --git a/tests/models/TestModel.php b/tests/models/TestModel.php index 5db603e..23a8a3b 100644 --- a/tests/models/TestModel.php +++ b/tests/models/TestModel.php @@ -4,11 +4,12 @@ use Elasticquent\ElasticquentTrait; use Illuminate\Database\Eloquent\Model as Eloquent; -class TestModel extends Eloquent implements ElasticquentInterface { +class TestModel extends Eloquent implements ElasticquentInterface +{ use ElasticquentTrait; protected $table = 'test_table'; - protected $fillable = array('name'); + protected $fillable = ['name']; } \ No newline at end of file diff --git a/tests/models/TestModelWithCustomTypeName.php b/tests/models/TestModelWithCustomTypeName.php index d680de4..1c89dab 100644 --- a/tests/models/TestModelWithCustomTypeName.php +++ b/tests/models/TestModelWithCustomTypeName.php @@ -4,13 +4,15 @@ use Elasticquent\ElasticquentTrait; use Illuminate\Database\Eloquent\Model as Eloquent; -class TestModelWithCustomTypeName extends Eloquent implements ElasticquentInterface { +class TestModelWithCustomTypeName extends Eloquent implements ElasticquentInterface +{ use ElasticquentTrait; protected $table = 'test_table'; - protected $fillable = array('name'); + protected $fillable = ['name']; + public function getTypeName() { diff --git a/tests/stubs/parameters.php b/tests/stubs/parameters.php index 557b1b9..ab37e6e 100644 --- a/tests/stubs/parameters.php +++ b/tests/stubs/parameters.php @@ -8,31 +8,33 @@ function basicParameters() { return [ 'index' => 'my_custom_index_name', - 'type' => 'test_table', + 'type' => 'test_table', ]; } function searchParams($searchTerm) { - $params = basicParameters(); + $params = basicParameters(); $params['body'] = ['query' => ['match' => ['_all' => $searchTerm]]]; + return $params; } function complexParameters() { - $params = basicParameters(); + $params = basicParameters(); $params['body'] = [ 'query' => [ 'filtered' => [ 'filter' => [ - 'term' => [ 'my_field' => 'abc' ] + 'term' => ['my_field' => 'abc'] ], - 'query' => [ - 'match' => [ 'my_other_field' => 'xyz' ] + 'query' => [ + 'match' => ['my_other_field' => 'xyz'] ] ] ] ]; - return $params; + + return $params; } diff --git a/tests/stubs/results.php b/tests/stubs/results.php index 6283a83..036cad5 100644 --- a/tests/stubs/results.php +++ b/tests/stubs/results.php @@ -7,29 +7,29 @@ function successfulResults() { return [ - 'took' => 8, - 'timed_out' => false, - '_shards' => [ - 'total' => 5, - 'successful' => 5, + 'took' => 8, + 'timed_out' => false, + '_shards' => [ + 'total' => 5, + 'successful' => 5, 'unsuccessful' => 0, ], - 'hits' => [ - 'total' => 2, + 'hits' => [ + 'total' => 2, 'max_score' => 0.7768564, - 'hits' => [ + 'hits' => [ [ - '_index' => 'my_custom_index_name', - '_type' => 'test_table', - '_score' => 0.7768564, + '_index' => 'my_custom_index_name', + '_type' => 'test_table', + '_score' => 0.7768564, '_source' => [ 'name' => 'foo', ] ], [ - '_index' => 'my_custom_index_name', - '_type' => 'test_table', - '_score' => 0.5634561, + '_index' => 'my_custom_index_name', + '_type' => 'test_table', + '_score' => 0.5634561, '_source' => [ 'name' => 'bar', ] @@ -43,17 +43,17 @@ function successfulResults() function unsuccessfulResults() { return [ - 'took' => 4, - 'timed_out' => false, - '_shards' => [ - 'total' => 5, - 'successful' => 5, + 'took' => 4, + 'timed_out' => false, + '_shards' => [ + 'total' => 5, + 'successful' => 5, 'unsuccessful' => 0, ], - 'hits' => [ - 'total' => 0, + 'hits' => [ + 'total' => 0, 'max_score' => null, - 'hits' => [], + 'hits' => [], ], 'aggregations' => [], ]; From 84d36b0515e9aa755589ca57c4d349810ed9aa36 Mon Sep 17 00:00:00 2001 From: yuki kato Date: Tue, 26 Jul 2016 17:48:34 +0700 Subject: [PATCH 2/6] Enable to use Amazon Elasticsearch Service with IAM auth --- composer.json | 3 +- src/ElasticquentClientTrait.php | 68 +++++++++++++++++++++++++++++++++ src/config/elasticquent.php | 12 ++++++ 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index a5840c7..6aac809 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,8 @@ "illuminate/database": "~4.2|^5", "illuminate/config": "~4.2|^5", "nesbot/carbon": "~1.0", - "elasticsearch/elasticsearch": ">1.0 <2.2" + "elasticsearch/elasticsearch": ">1.0 <2.2", + "aws/aws-sdk-php": "^3.18" }, "require-dev": { "phpunit/phpunit": "~4.2|~5.0", diff --git a/src/ElasticquentClientTrait.php b/src/ElasticquentClientTrait.php index 8dbecbe..878db3f 100644 --- a/src/ElasticquentClientTrait.php +++ b/src/ElasticquentClientTrait.php @@ -2,6 +2,13 @@ namespace Elasticquent; +use GuzzleHttp\Psr7\Request; +use Aws\Signature\SignatureV4; +use Aws\Credentials\Credentials; +use GuzzleHttp\Ring\Future\CompletedFutureArray; +use GuzzleHttp\Psr7\Uri; +use Psr\Http\Message\ResponseInterface; + trait ElasticquentClientTrait { @@ -19,6 +26,13 @@ public function getElasticSearchClient() // elasticsearch v2.0 using builder if (class_exists('\Elasticsearch\ClientBuilder')) { + $awsConfig = $this->getElasticConfig('aws'); + if ( ! empty($awsConfig) && array_get($this->getElasticConfig('aws'), 'iam', false)) { + if ($handler = $this->getAwsESHandler()) { + array_set($config, 'handler', $handler); + } + } + return \Elasticsearch\ClientBuilder::fromConfig($config); } @@ -26,4 +40,58 @@ public function getElasticSearchClient() return new \Elasticsearch\Client($config); } + + /** + * @return bool|\Closure + */ + private function getAwsESHandler() + { + $awsConfig = $this->getElasticConfig('aws'); + if (empty($awsConfig)) { + return false; + } + + $key = array_get($awsConfig, 'key'); + $secret = array_get($awsConfig, 'secret'); + $region = array_get($awsConfig, 'region', 'us-west-2'); + + $psr7Handler = \Aws\default_http_handler(); + $signer = new SignatureV4('es', $region); + + $handler = function (array $request) use ( + $psr7Handler, + $signer, + $key, + $secret + ) { + // Amazon ES listens on standard ports (443 for HTTPS, 80 for HTTP). + $request['headers']['host'][0] = parse_url($request['headers']['host'][0], PHP_URL_HOST); + + $credentials = new Credentials($key, $secret); + + // Create a PSR-7 request from the array passed to the handler + $psr7Request = new Request($request['http_method'], + (new Uri($request['uri']))->withScheme($request['scheme'])->withHost($request['headers']['host'][0]), + $request['headers'], $request['body']); + + // Sign the PSR-7 request with credentials from the environment + $signedRequest = $signer->signRequest($psr7Request, $credentials); + + // Send the signed request to Amazon ES + /** @var ResponseInterface $response */ + $response = $psr7Handler($signedRequest)->wait(); + + // Convert the PSR-7 response to a RingPHP response + return new CompletedFutureArray([ + 'status' => $response->getStatusCode(), + 'headers' => $response->getHeaders(), + 'body' => $response->getBody()->detach(), + 'transfer_stats' => ['total_time' => 0], + 'effective_url' => (string)$psr7Request->getUri(), + ]); + }; + + return $handler; + } + } diff --git a/src/config/elasticquent.php b/src/config/elasticquent.php index b894f04..dfa37de 100644 --- a/src/config/elasticquent.php +++ b/src/config/elasticquent.php @@ -29,4 +29,16 @@ 'default_index' => 'my_custom_index_name', + /* + |-------------------------------------------------------------------------- + | Enable to use Amazon Elasticsearch Service + |-------------------------------------------------------------------------- + */ + 'aws' => [ + 'iam' => true, + 'key' => 'YOUR_AWS_KEY', + 'secret' => 'YOUR_AWS_SECRET', + 'region' => 'us-west-2', + ] + ]; From 7709f6b3f2655f00b6e13d8fa55bd320bf2e10a4 Mon Sep 17 00:00:00 2001 From: yuki kato Date: Fri, 14 Oct 2016 11:46:45 +0900 Subject: [PATCH 3/6] Add php-cs-fixer config, code formatted --- .php_cs | 65 ++++++++++ src/ElasticquentClientTrait.php | 14 +- src/ElasticquentCollection.php | 8 +- src/ElasticquentCollectionTrait.php | 19 ++- src/ElasticquentConfigTrait.php | 20 ++- src/ElasticquentElasticsearchFacade.php | 1 - src/ElasticquentInterface.php | 59 +++------ src/ElasticquentPaginator.php | 18 +-- src/ElasticquentResultCollection.php | 47 +++---- src/ElasticquentServiceProvider.php | 4 +- src/ElasticquentSupport.php | 2 - src/ElasticquentTrait.php | 129 +++++++------------ src/config/elasticquent.php | 2 +- tests/ElasticSearchMethodsTest.php | 14 +- tests/ElasticquentClientTraitTest.php | 2 - tests/ElasticquentConfigTraitTest.php | 2 - tests/ElasticquentTraitTest.php | 23 +--- tests/models/CustomTestModel.php | 4 +- tests/models/SearchTestModel.php | 2 - tests/models/TestModel.php | 3 +- tests/models/TestModelWithCustomTypeName.php | 4 +- tests/stubs/parameters.php | 14 +- tests/stubs/results.php | 6 +- 23 files changed, 208 insertions(+), 254 deletions(-) create mode 100644 .php_cs diff --git a/.php_cs b/.php_cs new file mode 100644 index 0000000..225393f --- /dev/null +++ b/.php_cs @@ -0,0 +1,65 @@ +notPath('bootstrap/cache') + ->notPath('storage') + ->notPath('vendor') + ->in(__DIR__) + ->name('*.php') + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +$fixers = [ + '-psr0', + '-php_closing_tag', + 'blankline_after_open_tag', + 'concat_without_spaces', + 'double_arrow_multiline_whitespaces', + 'duplicate_semicolon', + 'empty_return', + 'extra_empty_lines', + 'include', + 'join_function', + 'list_commas', + 'multiline_array_trailing_comma', + 'namespace_no_leading_whitespace', + 'newline_after_open_tag', + 'no_blank_lines_after_class_opening', + 'no_empty_lines_after_phpdocs', + 'object_operator', + 'operators_spaces', + 'phpdoc_indent', + 'phpdoc_no_access', + 'phpdoc_no_package', + 'phpdoc_scalar', + 'phpdoc_short_description', + 'phpdoc_to_comment', + 'phpdoc_trim', + 'phpdoc_type_to_var', + 'phpdoc_var_without_name', + 'remove_leading_slash_use', + 'remove_lines_between_uses', + 'return', + 'self_accessor', + 'single_array_no_trailing_comma', + 'single_blank_line_before_namespace', + 'single_quote', + 'spaces_before_semicolon', + 'spaces_cast', + 'standardize_not_equal', + 'ternary_spaces', + 'trim_array_spaces', + 'unalign_equals', + 'unary_operators_spaces', + 'whitespacy_lines', + 'multiline_spaces_before_semicolon', + 'short_array_syntax', + 'short_echo_tag', +]; + +return Symfony\CS\Config\Config::create() + ->level(Symfony\CS\FixerInterface::PSR2_LEVEL) + ->fixers($fixers) + ->finder($finder) + ->setUsingCache(true); + diff --git a/src/ElasticquentClientTrait.php b/src/ElasticquentClientTrait.php index 878db3f..86d8f1f 100644 --- a/src/ElasticquentClientTrait.php +++ b/src/ElasticquentClientTrait.php @@ -11,12 +11,10 @@ trait ElasticquentClientTrait { - use ElasticquentConfigTrait; - /** - * Get ElasticSearch Client + * Get ElasticSearch Client. * * @return \Elasticsearch\Client */ @@ -27,7 +25,7 @@ public function getElasticSearchClient() // elasticsearch v2.0 using builder if (class_exists('\Elasticsearch\ClientBuilder')) { $awsConfig = $this->getElasticConfig('aws'); - if ( ! empty($awsConfig) && array_get($this->getElasticConfig('aws'), 'iam', false)) { + if (!empty($awsConfig) && array_get($this->getElasticConfig('aws'), 'iam', false)) { if ($handler = $this->getAwsESHandler()) { array_set($config, 'handler', $handler); } @@ -40,7 +38,6 @@ public function getElasticSearchClient() return new \Elasticsearch\Client($config); } - /** * @return bool|\Closure */ @@ -51,12 +48,12 @@ private function getAwsESHandler() return false; } - $key = array_get($awsConfig, 'key'); + $key = array_get($awsConfig, 'key'); $secret = array_get($awsConfig, 'secret'); $region = array_get($awsConfig, 'region', 'us-west-2'); $psr7Handler = \Aws\default_http_handler(); - $signer = new SignatureV4('es', $region); + $signer = new SignatureV4('es', $region); $handler = function (array $request) use ( $psr7Handler, @@ -87,11 +84,10 @@ private function getAwsESHandler() 'headers' => $response->getHeaders(), 'body' => $response->getBody()->detach(), 'transfer_stats' => ['total_time' => 0], - 'effective_url' => (string)$psr7Request->getUri(), + 'effective_url' => (string) $psr7Request->getUri(), ]); }; return $handler; } - } diff --git a/src/ElasticquentCollection.php b/src/ElasticquentCollection.php index f7e41a7..ffe08ac 100644 --- a/src/ElasticquentCollection.php +++ b/src/ElasticquentCollection.php @@ -1,8 +1,8 @@ -isEmpty()) { - return null; + return; } $params = []; @@ -42,9 +42,8 @@ public function addToIndex() return $this->getElasticSearchClient()->bulk($params); } - /** - * Delete From Index + * Delete From Index. * * @return array */ @@ -67,9 +66,8 @@ public function deleteFromIndex() return $this->getElasticSearchClient()->bulk($params); } - /** - * Reindex + * Reindex. * * Delete the items and then re-index them. * @@ -81,5 +79,4 @@ public function reindex() return $this->addToIndex(); } - } diff --git a/src/ElasticquentConfigTrait.php b/src/ElasticquentConfigTrait.php index 9b1fca1..3c181d3 100644 --- a/src/ElasticquentConfigTrait.php +++ b/src/ElasticquentConfigTrait.php @@ -4,9 +4,8 @@ trait ElasticquentConfigTrait { - /** - * Get Index Name + * Get Index Name. * * @return string */ @@ -16,7 +15,7 @@ public function getIndexName() // config file and if there is a default index. $index_name = $this->getElasticConfig('default_index'); - if ( ! empty($index_name)) { + if (!empty($index_name)) { return $index_name; } @@ -24,9 +23,8 @@ public function getIndexName() return 'default'; } - /** - * Get the Elasticquent config + * Get the Elasticquent config. * * @param string $key the configuration key * @param string $prefix filename of configuration file @@ -35,7 +33,7 @@ public function getIndexName() */ public function getElasticConfig($key = 'config', $prefix = 'elasticquent') { - $key = $prefix . ($key ? '.' : '') . $key; + $key = $prefix.($key ? '.' : '').$key; if (function_exists('config')) { // Get config helper for Laravel 5.1+ @@ -51,9 +49,8 @@ public function getElasticConfig($key = 'config', $prefix = 'elasticquent') return $config_helper->get($key); } - /** - * Inject given config file into an instance of Laravel's config + * Inject given config file into an instance of Laravel's config. * * @throws \Exception when the configuration file is not found * @return \Illuminate\Config\Repository configuration repository @@ -62,22 +59,21 @@ protected function getConfigHelper() { $config_file = $this->getConfigFile(); - if ( ! file_exists($config_file)) { + if (!file_exists($config_file)) { throw new \Exception('Config file not found.'); } return new \Illuminate\Config\Repository(['elasticquent' => require($config_file)]); } - /** * Get the config path and file name to use when Laravel framework isn't present - * e.g. using Eloquent stand-alone or running unit tests + * e.g. using Eloquent stand-alone or running unit tests. * * @return string config file path */ protected function getConfigFile() { - return __DIR__ . '/config/elasticquent.php'; + return __DIR__.'/config/elasticquent.php'; } } diff --git a/src/ElasticquentElasticsearchFacade.php b/src/ElasticquentElasticsearchFacade.php index f5a64fe..bcdb911 100644 --- a/src/ElasticquentElasticsearchFacade.php +++ b/src/ElasticquentElasticsearchFacade.php @@ -9,7 +9,6 @@ */ class ElasticquentElasticsearchFacade extends Facade { - /** * Get the registered name of the component. * diff --git a/src/ElasticquentInterface.php b/src/ElasticquentInterface.php index 36cba6b..3a21b64 100644 --- a/src/ElasticquentInterface.php +++ b/src/ElasticquentInterface.php @@ -1,18 +1,18 @@ - $value) { $this->{$key} = $value; } - $this->total = $total; - $this->perPage = $perPage; - $this->lastPage = (int)ceil($total / $perPage); + $this->total = $total; + $this->perPage = $perPage; + $this->lastPage = (int) ceil($total / $perPage); $this->currentPage = $this->setCurrentPage($currentPage, $this->lastPage); - $this->path = $this->path != '/' ? rtrim($this->path, '/') . '/' : $this->path; - $this->items = $items instanceof Collection ? $items : Collection::make($items); - $this->hits = $hits; + $this->path = $this->path != '/' ? rtrim($this->path, '/').'/' : $this->path; + $this->items = $items instanceof Collection ? $items : Collection::make($items); + $this->hits = $hits; } - /** * Get the instance as an array. * diff --git a/src/ElasticquentResultCollection.php b/src/ElasticquentResultCollection.php index cee4f8e..d685d8f 100644 --- a/src/ElasticquentResultCollection.php +++ b/src/ElasticquentResultCollection.php @@ -1,10 +1,11 @@ -took = isset($meta['took']) ? $meta['took'] : null; - $this->timed_out = isset($meta['timed_out']) ? $meta['timed_out'] : null; - $this->shards = isset($meta['_shards']) ? $meta['_shards'] : null; - $this->hits = isset($meta['hits']) ? $meta['hits'] : null; + $this->took = isset($meta['took']) ? $meta['took'] : null; + $this->timed_out = isset($meta['timed_out']) ? $meta['timed_out'] : null; + $this->shards = isset($meta['_shards']) ? $meta['_shards'] : null; + $this->hits = isset($meta['hits']) ? $meta['hits'] : null; $this->aggregations = isset($meta['aggregations']) ? $meta['aggregations'] : []; return $this; } - /** - * Total Hits + * Total Hits. * * @return int */ @@ -76,9 +74,8 @@ public function totalHits() return $this->hits['total']; } - /** - * Max Score + * Max Score. * * @return float */ @@ -87,9 +84,8 @@ public function maxScore() return $this->hits['max_score']; } - /** - * Get Shards + * Get Shards. * * @return array */ @@ -98,9 +94,8 @@ public function getShards() return $this->shards; } - /** - * Took + * Took. * * @return string */ @@ -109,20 +104,18 @@ public function took() return $this->took; } - /** - * Timed Out + * Timed Out. * * @return bool */ public function timedOut() { - return (bool)$this->timed_out; + return (bool) $this->timed_out; } - /** - * Get Hits + * Get Hits. * * Get the raw hits array from * Elasticsearch results. @@ -134,9 +127,8 @@ public function getHits() return $this->hits; } - /** - * Get aggregations + * Get aggregations. * * Get the raw hits array from * Elasticsearch results. @@ -148,9 +140,8 @@ public function getAggregations() return $this->aggregations; } - /** - * Paginate Collection + * Paginate Collection. * * @param int $pageLimit * diff --git a/src/ElasticquentServiceProvider.php b/src/ElasticquentServiceProvider.php index 52c608c..45958d0 100644 --- a/src/ElasticquentServiceProvider.php +++ b/src/ElasticquentServiceProvider.php @@ -6,7 +6,6 @@ class ElasticquentServiceProvider extends ServiceProvider { - /** * Bootstrap services. * @@ -16,12 +15,11 @@ public function boot() { if (ElasticquentSupport::isLaravel5()) { $this->publishes([ - __DIR__ . '/config/elasticquent.php' => config_path('elasticquent.php'), + __DIR__.'/config/elasticquent.php' => config_path('elasticquent.php'), ]); } } - /** * Register services. * diff --git a/src/ElasticquentSupport.php b/src/ElasticquentSupport.php index 51f2829..a4afaed 100644 --- a/src/ElasticquentSupport.php +++ b/src/ElasticquentSupport.php @@ -6,10 +6,8 @@ class ElasticquentSupport { - use ElasticquentClientTrait; - public static function isLaravel5() { return version_compare(Application::VERSION, '5', '>'); diff --git a/src/ElasticquentTrait.php b/src/ElasticquentTrait.php index e6745cf..5f3b93b 100644 --- a/src/ElasticquentTrait.php +++ b/src/ElasticquentTrait.php @@ -8,25 +8,24 @@ use Illuminate\Database\Eloquent\Relations\Relation; /** - * Elasticquent Trait + * Elasticquent Trait. * * Functionality extensions for Elequent that * makes working with Elasticsearch easier. */ trait ElasticquentTrait { - use ElasticquentClientTrait; /** - * Uses Timestamps In Index + * Uses Timestamps In Index. * * @var bool */ protected $usesTimestampsInIndex = true; /** - * Is ES Document + * Is ES Document. * * Set to true when our model is * populated by a @@ -36,7 +35,7 @@ trait ElasticquentTrait protected $isDocument = false; /** - * Document Score + * Document Score. * * Hit score when using data * from Elasticsearch results. @@ -46,7 +45,7 @@ trait ElasticquentTrait protected $documentScore = null; /** - * Document Version + * Document Version. * * Elasticsearch document version. * @@ -54,9 +53,8 @@ trait ElasticquentTrait */ protected $documentVersion = null; - /** - * New Collection + * New Collection. * * @param array $models * @@ -67,9 +65,8 @@ public function newCollection(array $models = []) return new ElasticquentCollection($models); } - /** - * Get Type Name + * Get Type Name. * * @return string */ @@ -78,7 +75,6 @@ public function getTypeName() return $this->getTable(); } - /** * Uses Timestamps In Index. */ @@ -87,7 +83,6 @@ public function usesTimestampsInIndex() return $this->usesTimestampsInIndex; } - /** * Use Timestamps In Index. */ @@ -96,7 +91,6 @@ public function useTimestampsInIndex($shouldUse = true) $this->usesTimestampsInIndex = $shouldUse; } - /** * Don't Use Timestamps In Index. * @@ -107,9 +101,8 @@ public function dontUseTimestampsInIndex() $this->useTimestampsInIndex(false); } - /** - * Get Mapping Properties + * Get Mapping Properties. * * @return array */ @@ -118,9 +111,8 @@ public function getMappingProperties() return $this->mappingProperties; } - /** - * Set Mapping Properties + * Set Mapping Properties. * * @param array $mapping * @@ -131,9 +123,8 @@ public function setMappingProperties(array $mapping = null) $this->mappingProperties = $mapping; } - /** - * Get Index Settings + * Get Index Settings. * * @return array */ @@ -142,9 +133,8 @@ public function getIndexSettings() return $this->indexSettings; } - /** - * Is Elasticsearch Document + * Is Elasticsearch Document. * * Is the data in this module sourced * from an Elasticsearch document source? @@ -156,9 +146,8 @@ public function isDocument() return $this->isDocument; } - /** - * Get Document Score + * Get Document Score. * * @return null|float */ @@ -167,9 +156,8 @@ public function documentScore() return $this->documentScore; } - /** - * Document Version + * Document Version. * * @return null|int */ @@ -178,9 +166,8 @@ public function documentVersion() return $this->documentVersion; } - /** - * Get Index Document Data + * Get Index Document Data. * * Get the data that Elasticsearch will * index for this particular document. @@ -192,9 +179,8 @@ public function getIndexDocumentData() return $this->toArray(); } - /** - * Index Documents + * Index Documents. * * Index all documents in an Eloquent model. * @@ -209,9 +195,8 @@ public static function addAllToIndex() return $all->addToIndex(); } - /** - * Re-Index All Content + * Re-Index All Content. * * @return array */ @@ -224,9 +209,8 @@ public static function reindex() return $all->reindex(); } - /** - * Search By Query + * Search By Query. * * Search with a query array * @@ -251,19 +235,19 @@ public static function searchByQuery( $params = $instance->getBasicEsParams(true, true, true, $limit, $offset); - if ( ! empty($sourceFields)) { + if (!empty($sourceFields)) { $params['body']['_source']['include'] = $sourceFields; } - if ( ! empty($query)) { + if (!empty($query)) { $params['body']['query'] = $query; } - if ( ! empty($aggregations)) { + if (!empty($aggregations)) { $params['body']['aggs'] = $aggregations; } - if ( ! empty($sort)) { + if (!empty($sort)) { $params['body']['sort'] = $sort; } @@ -272,7 +256,6 @@ public static function searchByQuery( return static::hydrateElasticsearchResult($result); } - /** * Perform a "complex" or custom search. * @@ -291,9 +274,8 @@ public static function complexSearch($params) return static::hydrateElasticsearchResult($result); } - /** - * Search + * Search. * * Simple search using a match _all query * @@ -314,16 +296,15 @@ public static function search($term = '') return static::hydrateElasticsearchResult($result); } - /** - * Add to Search Index + * Add to Search Index. * * @throws Exception * @return array */ public function addToIndex() { - if ( ! $this->exists) { + if (!$this->exists) { throw new Exception('Document does not exist.'); } @@ -342,9 +323,8 @@ public function addToIndex() return $this->getElasticSearchClient()->index($params); } - /** - * Remove From Search Index + * Remove From Search Index. * * @return array */ @@ -353,9 +333,8 @@ public function removeFromIndex() return $this->getElasticSearchClient()->delete($this->getBasicEsParams()); } - /** - * Partial Update to Indexed Document + * Partial Update to Indexed Document. * * @return array */ @@ -369,9 +348,8 @@ public function updateIndex() return $this->getElasticSearchClient()->update($params); } - /** - * Get Search Document + * Get Search Document. * * Retrieve an ElasticSearch document * for this entity. @@ -383,9 +361,8 @@ public function getIndexedDocument() return $this->getElasticSearchClient()->get($this->getBasicEsParams()); } - /** - * Get Basic Elasticsearch Params + * Get Basic Elasticsearch Params. * * Most Elasticsearch API calls need the index and * type passed in a parameter array. @@ -415,7 +392,7 @@ public function getBasicEsParams( } $fields = $this->buildFieldsParameter($getSourceIfPossible, $getTimestampIfPossible); - if ( ! empty($fields)) { + if (!empty($fields)) { $params['fields'] = implode(',', $fields); } @@ -430,7 +407,6 @@ public function getBasicEsParams( return $params; } - /** * Build the 'fields' parameter depending on given options. * @@ -454,9 +430,8 @@ private function buildFieldsParameter($getSourceIfPossible, $getTimestampIfPossi return $fieldsParam; } - /** - * Mapping Exists + * Mapping Exists. * * @return bool */ @@ -469,9 +444,8 @@ public static function mappingExists() return (empty($mapping)) ? false : true; } - /** - * Get Mapping + * Get Mapping. * * @return void */ @@ -484,7 +458,6 @@ public static function getMapping() return $instance->getElasticSearchClient()->indices()->getMapping($params); } - /** * Put Mapping. * @@ -508,9 +481,8 @@ public static function putMapping($ignoreConflicts = false) return $instance->getElasticSearchClient()->indices()->putMapping($mapping); } - /** - * Delete Mapping + * Delete Mapping. * * @return array */ @@ -523,9 +495,8 @@ public static function deleteMapping() return $instance->getElasticSearchClient()->indices()->deleteMapping($params); } - /** - * Rebuild Mapping + * Rebuild Mapping. * * This will delete and then re-add * the mapping for this model. @@ -547,9 +518,8 @@ public static function rebuildMapping() return $instance->putMapping(); } - /** - * Create Index + * Create Index. * * @param int $shards * @param int $replicas @@ -567,20 +537,20 @@ public static function createIndex($shards = null, $replicas = null) ]; $settings = $instance->getIndexSettings(); - if ( ! is_null($settings)) { + if (!is_null($settings)) { $index['body']['settings'] = $settings; } - if ( ! is_null($shards)) { + if (!is_null($shards)) { $index['body']['settings']['number_of_shards'] = $shards; } - if ( ! is_null($replicas)) { + if (!is_null($replicas)) { $index['body']['settings']['number_of_replicas'] = $replicas; } $mappingProperties = $instance->getMappingProperties(); - if ( ! is_null($mappingProperties)) { + if (!is_null($mappingProperties)) { $index['body']['mappings'][$instance->getTypeName()] = [ '_source' => ['enabled' => true], 'properties' => $mappingProperties, @@ -590,9 +560,8 @@ public static function createIndex($shards = null, $replicas = null) return $client->indices()->create($index); } - /** - * Delete Index + * Delete Index. * * @return array */ @@ -609,7 +578,6 @@ public static function deleteIndex() return $client->indices()->delete($index); } - /** * Type Exists. * @@ -626,9 +594,8 @@ public static function typeExists() return $instance->getElasticSearchClient()->indices()->existsType($params); } - /** - * New From Hit Builder + * New From Hit Builder. * * Variation on newFromBuilder. Instead, takes * @@ -671,7 +638,6 @@ public function newFromHitBuilder($hit = []) return $instance; } - /** * Create a elacticquent result collection of models from plain elasticsearch result. * @@ -686,7 +652,6 @@ public static function hydrateElasticsearchResult(array $result) return static::hydrateElasticquentResult($items, $meta = $result); } - /** * Create a elacticquent result collection of models from plain arrays. * @@ -706,7 +671,6 @@ public static function hydrateElasticquentResult(array $items, $meta = null) return $instance->newElasticquentResultCollection($items, $meta); } - /** * Create a new model instance that is existing recursive. * @@ -723,7 +687,7 @@ public static function newFromBuilderRecursive( ) { $instance = $model->newInstance([], $exists = true); - $instance->setRawAttributes((array)$attributes, $sync = true); + $instance->setRawAttributes((array) $attributes, $sync = true); // Load relations recursive static::loadRelationsAttributesRecursive($instance); @@ -733,7 +697,6 @@ public static function newFromBuilderRecursive( return $instance; } - /** * Create a collection of models from plain arrays recursive. * @@ -757,7 +720,6 @@ public static function hydrateRecursive(Model $model, array $items, Relation $pa return $instance->newCollection($items); } - /** * Get the relations attributes from a model. * @@ -776,7 +738,7 @@ public static function loadRelationsAttributesRecursive(Model $model) if ($relation instanceof Relation) { // Check if the relation field is single model or collections - if (is_null($value) === true || ! static::isMultiLevelArray($value)) { + if (is_null($value) === true || !static::isMultiLevelArray($value)) { $value = [$value]; } @@ -791,7 +753,6 @@ public static function loadRelationsAttributesRecursive(Model $model) } } - /** * Get the pivot attribute from a model. * @@ -811,7 +772,6 @@ public static function loadPivotAttribute(Model $model, Relation $parentRelation } } - /** * Create a new Elasticquent Result Collection instance. * @@ -825,7 +785,6 @@ public function newElasticquentResultCollection(array $models = [], $meta = null return new ElasticquentResultCollection($models, $meta); } - /** * Check if an array is multi-level array like [[id], [id], [id]]. * @@ -833,12 +792,12 @@ public function newElasticquentResultCollection(array $models = [], $meta = null * * @param array $array * - * @return boolean + * @return bool */ private static function isMultiLevelArray(array $array) { foreach ($array as $key => $value) { - if ( ! is_array($value)) { + if (!is_array($value)) { return false; } } diff --git a/src/config/elasticquent.php b/src/config/elasticquent.php index dfa37de..bf98eb4 100644 --- a/src/config/elasticquent.php +++ b/src/config/elasticquent.php @@ -39,6 +39,6 @@ 'key' => 'YOUR_AWS_KEY', 'secret' => 'YOUR_AWS_SECRET', 'region' => 'us-west-2', - ] + ], ]; diff --git a/tests/ElasticSearchMethodsTest.php b/tests/ElasticSearchMethodsTest.php index a6c868c..6b876d3 100644 --- a/tests/ElasticSearchMethodsTest.php +++ b/tests/ElasticSearchMethodsTest.php @@ -18,7 +18,6 @@ class ElasticSearchMethodsTest extends PHPUnit_Framework_TestCase { - protected $expectedHits = [ 'total' => 2, 'max_score' => 0.7768564, @@ -29,7 +28,7 @@ class ElasticSearchMethodsTest extends PHPUnit_Framework_TestCase '_score' => 0.7768564, '_source' => [ 'name' => 'foo', - ] + ], ], [ '_index' => 'my_custom_index_name', @@ -37,18 +36,16 @@ class ElasticSearchMethodsTest extends PHPUnit_Framework_TestCase '_score' => 0.5634561, '_source' => [ 'name' => 'bar', - ] + ], ], - ] + ], ]; - public function setUp() { $this->model = new SearchTestModel; } - public function testSuccessfulSearch() { $result = $this->model->search('with results'); @@ -63,7 +60,6 @@ public function testSuccessfulSearch() $this->assertEmpty($result->getAggregations()); } - public function testUnsuccessfulSearch() { $result = $this->model->search('with no results'); @@ -71,7 +67,7 @@ public function testUnsuccessfulSearch() $expectedHits = [ 'total' => 0, 'max_score' => null, - 'hits' => [] + 'hits' => [], ]; $this->assertInstanceOf('Elasticquent\ElasticquentResultCollection', $result); @@ -84,7 +80,6 @@ public function testUnsuccessfulSearch() $this->assertEmpty($result->getAggregations()); } - public function testSearchWithEmptyParamters() { $this->model->search(); @@ -94,7 +89,6 @@ public function testSearchWithEmptyParamters() $this->addToAssertionCount(3); // does not throw an exception } - public function testComplexSearch() { $params = complexParameters(); diff --git a/tests/ElasticquentClientTraitTest.php b/tests/ElasticquentClientTraitTest.php index a2ee6da..34db6c8 100644 --- a/tests/ElasticquentClientTraitTest.php +++ b/tests/ElasticquentClientTraitTest.php @@ -2,13 +2,11 @@ class ElasticquentClientTraitTest extends PHPUnit_Framework_TestCase { - public function setUp() { $this->model = new TestModel; } - public function testClient() { $this->assertInstanceOf('ElasticSearch\Client', $this->model->getElasticSearchClient()); diff --git a/tests/ElasticquentConfigTraitTest.php b/tests/ElasticquentConfigTraitTest.php index 307b30a..f36da79 100644 --- a/tests/ElasticquentConfigTraitTest.php +++ b/tests/ElasticquentConfigTraitTest.php @@ -2,13 +2,11 @@ class ElasticquentConfigTraitTest extends PHPUnit_Framework_TestCase { - public function setUp() { $this->model = new TestModel; } - public function testAccesssToConfig() { $this->assertEquals(['localhost:9200'], $this->model->getElasticConfig('config.hosts')); diff --git a/tests/ElasticquentTraitTest.php b/tests/ElasticquentTraitTest.php index b94bfed..c47ed8c 100644 --- a/tests/ElasticquentTraitTest.php +++ b/tests/ElasticquentTraitTest.php @@ -2,12 +2,10 @@ class ElasticquentTraitTest extends PHPUnit_Framework_TestCase { - public $modelData = ['name' => 'Test Name']; - /** - * Testing Model + * Testing Model. * * @return void */ @@ -17,18 +15,16 @@ public function setup() $this->model->fill($this->modelData); } - /** - * Test type name inferred from table name + * Test type name inferred from table name. */ public function testTypeNameInferredFromTableName() { $this->assertEquals('test_table', $this->model->getTypeName()); } - /** - * Test type name overrides table name + * Test type name overrides table name. */ public function testTypeNameOverridesTableName() { @@ -36,9 +32,8 @@ public function testTypeNameOverridesTableName() $this->assertEquals('test_type_name', $model->getTypeName()); } - /** - * Test Basic Properties Getters + * Test Basic Properties Getters. */ public function testBasicPropertiesGetters() { @@ -49,9 +44,8 @@ public function testBasicPropertiesGetters() $this->assertFalse($this->model->usesTimestampsInIndex()); } - /** - * Testing Mapping Setup + * Testing Mapping Setup. */ public function testMappingSetup() { @@ -61,9 +55,8 @@ public function testMappingSetup() $this->assertEquals($mapping, $this->model->getMappingProperties()); } - /** - * Test Index Document Data + * Test Index Document Data. */ public function testIndexDocumentData() { @@ -77,14 +70,12 @@ public function testIndexDocumentData() $this->assertEquals(['foo' => 'bar'], $custom->getIndexDocumentData()); } - /** - * Test Document Null States + * Test Document Null States. */ public function testDocumentNullStates() { $this->assertFalse($this->model->isDocument()); $this->assertNull($this->model->documentScore()); } - } diff --git a/tests/models/CustomTestModel.php b/tests/models/CustomTestModel.php index 1e520dd..1c6836c 100644 --- a/tests/models/CustomTestModel.php +++ b/tests/models/CustomTestModel.php @@ -6,13 +6,11 @@ class CustomTestModel extends Eloquent implements ElasticquentInterface { - use ElasticquentTrait; protected $fillable = ['name']; - - function getIndexDocumentData() + public function getIndexDocumentData() { return ['foo' => 'bar']; } diff --git a/tests/models/SearchTestModel.php b/tests/models/SearchTestModel.php index df9eb34..0432e93 100644 --- a/tests/models/SearchTestModel.php +++ b/tests/models/SearchTestModel.php @@ -7,12 +7,10 @@ class SearchTestModel extends Eloquent implements ElasticquentInterface { - use ElasticquentTrait; protected $table = 'test_table'; - public function getElasticSearchClient() { $elasticClient = m::mock('Elasticsearch\Client'); diff --git a/tests/models/TestModel.php b/tests/models/TestModel.php index 23a8a3b..340368c 100644 --- a/tests/models/TestModel.php +++ b/tests/models/TestModel.php @@ -6,10 +6,9 @@ class TestModel extends Eloquent implements ElasticquentInterface { - use ElasticquentTrait; protected $table = 'test_table'; protected $fillable = ['name']; -} \ No newline at end of file +} diff --git a/tests/models/TestModelWithCustomTypeName.php b/tests/models/TestModelWithCustomTypeName.php index 1c89dab..28c6cdd 100644 --- a/tests/models/TestModelWithCustomTypeName.php +++ b/tests/models/TestModelWithCustomTypeName.php @@ -6,16 +6,14 @@ class TestModelWithCustomTypeName extends Eloquent implements ElasticquentInterface { - use ElasticquentTrait; protected $table = 'test_table'; protected $fillable = ['name']; - public function getTypeName() { return 'test_type_name'; } -} \ No newline at end of file +} diff --git a/tests/stubs/parameters.php b/tests/stubs/parameters.php index ab37e6e..8dd2fd7 100644 --- a/tests/stubs/parameters.php +++ b/tests/stubs/parameters.php @@ -14,7 +14,7 @@ function basicParameters() function searchParams($searchTerm) { - $params = basicParameters(); + $params = basicParameters(); $params['body'] = ['query' => ['match' => ['_all' => $searchTerm]]]; return $params; @@ -22,18 +22,18 @@ function searchParams($searchTerm) function complexParameters() { - $params = basicParameters(); + $params = basicParameters(); $params['body'] = [ 'query' => [ 'filtered' => [ 'filter' => [ - 'term' => ['my_field' => 'abc'] + 'term' => ['my_field' => 'abc'], ], 'query' => [ - 'match' => ['my_other_field' => 'xyz'] - ] - ] - ] + 'match' => ['my_other_field' => 'xyz'], + ], + ], + ], ]; return $params; diff --git a/tests/stubs/results.php b/tests/stubs/results.php index 036cad5..93d63d9 100644 --- a/tests/stubs/results.php +++ b/tests/stubs/results.php @@ -24,7 +24,7 @@ function successfulResults() '_score' => 0.7768564, '_source' => [ 'name' => 'foo', - ] + ], ], [ '_index' => 'my_custom_index_name', @@ -32,7 +32,7 @@ function successfulResults() '_score' => 0.5634561, '_source' => [ 'name' => 'bar', - ] + ], ], ], ], @@ -57,4 +57,4 @@ function unsuccessfulResults() ], 'aggregations' => [], ]; -} \ No newline at end of file +} From 7a7ecf8b012e6d0613dbc181928f5380e8908b1c Mon Sep 17 00:00:00 2001 From: yuki kato Date: Fri, 14 Oct 2016 15:26:50 +0900 Subject: [PATCH 4/6] Add ElasticSearchClientFactory --- src/ElasticSearchClientFactory.php | 104 +++++++++++++++++++++++++++++ src/ElasticquentClientTrait.php | 77 +-------------------- src/ElasticquentTrait.php | 2 +- 3 files changed, 107 insertions(+), 76 deletions(-) create mode 100644 src/ElasticSearchClientFactory.php diff --git a/src/ElasticSearchClientFactory.php b/src/ElasticSearchClientFactory.php new file mode 100644 index 0000000..ce759cf --- /dev/null +++ b/src/ElasticSearchClientFactory.php @@ -0,0 +1,104 @@ +config = $this->getElasticConfig(); + } + + /** + * @return \Elasticsearch\Client + */ + public function getClient() + { + // elasticsearch v2.0 using builder + if (class_exists('\Elasticsearch\ClientBuilder')) { + // elasticsearch v2.0 using builder + $awsConfig = $this->getElasticConfig('aws'); + if (!empty($awsConfig) && array_get($this->getElasticConfig('aws'), 'iam', false)) { + if ($handler = $this->getAwsESHandler()) { + array_set($this->config, 'handler', $handler); + } + } + + return \Elasticsearch\ClientBuilder::fromConfig($this->config); + } + + // elasticsearch v1 + return new \Elasticsearch\Client($this->config); + } + + /** + * @return bool|\Closure + */ + private function getAwsESHandler() + { + $awsConfig = $this->getElasticConfig('aws'); + if (empty($awsConfig)) { + return false; + } + + $key = array_get($awsConfig, 'key'); + $secret = array_get($awsConfig, 'secret'); + $region = array_get($awsConfig, 'region', 'us-west-2'); + + $psr7Handler = \Aws\default_http_handler(); + $signer = new SignatureV4('es', $region); + + $handler = function (array $request) use ( + $psr7Handler, + $signer, + $key, + $secret + ) { + // Amazon ES listens on standard ports (443 for HTTPS, 80 for HTTP). + $request['headers']['host'][0] = parse_url($request['headers']['host'][0], PHP_URL_HOST); + + $credentials = new Credentials($key, $secret); + + // Create a PSR-7 request from the array passed to the handler + $psr7Request = new Request($request['http_method'], + (new Uri($request['uri']))->withScheme($request['scheme'])->withHost($request['headers']['host'][0]), $request['headers'], + $request['body']); + + // Sign the PSR-7 request with credentials from the environment + $signedRequest = $signer->signRequest($psr7Request, $credentials); + + // Send the signed request to Amazon ES + /** @var ResponseInterface $response */ + $response = $psr7Handler($signedRequest)->wait(); + + // Convert the PSR-7 response to a RingPHP response + return new CompletedFutureArray([ + 'status' => $response->getStatusCode(), + 'headers' => $response->getHeaders(), + 'body' => $response->getBody()->detach(), + 'transfer_stats' => ['total_time' => 0], + 'effective_url' => (string) $psr7Request->getUri(), + ]); + }; + + return $handler; + } +} diff --git a/src/ElasticquentClientTrait.php b/src/ElasticquentClientTrait.php index 86d8f1f..6a6d251 100644 --- a/src/ElasticquentClientTrait.php +++ b/src/ElasticquentClientTrait.php @@ -2,13 +2,6 @@ namespace Elasticquent; -use GuzzleHttp\Psr7\Request; -use Aws\Signature\SignatureV4; -use Aws\Credentials\Credentials; -use GuzzleHttp\Ring\Future\CompletedFutureArray; -use GuzzleHttp\Psr7\Uri; -use Psr\Http\Message\ResponseInterface; - trait ElasticquentClientTrait { use ElasticquentConfigTrait; @@ -20,74 +13,8 @@ trait ElasticquentClientTrait */ public function getElasticSearchClient() { - $config = $this->getElasticConfig(); - - // elasticsearch v2.0 using builder - if (class_exists('\Elasticsearch\ClientBuilder')) { - $awsConfig = $this->getElasticConfig('aws'); - if (!empty($awsConfig) && array_get($this->getElasticConfig('aws'), 'iam', false)) { - if ($handler = $this->getAwsESHandler()) { - array_set($config, 'handler', $handler); - } - } - - return \Elasticsearch\ClientBuilder::fromConfig($config); - } - - // elasticsearch v1 - return new \Elasticsearch\Client($config); - } - - /** - * @return bool|\Closure - */ - private function getAwsESHandler() - { - $awsConfig = $this->getElasticConfig('aws'); - if (empty($awsConfig)) { - return false; - } - - $key = array_get($awsConfig, 'key'); - $secret = array_get($awsConfig, 'secret'); - $region = array_get($awsConfig, 'region', 'us-west-2'); - - $psr7Handler = \Aws\default_http_handler(); - $signer = new SignatureV4('es', $region); - - $handler = function (array $request) use ( - $psr7Handler, - $signer, - $key, - $secret - ) { - // Amazon ES listens on standard ports (443 for HTTPS, 80 for HTTP). - $request['headers']['host'][0] = parse_url($request['headers']['host'][0], PHP_URL_HOST); - - $credentials = new Credentials($key, $secret); - - // Create a PSR-7 request from the array passed to the handler - $psr7Request = new Request($request['http_method'], - (new Uri($request['uri']))->withScheme($request['scheme'])->withHost($request['headers']['host'][0]), - $request['headers'], $request['body']); - - // Sign the PSR-7 request with credentials from the environment - $signedRequest = $signer->signRequest($psr7Request, $credentials); - - // Send the signed request to Amazon ES - /** @var ResponseInterface $response */ - $response = $psr7Handler($signedRequest)->wait(); - - // Convert the PSR-7 response to a RingPHP response - return new CompletedFutureArray([ - 'status' => $response->getStatusCode(), - 'headers' => $response->getHeaders(), - 'body' => $response->getBody()->detach(), - 'transfer_stats' => ['total_time' => 0], - 'effective_url' => (string) $psr7Request->getUri(), - ]); - }; + $factory = new ElasticSearchClientFactory(); - return $handler; + return $factory->getClient(); } } diff --git a/src/ElasticquentTrait.php b/src/ElasticquentTrait.php index 5f3b93b..d1a86be 100644 --- a/src/ElasticquentTrait.php +++ b/src/ElasticquentTrait.php @@ -3,9 +3,9 @@ namespace Elasticquent; use Exception; -use ReflectionMethod; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Relation; +use ReflectionMethod; /** * Elasticquent Trait. From 96e65e7b15de982bffcbcc29832fbc5f954b1799 Mon Sep 17 00:00:00 2001 From: yuki kato Date: Tue, 18 Oct 2016 15:08:05 +0900 Subject: [PATCH 5/6] Fix composer.json, check if Amazon SDK installed --- composer.json | 6 +++-- src/ElasticSearchClientFactory.php | 36 ++++++++++++++++++------------ 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/composer.json b/composer.json index 6aac809..0f93cf0 100644 --- a/composer.json +++ b/composer.json @@ -21,13 +21,15 @@ "illuminate/database": "~4.2|^5", "illuminate/config": "~4.2|^5", "nesbot/carbon": "~1.0", - "elasticsearch/elasticsearch": ">1.0 <2.2", - "aws/aws-sdk-php": "^3.18" + "elasticsearch/elasticsearch": ">1.0 <2.2" }, "require-dev": { "phpunit/phpunit": "~4.2|~5.0", "mockery/mockery": "^0.9.4" }, + "suggest": { + "aws/aws-sdk-php": "^3.19" + }, "autoload": { "psr-4": { "Elasticquent\\": "src/" diff --git a/src/ElasticSearchClientFactory.php b/src/ElasticSearchClientFactory.php index ce759cf..609a9cf 100644 --- a/src/ElasticSearchClientFactory.php +++ b/src/ElasticSearchClientFactory.php @@ -2,13 +2,6 @@ namespace Elasticquent; -use Aws\Credentials\Credentials; -use Aws\Signature\SignatureV4; -use GuzzleHttp\Psr7\Request; -use GuzzleHttp\Psr7\Uri; -use GuzzleHttp\Ring\Future\CompletedFutureArray; -use Psr\Http\Message\ResponseInterface; - final class ElasticSearchClientFactory { use ElasticquentConfigTrait; @@ -54,6 +47,21 @@ public function getClient() */ private function getAwsESHandler() { + $classExistsChecks = [ + '\Aws\Credentials\Credentials', + '\Aws\Signature\SignatureV4', + '\GuzzleHttp\Psr7\Request', + '\GuzzleHttp\Psr7\Uri', + '\GuzzleHttp\Ring\Future\CompletedFutureArray', + '\Psr\Http\Message\ResponseInterface', + ]; + + foreach ($classExistsChecks as $classExistsCheck) { + if (!class_exists($classExistsCheck)) { + return false; + } + } + $awsConfig = $this->getElasticConfig('aws'); if (empty($awsConfig)) { return false; @@ -64,7 +72,7 @@ private function getAwsESHandler() $region = array_get($awsConfig, 'region', 'us-west-2'); $psr7Handler = \Aws\default_http_handler(); - $signer = new SignatureV4('es', $region); + $signer = new \Aws\Signature\SignatureV4('es', $region); $handler = function (array $request) use ( $psr7Handler, @@ -75,22 +83,22 @@ private function getAwsESHandler() // Amazon ES listens on standard ports (443 for HTTPS, 80 for HTTP). $request['headers']['host'][0] = parse_url($request['headers']['host'][0], PHP_URL_HOST); - $credentials = new Credentials($key, $secret); + $credentials = new \Aws\Credentials\Credentials($key, $secret); // Create a PSR-7 request from the array passed to the handler - $psr7Request = new Request($request['http_method'], - (new Uri($request['uri']))->withScheme($request['scheme'])->withHost($request['headers']['host'][0]), $request['headers'], - $request['body']); + $psr7Request = new \GuzzleHttp\Psr7\Request($request['http_method'], + (new \GuzzleHttp\Psr7\Uri($request['uri']))->withScheme($request['scheme'])->withHost($request['headers']['host'][0]), + $request['headers'], $request['body']); // Sign the PSR-7 request with credentials from the environment $signedRequest = $signer->signRequest($psr7Request, $credentials); // Send the signed request to Amazon ES - /** @var ResponseInterface $response */ + /** @var \Psr\Http\Message\ResponseInterface $response */ $response = $psr7Handler($signedRequest)->wait(); // Convert the PSR-7 response to a RingPHP response - return new CompletedFutureArray([ + return new \GuzzleHttp\Ring\Future\CompletedFutureArray([ 'status' => $response->getStatusCode(), 'headers' => $response->getHeaders(), 'body' => $response->getBody()->detach(), From 11d4d717476865bb28974dc39c419450adeff39b Mon Sep 17 00:00:00 2001 From: yuki kato Date: Tue, 18 Oct 2016 15:32:46 +0900 Subject: [PATCH 6/6] Fix bug --- src/ElasticSearchClientFactory.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ElasticSearchClientFactory.php b/src/ElasticSearchClientFactory.php index 609a9cf..0673f20 100644 --- a/src/ElasticSearchClientFactory.php +++ b/src/ElasticSearchClientFactory.php @@ -53,7 +53,6 @@ private function getAwsESHandler() '\GuzzleHttp\Psr7\Request', '\GuzzleHttp\Psr7\Uri', '\GuzzleHttp\Ring\Future\CompletedFutureArray', - '\Psr\Http\Message\ResponseInterface', ]; foreach ($classExistsChecks as $classExistsCheck) {