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/composer.json b/composer.json index a5840c7..0f93cf0 100644 --- a/composer.json +++ b/composer.json @@ -27,6 +27,9 @@ "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 new file mode 100644 index 0000000..0673f20 --- /dev/null +++ b/src/ElasticSearchClientFactory.php @@ -0,0 +1,111 @@ +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() + { + $classExistsChecks = [ + '\Aws\Credentials\Credentials', + '\Aws\Signature\SignatureV4', + '\GuzzleHttp\Psr7\Request', + '\GuzzleHttp\Psr7\Uri', + '\GuzzleHttp\Ring\Future\CompletedFutureArray', + ]; + + foreach ($classExistsChecks as $classExistsCheck) { + if (!class_exists($classExistsCheck)) { + return false; + } + } + + $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 \Aws\Signature\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 \Aws\Credentials\Credentials($key, $secret); + + // Create a PSR-7 request from the array passed to the handler + $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 \Psr\Http\Message\ResponseInterface $response */ + $response = $psr7Handler($signedRequest)->wait(); + + // Convert the PSR-7 response to a RingPHP response + return new \GuzzleHttp\Ring\Future\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 63045a5..6a6d251 100644 --- a/src/ElasticquentClientTrait.php +++ b/src/ElasticquentClientTrait.php @@ -7,21 +7,14 @@ trait ElasticquentClientTrait use ElasticquentConfigTrait; /** - * Get ElasticSearch Client + * Get ElasticSearch Client. * * @return \Elasticsearch\Client */ public function getElasticSearchClient() { - $config = $this->getElasticConfig(); + $factory = new ElasticSearchClientFactory(); - // elasticsearch v2.0 using builder - if (class_exists('\Elasticsearch\ClientBuilder')) { - return \Elasticsearch\ClientBuilder::fromConfig($config); - } - - // elasticsearch v1 - return new \Elasticsearch\Client($config); + return $factory->getClient(); } - } 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 = 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(); } @@ -41,7 +43,7 @@ public function addToIndex() } /** - * Delete From Index + * Delete From Index. * * @return array */ @@ -49,23 +51,23 @@ 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 + * Reindex. * * Delete the items and then re-index them. * @@ -74,7 +76,7 @@ public function deleteFromIndex() public function reindex() { $this->deleteFromIndex(); + return $this->addToIndex(); } - } diff --git a/src/ElasticquentConfigTrait.php b/src/ElasticquentConfigTrait.php index 80f8e3f..3c181d3 100644 --- a/src/ElasticquentConfigTrait.php +++ b/src/ElasticquentConfigTrait.php @@ -5,7 +5,7 @@ trait ElasticquentConfigTrait { /** - * Get Index Name + * Get Index Name. * * @return string */ @@ -24,15 +24,16 @@ public function getIndexName() } /** - * Get the Elasticquent config + * 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') { - $key = $prefix . ($key ? '.' : '') . $key; + $key = $prefix.($key ? '.' : '').$key; if (function_exists('config')) { // Get config helper for Laravel 5.1+ @@ -49,7 +50,7 @@ public function getElasticConfig($key = 'config', $prefix = 'elasticquent') } /** - * 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,17 +63,17 @@ protected function getConfigHelper() 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 + * e.g. using Eloquent stand-alone or running unit tests. * - * @return string config file path + * @return string config file path */ protected function getConfigFile() { - return __DIR__ . '/config/elasticquent.php'; + return __DIR__.'/config/elasticquent.php'; } } diff --git a/src/ElasticquentInterface.php b/src/ElasticquentInterface.php index b5ecba7..3a21b64 100644 --- a/src/ElasticquentInterface.php +++ b/src/ElasticquentInterface.php @@ -1,31 +1,34 @@ -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->path = $this->path != '/' ? rtrim($this->path, '/').'/' : $this->path; $this->items = $items instanceof Collection ? $items : Collection::make($items); $this->hits = $hits; } diff --git a/src/ElasticquentResultCollection.php b/src/ElasticquentResultCollection.php index 100ede6..d685d8f 100644 --- a/src/ElasticquentResultCollection.php +++ b/src/ElasticquentResultCollection.php @@ -1,24 +1,31 @@ -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/ElasticquentTrait.php b/src/ElasticquentTrait.php index a23e7c4..d1a86be 100644 --- a/src/ElasticquentTrait.php +++ b/src/ElasticquentTrait.php @@ -3,12 +3,12 @@ namespace Elasticquent; use Exception; -use ReflectionMethod; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Relation; +use ReflectionMethod; /** - * Elasticquent Trait + * Elasticquent Trait. * * Functionality extensions for Elequent that * makes working with Elasticsearch easier. @@ -18,14 +18,14 @@ 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 @@ -35,7 +35,7 @@ trait ElasticquentTrait protected $isDocument = false; /** - * Document Score + * Document Score. * * Hit score when using data * from Elasticsearch results. @@ -45,7 +45,7 @@ trait ElasticquentTrait protected $documentScore = null; /** - * Document Version + * Document Version. * * Elasticsearch document version. * @@ -54,18 +54,19 @@ trait ElasticquentTrait protected $documentVersion = null; /** - * New Collection + * 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 + * Get Type Name. * * @return string */ @@ -101,7 +102,7 @@ public function dontUseTimestampsInIndex() } /** - * Get Mapping Properties + * Get Mapping Properties. * * @return array */ @@ -111,9 +112,10 @@ public function getMappingProperties() } /** - * Set Mapping Properties + * Set Mapping Properties. * * @param array $mapping + * * @internal param array $mapping */ public function setMappingProperties(array $mapping = null) @@ -122,7 +124,7 @@ public function setMappingProperties(array $mapping = null) } /** - * Get Index Settings + * Get Index Settings. * * @return array */ @@ -132,7 +134,7 @@ public function getIndexSettings() } /** - * Is Elasticsearch Document + * Is Elasticsearch Document. * * Is the data in this module sourced * from an Elasticsearch document source? @@ -145,7 +147,7 @@ public function isDocument() } /** - * Get Document Score + * Get Document Score. * * @return null|float */ @@ -155,7 +157,7 @@ public function documentScore() } /** - * Document Version + * Document Version. * * @return null|int */ @@ -165,7 +167,7 @@ public function documentVersion() } /** - * Get Index Document Data + * Get Index Document Data. * * Get the data that Elasticsearch will * index for this particular document. @@ -178,7 +180,7 @@ public function getIndexDocumentData() } /** - * Index Documents + * Index Documents. * * Index all documents in an Eloquent model. * @@ -188,13 +190,13 @@ public static function addAllToIndex() { $instance = new static; - $all = $instance->newQuery()->get(array('*')); + $all = $instance->newQuery()->get(['*']); return $all->addToIndex(); } /** - * Re-Index All Content + * Re-Index All Content. * * @return array */ @@ -202,13 +204,13 @@ public static function reindex() { $instance = new static; - $all = $instance->newQuery()->get(array('*')); + $all = $instance->newQuery()->get(['*']); return $all->reindex(); } /** - * Search By Query + * Search By Query. * * Search with a query array * @@ -221,8 +223,14 @@ 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); @@ -254,6 +262,7 @@ public static function searchByQuery($query = null, $aggregations = null, $sourc * 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) @@ -266,7 +275,7 @@ public static function complexSearch($params) } /** - * Search + * Search. * * Simple search using a match _all query * @@ -288,7 +297,7 @@ public static function search($term = '') } /** - * Add to Search Index + * Add to Search Index. * * @throws Exception * @return array @@ -315,7 +324,7 @@ public function addToIndex() } /** - * Remove From Search Index + * Remove From Search Index. * * @return array */ @@ -325,7 +334,7 @@ public function removeFromIndex() } /** - * Partial Update to Indexed Document + * Partial Update to Indexed Document. * * @return array */ @@ -340,7 +349,7 @@ public function updateIndex() } /** - * Get Search Document + * Get Search Document. * * Retrieve an ElasticSearch document * for this entity. @@ -353,7 +362,7 @@ public function getIndexedDocument() } /** - * Get Basic Elasticsearch Params + * Get Basic Elasticsearch Params. * * Most Elasticsearch API calls need the index and * type passed in a parameter array. @@ -366,12 +375,17 @@ 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(); @@ -396,13 +410,14 @@ public function getBasicEsParams($getIdIfPossible = true, $getSourceIfPossible = /** * 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'; @@ -416,7 +431,7 @@ private function buildFieldsParameter($getSourceIfPossible, $getTimestampIfPossi } /** - * Mapping Exists + * Mapping Exists. * * @return bool */ @@ -430,7 +445,7 @@ public static function mappingExists() } /** - * Get Mapping + * Get Mapping. * * @return void */ @@ -456,10 +471,10 @@ 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; @@ -467,7 +482,7 @@ public static function putMapping($ignoreConflicts = false) } /** - * Delete Mapping + * Delete Mapping. * * @return array */ @@ -481,7 +496,7 @@ public static function deleteMapping() } /** - * Rebuild Mapping + * Rebuild Mapping. * * This will delete and then re-add * the mapping for this model. @@ -504,7 +519,7 @@ public static function rebuildMapping() } /** - * Create Index + * Create Index. * * @param int $shards * @param int $replicas @@ -517,9 +532,9 @@ public static function createIndex($shards = null, $replicas = null) $client = $instance->getElasticSearchClient(); - $index = array( + $index = [ 'index' => $instance->getIndexName(), - ); + ]; $settings = $instance->getIndexSettings(); if (!is_null($settings)) { @@ -537,7 +552,7 @@ public static function createIndex($shards = null, $replicas = null) $mappingProperties = $instance->getMappingProperties(); if (!is_null($mappingProperties)) { $index['body']['mappings'][$instance->getTypeName()] = [ - '_source' => array('enabled' => true), + '_source' => ['enabled' => true], 'properties' => $mappingProperties, ]; } @@ -546,7 +561,7 @@ public static function createIndex($shards = null, $replicas = null) } /** - * Delete Index + * Delete Index. * * @return array */ @@ -556,9 +571,9 @@ public static function deleteIndex() $client = $instance->getElasticSearchClient(); - $index = array( + $index = [ 'index' => $instance->getIndexName(), - ); + ]; return $client->indices()->delete($index); } @@ -580,7 +595,7 @@ public static function typeExists() } /** - * New From Hit Builder + * New From Hit Builder. * * Variation on newFromBuilder. Instead, takes * @@ -588,16 +603,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) { @@ -626,20 +641,23 @@ public function newFromHitBuilder($hit = array()) /** * 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) @@ -656,16 +674,20 @@ public static function hydrateElasticquentResult(array $items, $meta = null) /** * 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); + $instance->setRawAttributes((array) $attributes, $sync = true); // Load relations recursive static::loadRelationsAttributesRecursive($instance); @@ -678,9 +700,10 @@ public static function newFromBuilderRecursive(Model $model, array $attributes = /** * 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,7 +713,7 @@ 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); @@ -733,8 +756,8 @@ 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) { @@ -752,8 +775,9 @@ 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) @@ -766,8 +790,9 @@ public function newElasticquentResultCollection(array $models = [], $meta = null * * For detect if a relation field is single model or collections. * - * @param array $array - * @return boolean + * @param array $array + * + * @return bool */ private static function isMultiLevelArray(array $array) { @@ -776,6 +801,7 @@ private static function isMultiLevelArray(array $array) return false; } } + return true; } } diff --git a/src/config/elasticquent.php b/src/config/elasticquent.php index 7562a61..bf98eb4 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,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', + ], + +]; diff --git a/tests/ElasticSearchMethodsTest.php b/tests/ElasticSearchMethodsTest.php index 2fbd0a9..6b876d3 100644 --- a/tests/ElasticSearchMethodsTest.php +++ b/tests/ElasticSearchMethodsTest.php @@ -14,32 +14,32 @@ * * 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', - ] + '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', - ] + ], + [ + '_index' => 'my_custom_index_name', + '_type' => 'test_table', + '_score' => 0.5634561, + '_source' => [ + 'name' => 'bar', ], - ] - ]; + ], + ], + ]; public function setUp() { @@ -53,7 +53,7 @@ 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()); @@ -65,15 +65,15 @@ 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()); diff --git a/tests/ElasticquentTraitTest.php b/tests/ElasticquentTraitTest.php index 5939857..c47ed8c 100644 --- a/tests/ElasticquentTraitTest.php +++ b/tests/ElasticquentTraitTest.php @@ -1,11 +1,11 @@ 'Test Name'); +class ElasticquentTraitTest extends PHPUnit_Framework_TestCase +{ + public $modelData = ['name' => 'Test Name']; /** - * Testing Model + * Testing Model. * * @return void */ @@ -16,7 +16,7 @@ public function setup() } /** - * Test type name inferred from table name + * Test type name inferred from table name. */ public function testTypeNameInferredFromTableName() { @@ -24,7 +24,7 @@ public function testTypeNameInferredFromTableName() } /** - * Test type name overrides table name + * Test type name overrides table name. */ public function testTypeNameOverridesTableName() { @@ -33,7 +33,7 @@ public function testTypeNameOverridesTableName() } /** - * Test Basic Properties Getters + * Test Basic Properties Getters. */ public function testBasicPropertiesGetters() { @@ -45,18 +45,18 @@ public function testBasicPropertiesGetters() } /** - * Testing Mapping Setup + * 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 + * Test Index Document Data. */ public function testIndexDocumentData() { @@ -67,17 +67,15 @@ 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 + * 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 a348552..1c6836c 100644 --- a/tests/models/CustomTestModel.php +++ b/tests/models/CustomTestModel.php @@ -4,14 +4,14 @@ 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() + public function getIndexDocumentData() { - return array('foo' => 'bar'); + return ['foo' => 'bar']; } } diff --git a/tests/models/SearchTestModel.php b/tests/models/SearchTestModel.php index 63d6044..0432e93 100644 --- a/tests/models/SearchTestModel.php +++ b/tests/models/SearchTestModel.php @@ -15,26 +15,14 @@ public function getElasticSearchClient() { $elasticClient = m::mock('Elasticsearch\Client'); - $elasticClient - ->shouldReceive('search') - ->with(searchParams('with results')) - ->andReturn(successfulResults()); - - $elasticClient - ->shouldReceive('search') - ->with(searchParams('with no results')) - ->andReturn(unsuccessfulResults()); - - $elasticClient - ->shouldReceive('search') - ->with(searchParams('')) - ->andReturn(unsuccessfulResults()); - - $elasticClient - ->shouldReceive('search') - ->with(complexParameters()) - ->andReturn(successfulResults()); - - return $elasticClient; + $elasticClient->shouldReceive('search')->with(searchParams('with results'))->andReturn(successfulResults()); + + $elasticClient->shouldReceive('search')->with(searchParams('with no results'))->andReturn(unsuccessfulResults()); + + $elasticClient->shouldReceive('search')->with(searchParams(''))->andReturn(unsuccessfulResults()); + + $elasticClient->shouldReceive('search')->with(complexParameters())->andReturn(successfulResults()); + + return $elasticClient; } } diff --git a/tests/models/TestModel.php b/tests/models/TestModel.php index 5db603e..340368c 100644 --- a/tests/models/TestModel.php +++ b/tests/models/TestModel.php @@ -4,11 +4,11 @@ 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'); -} \ No newline at end of file + protected $fillable = ['name']; +} diff --git a/tests/models/TestModelWithCustomTypeName.php b/tests/models/TestModelWithCustomTypeName.php index d680de4..28c6cdd 100644 --- a/tests/models/TestModelWithCustomTypeName.php +++ b/tests/models/TestModelWithCustomTypeName.php @@ -4,16 +4,16 @@ 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() { return 'test_type_name'; } -} \ No newline at end of file +} diff --git a/tests/stubs/parameters.php b/tests/stubs/parameters.php index 557b1b9..8dd2fd7 100644 --- a/tests/stubs/parameters.php +++ b/tests/stubs/parameters.php @@ -8,7 +8,7 @@ function basicParameters() { return [ 'index' => 'my_custom_index_name', - 'type' => 'test_table', + 'type' => 'test_table', ]; } @@ -16,6 +16,7 @@ function searchParams($searchTerm) { $params = basicParameters(); $params['body'] = ['query' => ['match' => ['_all' => $searchTerm]]]; + return $params; } @@ -26,13 +27,14 @@ function complexParameters() '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..93d63d9 100644 --- a/tests/stubs/results.php +++ b/tests/stubs/results.php @@ -7,32 +7,32 @@ 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,18 +43,18 @@ 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' => [], ]; -} \ No newline at end of file +}