Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Enalquiler\Modules\Elastica\Handler;
- use Elastica\Request;
- use Elastica\ResultSet;
- use Enalquiler\Core\DI\DIContainer;
- use Enalquiler\Core\Environment\Environment;
- use Enalquiler\Modules\Elastica\Manager\ElasticaQueryBuilder;
- use Enalquiler\Modules\Product\Service\BookingOnline;
- use Enalquiler\Modules\Product\Service\Service;
- use Enalquiler\Modules\Search\Handler\SearchHandlerInterface;
- use Enalquiler\Modules\Search\ListHelper\DataProvider;
- use TextUtilities;
- /**
- * Default search handler.
- *
- * @author Francesc Roldán <francesc@enalquiler.com>
- * */
- class ElasticaSearchHandler implements SearchHandlerInterface
- {
- const ONLY_FULL_PROPERTY = 1;
- const ONLY_ROOMS = 2;
- const NOT_SMOKE_FILTER = 2;
- /**
- * Search params array variable.
- *
- * @var array
- * */
- protected $search_params = [];
- protected $aggregations = [];
- protected $highlight = [];
- protected $queryType = [];
- protected $parameters = [];
- protected $debug = '';
- /**
- * Query builder.
- *
- * @var \Enalquiler\Modules\Elastica\Manager\ElasticaQueryBuilder
- * */
- private $qb;
- /**
- * Logger.
- *
- * @var \Enalquiler\Core\Log\LogInterface
- * */
- private $logger;
- /**
- * @var Environment
- */
- private $environment;
- /**
- * Constructor.
- *
- * @param \Doctrine\Common\Persistence\ManagerRegistry $doctrine
- *
- * @author
- * */
- public function __construct(ElasticaQueryBuilder $qb, $logger)
- {
- $this->qb = $qb;
- $this->logger = $logger;
- }
- /**
- * Execute the search action and returns the result set.
- *
- * @return array An array of search results
- * @throws \Exception
- */
- public function execute()
- {
- if (!$this->qb instanceof ElasticaQueryBuilder) {
- throw new \Exception('Query builder not found');
- }
- if (!isset($this->search_params['searchType']) || !$this->search_params['searchType']) {
- throw new \Exception('Search type not set');
- }
- $results = [];
- switch ($this->search_params['searchType']) {
- case 'search_results':
- $results = $this->getSearchResults();
- break;
- case 'search_province':
- $results = $this->getSearchProvince();
- break;
- case 'boosted_close_locations':
- $results = $this->getBoostedCloseLocations();
- break;
- case 'search_close_locations':
- $results = $this->getSearchCloseLocations();
- break;
- case 'search_provinces':
- $results = $this->getProvinceCounts();
- break;
- case 'search_cities':
- $results = $this->getCityCountsByProvince();
- break;
- case 'search_ajax_ficha':
- $results = $this->getPropertyNavigation();
- break;
- case 'search_total':
- $results = $this->getSearchTotal();
- break;
- case 'provinces_counts':
- $results = $this->getSuggestProvincesCounts();
- break;
- case 'cities_counts':
- $results = $this->getSuggestCitiesCounts();
- break;
- case 'districts_counts':
- $results = $this->getSuggestDistrictsCounts();
- break;
- case 'neighborhoods_counts':
- $results = $this->getSuggestNeighborhoodsCounts();
- break;
- case 'search_last_properties':
- $results = $this->getSearchLastProperties();
- break;
- case 'search_related_properties':
- $results = $this->getSearchRelatedProperties();
- break;
- case 'search_min_price_property':
- $results = $this->getSearchMinPrice();
- break;
- case 'suggest_home':
- $results = $this->getSuggestHome();
- break;
- case 'search_favourites':
- $results = $this->getSearchFavourites();
- break;
- case 'search_boosted_properties':
- $results = $this->getSearchBoostedProperties();
- break;
- case 'search_expert_agency':
- $results = $this->getSearchExpertAgencyProperties();
- break;
- case 'categories_count':
- $results = $this->getSearchCategoriesCounts();
- break;
- case 'capital_province_count':
- $results = $this->getSearchCapitalProvinceCounts();
- break;
- case 'search_alert_properties':
- $results = $this->getSearchAlertProperties();
- break;
- case 'search_api_iphone':
- $results = $this->getSearchApiIphone();
- break;
- case 'search_active_microsite_users':
- $results = $this->getSearchActiveMicrositeUsers();
- break;
- case 'search_min_should_match':
- $results = $this->getSearchMinShouldMatch();
- break;
- case 'search_map':
- $results = $this->getSearchMap();
- break;
- default:
- $results = false;
- }
- return $results;
- }
- public function getFieldPrice($params)
- {
- if (!empty($params['price_type'])) {
- return get_field_price_name($params['price_type']);
- }
- return get_field_price_name(DEFAULT_PRICE_TYPE);
- }
- /**
- * Get params array.
- *
- * @return array returns an key/value array with all search params
- *
- * @author Francesc Roldán <francesc@enalquiler.com>
- * */
- public function getSearchParams()
- {
- return $this->search_params;
- }
- /**
- * Set params array.
- *
- * @param array $params a full set of key/values
- *
- * @return DefaultSearchHandler
- *
- * @author Francesc Roldán <francesc@enalquiler.com>
- * */
- public function setSearchParams(array $params)
- {
- $this->search_params = $params;
- return $this;
- }
- /**
- * Add a param into params array.
- *
- * @param array $param a key/values array
- *
- * @return DefaultSearchHandler
- *
- * @author Francesc Roldán <francesc@enalquiler.com>
- * */
- public function addSearchParam(array $param)
- {
- $this->search_params[\key($param)] = \current($param);
- return $this;
- }
- /**
- * Remove a param from params array.
- *
- * @param string $paramName param name to remove
- *
- * @return DefaultSearchHandler or false if param name not exists
- *
- * @author Francesc Roldán <francesc@enalquiler.com>
- * */
- public function removeSearchParam($paramName)
- {
- if (!isset($this->search_params[$paramName])) {
- return false;
- }
- unset($this->search_params[$paramName]);
- return $this;
- }
- /**
- * Remove all params from params array.
- *
- * @return DefaultSearchHandler
- *
- * @author Francesc Roldán <francesc@enalquiler.com>
- * */
- public function removeSearchParams()
- {
- $this->search_params = [];
- return $this;
- }
- /**
- * Gets the value of qb.
- *
- * @return mixed
- */
- public function getQb()
- {
- return $this->qb;
- }
- /**
- * Sets the value of qb.
- *
- * @param mixed $qb the qb
- *
- * @return self
- */
- public function setQb($qb)
- {
- $this->qb = $qb;
- return $this;
- }
- public function getAggregations()
- {
- return $this->aggregations;
- }
- public function setAggregations($aggregations): void
- {
- $this->aggregations = $aggregations;
- }
- public function getHighlight()
- {
- return $this->highlight;
- }
- public function setHighlight($highlight): void
- {
- $this->highlight = $highlight;
- }
- public function getQueryType()
- {
- return $this->queryType;
- }
- public function setQueryType($queryType): void
- {
- $this->queryType = $queryType;
- }
- public function getParameters()
- {
- return $this->parameters;
- }
- public function setParameters($parameters, $index): void
- {
- $this->parameters = $parameters;
- $this->setAggregations($parameters['elastica']['indexes'][$index]['aggregations']);
- $this->setHighlight($parameters['elastica']['indexes'][$index]['highlight']);
- $this->setQueryTypeOr();
- }
- public function setQueryTypeOrMinShouldMatch(): void
- {
- $this->setQueryType($this->parameters['elastica']['queryType']['queryOrMinShouldMatch']);
- }
- public function setQueryTypeOr(): void
- {
- $this->setQueryType($this->parameters['elastica']['queryType']['queryOr']);
- }
- public function setQueryTypeAnd(): void
- {
- $this->setQueryType($this->parameters['elastica']['queryType']['queryAnd']);
- }
- public function clearDebug(): void
- {
- $this->debug = '';
- }
- public function executeRawPropertySearch(array $query)
- {
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- try {
- if (isset($this->search_params['debug']) && $this->search_params['debug'] && ENV != 'PROD') {
- die(\json_encode($query, JSON_PRETTY_PRINT));
- }
- $results = $indexInstance->search($query);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . \json_encode($query, 1) . ' ' . $e->getMessage());
- return false;
- }
- return $this->processResults($results, []);
- }
- public function getSearchTotal()
- {
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $config = [
- 'size' => 1,
- 'queryFilters' => $queryFilters,
- 'offset' => 0,
- ];
- if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- $results = $this->filteredSearch($config);
- if (!$results instanceof ResultSet) {
- return 0;
- }
- return $results->getTotalHits();
- }
- public function getSearchResults()
- {
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $config = [
- 'size' => (isset($params['size']) && (int) $params['size'] > 0) ? $params['size'] : WEB_NUM_ROWS_PAGE,
- 'queryFilters' => $queryFilters,
- ];
- $config = $this->setQueryAggregations($queryFilters, $config, ['closeLocations']);
- if (!empty($this->search_params['fields'])) {
- $config['fields'] = $this->search_params['fields'];
- }
- if (!empty($params['max_results'])) {
- $config['size'] = $params['max_results'];
- }
- $config['offset'] = 0;
- if (isset($params['page']) && (int) ($params['page']) > 3) {
- $config['offset'] = ($params['page'] - 1) * WEB_NUM_ROWS_PAGE;
- } elseif (isset($params['offset']) && (int) ($params['offset']) > 0) {
- $config['offset'] = $params['offset'];
- }
- if (empty($this->search_params['query_string'])) {
- $config['order'] = 'orden';
- $config['type_order'] = 'asc';
- } else {
- $config['textQuery'] = $this->search_params['query_string'];
- if (isset($params['min_should_match']) && isset($params['cleanAnchor']) && $params['cleanAnchor'] != '') {
- $config['minShouldMatch'] = $params['min_should_match'];
- $config['textQuery'] = $params['cleanAnchor'];
- $this->setQueryTypeOrMinShouldMatch();
- }
- }
- $order = [];
- if (isset($this->search_params['order_booking_online'])) {
- $order = $this->search_params['order_booking_online'];
- }
- $searchParamOrderField = $this->search_params['order_field'];
- $searchParamTypeOrder = $this->search_params['type_order'];
- if (isset($searchParamOrderField) && $searchParamOrderField) {
- $order = $this->orderSearchByFields($searchParamOrderField, $searchParamTypeOrder, $config, $order);
- }
- if (\count($order) > 0) {
- $config['order'] = $order;
- }
- $results = $this->filteredSearch($config);
- return $this->processResults($results, $config);
- }
- public function getSearchLastProperties()
- {
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $size = WEB_NUM_ROWS_PAGE;
- if (isset($params['size']) && $params['size'] > 0) {
- $size = $params['size'];
- }
- $config = [
- 'size' => $size,
- 'queryFilters' => $queryFilters,
- 'offset' => 0,
- 'order' => 'fec_alta',
- 'order_type' => 'desc',
- ];
- $results = $this->filteredSearch($config);
- return $this->processResults($results, $config);
- }
- public function getSearchFavourites()
- {
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $size = WEB_NUM_FAVS_PAGE;
- if (isset($params['size']) && $params['size'] > 0) {
- $size = $params['size'];
- }
- $config = [
- 'size' => $size,
- 'queryFilters' => $queryFilters,
- 'offset' => 0,
- 'order' => 'fec_alta',
- 'order_type' => 'desc',
- ];
- $results = $this->filteredSearch($config);
- return $this->processResults($results, $config);
- }
- public function getSearchCloseLocations()
- {
- if (!isset($this->search_params['max_results']) || !$this->search_params['max_results']) {
- $this->search_params['max_results'] = 20;
- }
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- if (!isset($this->search_params['search_center'])) {
- $lat_lon = $this->getLocationCoords($this->search_params['poblacion']);
- } else {
- $lat_lon = $this->search_params['search_center'];
- }
- $radius = (empty($this->search_params['radius'])) ? 10 : $this->search_params['radius'];
- $config = [
- 'offset' => 0,
- 'size' => $this->search_params['max_results'],
- 'lat_lon' => ['lat' => (float) $lat_lon['latitud'], 'lon' => (float) $lat_lon['longitud']],
- 'order' => ['geo_location.location'],
- 'radius' => $radius,
- ];
- $config = $this->setQueryAggregations(
- $queryFilters,
- $config,
- ['conFoto', 'locations', 'provinces', 'districts', 'neighborhoods']
- );
- $config['queryFilters'] = $config['closeLocations']['queryFilters'];
- if (isset($this->search_params['poblacion']) && $this->search_params['poblacion']) {
- $config['closeLocations']['queryFilters'][] = $this->getCloseLocationsFilter(
- (float) $lat_lon['latitud'],
- (float) $lat_lon['longitud'],
- $radius
- );
- }
- $results = $this->geoSearch($config);
- return $this->processResults($results, $config);
- }
- public function getBoostedCloseLocations()
- {
- if (!isset($this->search_params['max_results']) || !$this->search_params['max_results']) {
- $this->search_params['max_results'] = 15;
- }
- if (empty($this->search_params['radius'])) {
- $this->search_params['radius'] = isset($this->search_params['distritos'])
- && \count(\explode(',', $this->search_params['distritos'])) == 1 ? 5 : 10;
- }
- $params = $this->search_params;
- $onlineBooking = isset($params['online_booking']) && (int) $params['online_booking'] === 1;
- unset($params['online_booking']);
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $lat_lon = $this->removeLocationFilters($params, $queryFilters);
- $config = [
- 'offset' => 0,
- 'size' => $params['max_results'],
- 'lat_lon' => ['lat' => (float) $lat_lon['latitud'], 'lon' => (float) $lat_lon['longitud']],
- 'radius' => $params['radius'],
- ];
- if ($onlineBooking) {
- $config['order'][] = $this->getOnlineBookingSorting();
- }
- if (isset($params['precio_old'])) {
- $config['order'][] = $this->getPriceSorting($params);
- }
- $config['order'][] = $this->getPaymentSorting($params);
- $config['order'][] = 'geo_location.location';
- $config = $this->setQueryAggregations(
- $queryFilters,
- $config,
- ['conFoto', 'locations', 'provinces', 'districts', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
- );
- $config['queryFilters'] = $queryFilters;
- if (isset($params['poblacion']) && $params['poblacion'] && isset($config['closeLocations'])) {
- $config['closeLocations']['queryFilters'][] = $this->getCloseLocationsFilter(
- (float) $lat_lon['latitud'],
- (float) $lat_lon['longitud'],
- $params['radius']
- );
- }
- $results = $this->geoSearch($config);
- return $this->processResults($results, $config);
- }
- public function getSearchMinPrice()
- {
- $params = $this->search_params;
- // hack para evitar mostrar pisos desde 0 euros
- $params['precio_min'] = 100;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $config = [
- 'size' => 1,
- 'queryFilters' => $queryFilters,
- 'offset' => 0,
- 'order' => $this->getFieldPrice($params),
- 'order_type' => 'asc',
- ];
- if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- $results = $this->filteredSearch($config);
- $aInfo = $this->processResults($results, $config);
- return $aInfo;
- }
- public function getSearchMinShouldMatch()
- {
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $this->setQueryTypeOrMinShouldMatch();
- $config = [
- 'size' => 1,
- 'queryFilters' => $queryFilters,
- 'offset' => 0,
- 'minShouldMatch' => $params['minShouldMatch'] ?? 1,
- ];
- if (!empty($this->search_params['query_string'])) {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- $results = $this->filteredSearch($config);
- return $results ? $results->getTotalHits() : 0;
- }
- public function getSearchCategoriesCounts()
- {
- $queryFilters = [];
- $locale = $this->getEnvironment()->getCurrentLanguage();
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder->aggregation([
- 'name' => 'categories',
- 'type' => 'terms',
- 'aggs_type' => 'terms',
- 'size' => 200000,
- 'order' => '_term',
- 'order_type' => 'desc',
- 'filters' => $queryFilters,
- 'field' => 'nombre_categoria_slug_' . $locale . '.raw',
- ]);
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- try {
- $queryResults = $indexInstance->search($queryBuilder->getQuery());
- $aggregations = $queryResults->getAggregations();
- $results = [];
- foreach ($aggregations as $key => $aggregation) {
- foreach ($aggregation['buckets'] as $k => $category) {
- $item = \explode('|', $category['key']);
- if ($item[1] > 0) {
- $results[$item[1]]['doc_count'] = $category['doc_count'];
- $results[$item[1]]['id'] = $item[1];
- $results[$item[1]]['category'] = TextUtilities::reduceUTF8($item[0]);
- }
- }
- }
- return $results;
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- return false;
- }
- }
- public function getSearchProvince()
- {
- if (!isset($this->search_params['max_results']) || !$this->search_params['max_results']) {
- $this->search_params['max_results'] = 150;
- }
- //TODO: use search_params everywhere
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $config = [
- 'offset' => 0,
- 'size' => $this->search_params['max_results'],
- ];
- //$config = $this->_setQueryAggregations($queryFilters, $config, array('conFoto'));
- $config['queryFilters'] = $this->removeFilters(
- $queryFilters,
- ['fk_id_tbl_poblaciones', 'or_distritos', 'or_barrios']
- );
- if (empty($this->search_params['query_string'])) {
- $config['order'] = 'orden';
- $config['order_type'] = 'asc';
- } else {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- if (isset($this->search_params['order_field']) && $this->search_params['order_field']) {
- $config['order'] = \str_replace('alquiler ', '', $this->search_params['order_field']);
- }
- if (isset($this->search_params['type_order']) && $this->search_params['type_order']) {
- $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
- }
- $results = $this->filteredSearch($config);
- $aInfo = $this->processResults($results, $config);
- return $aInfo;
- }
- public function getSearchBoostedProperties()
- {
- $config = [
- 'offset' => 0,
- 'size' => $this->search_params['max_results'],
- ];
- $price_type_field = $this->getFieldPrice($this->search_params);
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => '(doc[\'foto\'].value == 0 || doc[\'fk_id_tbl_distritos\'].value != districts)?70:'
- . '((doc[\'fk_id_tbl_barrios\'].value != neighborhoods)?((doc[\'boosting_multirequest\'].value == 1)?5:50):0) + '
- . '((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 1)?0:'
- . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 0)?10:'
- . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?20:'
- . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == -1)?60:'
- . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?30:'
- . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2)?40:50)'
- . ' )'
- . ' )'
- . ' )'
- . ' )'
- . ')',
- 'type' => 'number',
- 'order' => 'asc',
- 'params' => [
- 'districts' => $this->search_params['distritos'],
- 'neighborhoods' => $this->search_params['barrios'],
- ],
- ],
- ],
- ];
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => 'abs(doc[\'' . $price_type_field . '\'].value - ' . $price_type_field . ')',
- 'type' => 'number',
- 'order' => 'asc',
- 'params' => [
- $price_type_field => (float) ($this->search_params['precio']),
- ],
- ],
- ],
- ];
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => 'abs(doc[\'num_habitaciones\'].value - rooms)',
- 'type' => 'number',
- 'order' => 'asc',
- 'params' => [
- 'rooms' => (int) ($this->search_params['habitaciones']),
- ],
- ],
- ],
- ];
- unset($this->search_params['precio'], $this->search_params['distritos'], $this->search_params['barrios'], $this->search_params['habitaciones']);
- $config['queryFilters'] = $this->getQueryFiltersToSearch($this->search_params);
- $results = $this->filteredSearch($config);
- return $this->processResults($results, $config);
- }
- public function getSearchExpertAgencyProperties()
- {
- $params = $this->search_params;
- $params['con_foto'] = 1;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $config = [
- 'size' => (isset($params['size']) && (int) ($params['size']) > 0) ? $params['size'] : WEB_NUM_ROWS_PAGE,
- 'queryFilters' => $queryFilters,
- ];
- if (!empty($params['max_results'])) {
- $config['size'] = $params['max_results'];
- }
- if (!empty($params['precio_max']) && !empty($params['habitaciones'])) {
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => '(abs(doc[\'' . $this->getFieldPrice($params) . '\'].value - ' . $params['precio_max'] . ') + ((doc[\'num_habitaciones\'].value >= ' . $params['habitaciones'] . ') ? 1 : 0))',
- 'type' => 'number',
- 'order' => 'desc',
- ],
- ],
- ];
- } elseif (!empty($params['precio_max'])) {
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => '(abs(doc[\'' . $this->getFieldPrice($params) . '\'].value - ' . $params['precio_max'] . '))',
- 'type' => 'number',
- 'order' => 'desc',
- ],
- ],
- ];
- } elseif (!empty($params['habitaciones'])) {
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => '((doc[\'num_habitaciones\'].value >= ' . $params['habitaciones'] . ') ? 1 : 0)',
- 'type' => 'number',
- 'order' => 'desc',
- ],
- ],
- ];
- } else {
- $config['order'][] = ['order' => 'orden', 'order_type' => 'asc'];
- }
- $results = $this->filteredSearch($config);
- return $this->processResults($results, $config);
- }
- public function getSearchAlertProperties()
- {
- $config = [
- 'offset' => 0,
- 'size' => (isset($this->search_params['max_results'])) ? $this->search_params['max_results'] : 10,
- ];
- if (isset($this->search_params['order_field'])) {
- if (\is_array($this->search_params['order_field'])) {
- foreach ($this->search_params['order_field'] as $k => $order_field) {
- $config['order'][] = ['order' => $order_field, 'order_type' => (isset($this->search_params['order_type'][$k])) ? $this->search_params['order_type'][$k] : 'asc'];
- }
- } else {
- $config['order'] = $this->search_params['order_field'];
- $config['order_type'] = 'asc';
- if (isset($this->search_params['order_type'])) {
- $config['order_type'] = $this->search_params['order_type'];
- }
- }
- unset($this->search_params['order_field'], $this->search_params['order_type']);
- }
- $config['queryFilters'] = $this->getQueryFiltersToSearch($this->search_params);
- $results = $this->filteredSearch($config);
- return $this->processResults($results, $config);
- }
- public function getSearchRelatedProperties()
- {
- $config = [
- 'offset' => 0,
- 'size' => $this->search_params['max_results'],
- ];
- if (isset($this->search_params['distritos'])) {
- $districts = [];
- if (\is_array($this->search_params['distritos'])) {
- foreach ($this->search_params['distritos'] as $district) {
- $districts[] = 'doc[\'fk_id_tbl_distritos\'].value == ' . $district;
- }
- } else {
- $districts[] = 'doc[\'fk_id_tbl_distritos\'].value == ' . $this->search_params['distritos'];
- }
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => \implode(' || ', $districts) . '?1:0',
- 'type' => 'number',
- 'order' => 'desc',
- ],
- ],
- ];
- }
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => 'doc[\'fk_id_tbl_poblaciones\'].value == ' . $this->search_params['poblacion'] . '?1:0',
- 'type' => 'number',
- 'order' => 'desc',
- ],
- ],
- ];
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => '(doc[\'' . $this->getFieldPrice($this->search_params) . '\'].value <= ' . $this->search_params['precio_max'] . ' && doc[\'' . $this->getFieldPrice($this->search_params) . '\'].value >= ' . $this->search_params['precio_min'] . ')?1:0',
- 'type' => 'number',
- 'order' => 'desc',
- ],
- ],
- ];
- $config['order'][] = [
- 'order' => [
- '_script' => [
- 'script' => 'doc[\'foto\'].value > 0?1:0',
- 'type' => 'number',
- 'order' => 'desc',
- ],
- ],
- ];
- if (!isset($this->search_params['distritos'])) {
- //$config['order'][] = array('order' => 'orden', 'order_type' => 'asc');
- $config['order'][] = ['order' => ['orden' => ['order' => 'asc']]];
- }
- unset($this->search_params['distritos'], $this->search_params['poblacion'], $this->search_params['barrios'], $this->search_params['precio_min'], $this->search_params['precio_max']);
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $config['queryFilters'] = $queryFilters;
- $results = $this->filteredSearch($config);
- $aInfo = $this->processResults($results, $config);
- $aDO = [];
- if (\count($aInfo['searchResults'])) {
- foreach ($aInfo['searchResults'] as $res) {
- $res['url'] = $this->getUrl($res);
- $res['anchor'] = $res['titulo_var'];
- $res['barrio'] = $res['nombre_barrio'];
- $aDO['pk_' . $res['id']] = $res;
- }
- }
- return $aDO;
- }
- public function getSearchActiveMicrositeUsers()
- {
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder->filterAnd($queryFilters);
- $queryBuilder->aggregation(['name' => 'users', 'type' => 'filter', 'aggs_type' => 'terms', 'size' => 200000,
- 'order' => '_term', 'order_type' => 'desc', 'filters' => $queryFilters, 'field' => 'fk_id_tbl_usuarios', ]);
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- $users = [];
- try {
- $queryResults = $indexInstance->search($queryBuilder->getQuery());
- $aggregations = $queryResults->getAggregations();
- foreach ($aggregations['users']['items']['buckets'] as $userInfo) {
- $users[] = $userInfo['key'];
- }
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- return $users;
- }
- public function getSearchApiIphone()
- {
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $config = [
- 'size' => (isset($params['size']) && (int) ($params['size']) > 0) ? $params['size'] : WEB_NUM_ROWS_PAGE,
- 'queryFilters' => $queryFilters,
- ];
- if (isset($params['lat_lon'])) {
- $config['lat_lon'] = $params['lat_lon'];
- }
- if (!isset($this->search_params['radius']) || !$this->search_params['radius']) {
- $this->search_params['radius'] = 10;
- }
- $config = $this->setQueryAggregations($queryFilters, $config);
- if (!empty($this->search_params['fields'])) {
- $config['fields'] = $this->search_params['fields'];
- }
- if (!empty($params['max_results'])) {
- $config['size'] = $params['max_results'];
- }
- if (isset($params['page']) && (int) ($params['page']) > 0) {
- $config['offset'] = ($params['page'] - 1) * WEB_NUM_ROWS_PAGE;
- } else {
- $config['offset'] = 0;
- }
- if (isset($this->search_params['poblacion']) && $this->search_params['poblacion']) {
- $lat_lon = $this->getLocationCoords($this->search_params['poblacion']);
- $config['closeLocations']['queryFilters'][] = $this->getCloseLocationsFilter(
- (float) $lat_lon['latitud'],
- (float) $lat_lon['longitud'],
- $this->search_params['radius']
- );
- }
- if (empty($this->search_params['query_string'])) {
- $config['order'] = 'orden';
- $config['order_type'] = 'asc';
- } else {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- if (isset($this->search_params['order_field']) && $this->search_params['order_field']) {
- $config['order'] = \str_replace('alquiler ', '', $this->search_params['order_field']);
- }
- if (isset($this->search_params['type_order']) && $this->search_params['type_order']) {
- $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
- }
- if (isset($config['lat_lon'])) {
- $results = $this->geoSearch($config);
- } else {
- $results = $this->filteredSearch($config);
- }
- return $this->processResults($results, $config);
- }
- public function getProvinceCounts()
- {
- $locale = $this->getEnvironment()->getCurrentLanguage();
- $queryFilters = [];
- $field = 'nombre_prov_slug';
- if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
- $field .= '_' . $locale;
- }
- $field .= '.raw';
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder->aggregation([
- 'name' => 'provincias',
- 'type' => 'terms',
- 'aggs_type' => 'terms',
- 'size' => 1000,
- 'order' => '_term',
- 'order_type' => 'asc',
- 'filters' => $queryFilters,
- 'field' => $field,
- ]);
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- try {
- $queryResults = $indexInstance->search($queryBuilder->getQuery());
- $aggregations = $queryResults->getAggregations();
- $results = [];
- $results['totals'] = $queryResults->getTotalHits();
- foreach ($aggregations as $key => $aggregation) {
- foreach ($aggregation['buckets'] as $k => $province) {
- $item = \explode('|', $province['key']);
- if ($item[2] > 0) {
- $results[$key]['items'][$item[2]]['doc_count'] = $province['doc_count'];
- $results[$key]['items'][$item[2]]['id'] = $item[2];
- $results[$key]['items'][$item[2]]['name'] = TextUtilities::reduceUTF8($item[1]);
- }
- }
- }
- return $results;
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- return false;
- }
- }
- public function getSuggestProvincesCounts()
- {
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $config = [
- 'queryFilters' => $queryFilters,
- ];
- if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- $excludes = [];
- $this->aggregations['provinces']['exclude'] = [];
- if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
- foreach ($this->languages() as $language) {
- $this->aggregations['provinces_' . $language]['exclude'] = [];
- $excludes[] = 'locations_' . $language;
- }
- }
- $config = $this->setQueryAggregations(
- $queryFilters,
- $config,
- \array_merge(
- $excludes,
- ['locations', 'conFoto', 'closeLocations', 'districts', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
- )
- );
- $results = $this->aggregationSearch($config);
- return $this->processCounts($results, $config);
- }
- public function getSuggestCitiesCounts()
- {
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $config = [
- 'queryFilters' => $queryFilters,
- ];
- if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- $excludes = [];
- $this->aggregations['locations']['exclude'] = [];
- if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
- foreach ($this->languages() as $language) {
- $this->aggregations['locations_' . $language]['exclude'] = [];
- $excludes[] = 'provinces_' . $language;
- }
- }
- $config = $this->setQueryAggregations(
- $queryFilters,
- $config,
- \array_merge(
- $excludes,
- ['provinces', 'conFoto', 'closeLocations', 'districts', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
- )
- );
- $results = $this->aggregationSearch($config);
- return $this->processCounts($results, $config);
- }
- public function getSuggestDistrictsCounts()
- {
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $config = [
- 'queryFilters' => $queryFilters,
- ];
- if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- $this->aggregations['districts']['exclude'] = [];
- $config = $this->setQueryAggregations(
- $queryFilters,
- $config,
- ['provinces', 'locations', 'conFoto', 'closeLocations', 'neighborhoods', 'priceHistogram', 'priceHistogramOverBoundary']
- );
- $results = $this->aggregationSearch($config);
- return $this->processCounts($results, $config);
- }
- public function getSuggestNeighborhoodsCounts()
- {
- $queryFilters = $this->getQueryFiltersToSearch($this->search_params);
- $config = [
- 'queryFilters' => $queryFilters,
- ];
- if (isset($this->search_params['home']) && $this->search_params['home']) {
- $config['home'] = true;
- }
- $config['url'] = 0;
- if (isset($this->search_params['url']) && $this->search_params['url']) {
- $config['url'] = 1;
- }
- if (isset($this->search_params['query_string']) && $this->search_params['query_string']) {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- $this->aggregations['neighborhoods']['exclude'] = [];
- $config = $this->setQueryAggregations(
- $queryFilters,
- $config,
- ['provinces', 'locations', 'conFoto', 'closeLocations', 'districts', 'priceHistogram', 'priceHistogramOverBoundary']
- );
- $results = $this->aggregationSearch($config);
- return $this->processCounts($results, $config);
- }
- public function getSuggestHome()
- {
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder->suggest($this->search_params);
- $results = $this->executeSuggest($queryBuilder);
- return $this->processSuggests($results);
- }
- //Función de la que se nutre el sitemap
- public function getSearchCapitalProvinceCounts()
- {
- $params = $this->search_params;
- $queryFilters = [];
- if (isset($params['tipo']) && $params['tipo'] != 1) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_categorias', 'value' => ['gte' => $params['tipo'],
- 'lte' => $params['tipo'], ]];
- }
- if (isset($params['province_capital'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'province_capital', 'value' => ['gte' => $params['province_capital']]];
- }
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder->aggregation(['name' => 'ciudades', 'type' => 'filter', 'aggs_type' => 'terms', 'field' => 'city.raw',
- 'size' => 1000, 'order' => '_term', 'order_type' => 'asc', 'filters' => $queryFilters, 'field' => 'nombre_pob_slug.raw', ]);
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- try {
- $queryResults = $indexInstance->search($queryBuilder->getQuery());
- $aggregations = $queryResults->getAggregations();
- $results = [];
- foreach ($aggregations as $key => $aggregation) {
- foreach ($aggregation['items']['buckets'] as $k => $city) {
- $item = \explode('|', $city['key']);
- $results[$item[2]]['doc_count'] = $city['doc_count'];
- $results[$item[2]]['fk_id_tbl_poblaciones'] = $item[2];
- $results[$item[2]]['nombre_poblacion'] = TextUtilities::reduceUTF8($item[1]);
- $results[$item[2]]['fk_id_tbl_provincias'] = $item[3];
- }
- }
- return $results;
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- return false;
- }
- }
- //Función de la que se nutre el search1
- public function getCityCountsByProvince()
- {
- $params = $this->search_params;
- $queryFilters = [];
- if (isset($params['tipo']) && $params['tipo'] != 1) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_categorias', 'value' => ['gte' => $params['tipo'],
- 'lte' => $params['tipo'], ]];
- }
- if (isset($params['con_foto'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'foto', 'value' => ['gte' => 1]];
- }
- if (isset($params['precio_max'])) {
- $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['lte' => $params['precio_max']]];
- }
- if (isset($params['amueblado'])) {
- if ($params['amueblado'] == 2) {
- $queryFilters[] = ['type' => 'range', 'field' => 'amueblado', 'value' => ['lte' => 0]];
- } else {
- $queryFilters[] = ['type' => 'range', 'field' => 'amueblado', 'value' => ['gte' => $params['amueblado'],
- 'lte' => $params['amueblado'], ]];
- }
- }
- if (isset($params['habitaciones'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['gte' => $params['habitaciones']]];
- }
- if (isset($params['provincia'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_provincias', 'value' => ['gte' => $params['provincia'],
- 'lte' => $params['provincia'], ]];
- }
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder->aggregation(['name' => 'ciudades', 'type' => 'filter', 'aggs_type' => 'terms', 'field' => 'city.raw',
- 'size' => 1000, 'order' => '_term', 'order_type' => 'asc', 'filters' => $queryFilters, 'field' => 'nombre_pob_slug.raw', ])
- ->aggregation(['name' => 'top_ciudades', 'type' => 'filter', 'aggs_type' => 'terms', 'field' => 'city.raw',
- 'size' => 5, 'order' => '_count', 'order_type' => 'desc', 'filters' => $queryFilters, 'field' => 'nombre_pob_slug.raw', ]);
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- try {
- $queryResults = $indexInstance->search($queryBuilder->getQuery());
- $aggregations = $queryResults->getAggregations();
- $results = [];
- $results['ciudades']['totals'] = $aggregations['ciudades']['doc_count'];
- $results['top_ciudades']['totals'] = $aggregations['top_ciudades']['doc_count'];
- foreach ($aggregations as $key => $aggregation) {
- foreach ($aggregation['items']['buckets'] as $k => $city) {
- $item = \explode('|', $city['key']);
- $results[$key]['items'][$item[2]]['total_inmuebles'] = $city['doc_count'];
- $results[$key]['items'][$item[2]]['fk_id_tbl_poblaciones'] = $item[2];
- $results[$key]['items'][$item[2]]['nombre_pob'] = TextUtilities::reduceUTF8($item[1]);
- $results[$key]['items'][$item[2]]['fk_id_tbl_provincias'] = $params['provincia'];
- }
- }
- return $results;
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- return false;
- }
- }
- public function getPropertyNavigation()
- {
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $config = [
- 'size' => WEB_NUM_ROWS_PAGE + 2,
- 'queryFilters' => $queryFilters,
- ];
- $config['offset'] = $params['offset'];
- //Si nos encontramos en el primer resultado de una paginación retamos al offset una posición
- //para poder obtener el resultado anterior del listado.
- if ($config['offset'] > 0 && ($config['offset'] % WEB_NUM_ROWS_PAGE) === 0) {
- --$config['offset'];
- }
- if (!empty($this->search_params['fields'])) {
- $config['fields'] = $this->search_params['fields'];
- }
- if (empty($this->search_params['query_string'])) {
- $config['order'] = 'orden';
- $config['order_type'] = 'asc';
- } else {
- $config['textQuery'] = $this->search_params['query_string'];
- }
- if (!empty($this->search_params['order_field'])) {
- $config['order'] = \str_replace('alquiler ', '', $this->search_params['order_field']);
- }
- if (!empty($this->search_params['type_order'])) {
- $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
- }
- if (isset($this->search_params['order_booking_online'])) {
- $config['order'] = $this->search_params['order_booking_online'];
- unset($config['order_type']);
- }
- $search = $this->filteredSearch($config);
- $results = $this->processResults($search, $config);
- $total = $results['total'];
- $id = $params['id'];
- $pos = ($params['offset'] < 0) ? 0 : $params['offset'];
- $docs = $results['searchResults'];
- while (\key($docs) != $id) {
- if (\next($docs) === false) {
- \end($docs);
- break;
- }
- ++$pos;
- }
- if (($DO_anterior = \prev($docs)) === false) {
- \reset($docs);
- $DO_siguiente = \next($docs);
- } else {
- \next($docs);
- $DO_siguiente = \next($docs);
- }
- return ['total' => $total, 'position' => $pos, 'prev' => $DO_anterior, 'next' => $DO_siguiente];
- }
- public function getSearchMap()
- {
- $params = $this->search_params;
- $queryFilters = $this->getQueryFiltersToSearch($params);
- $config = [
- 'queryFilters' => $queryFilters,
- 'geoGrid' => [],
- ];
- $results = $this->mapSearch($config);
- return $this->processResults($results, $config);
- }
- public function getQueryFilters($params)
- {
- return $this->getQueryFiltersToSearch($params);
- }
- public function getFilterHackMinPrecio($precio_max)
- {
- include_once PATH_SRC . 'data/daoprog/DAOProg_tbl_filtro_precio.class.php';
- $DAOFiltroPrecio = new \DAOProg_tbl_filtro_precio();
- $DAOFiltroPrecio->selectAllFor(
- DEFAULT_PRICE_TYPE,
- "precio< '" . $precio_max . "' AND indexable = 1 ",
- 'precio DESC',
- 0,
- 1
- );
- if (\count($DAOFiltroPrecio->aDO) == 1) {
- $precioMin = \current($DAOFiltroPrecio->aDO);
- return $precioMin['precio'];
- }
- return 0;
- }
- public function getEnvironment()
- {
- if (null === $this->environment) {
- $this->environment = Environment::getInstance();
- }
- return $this->environment;
- }
- /**
- * @param array $searchParams
- *
- * @return array
- */
- protected function getPriceSorting(array $searchParams)
- {
- $searchParams = $this->search_params;
- $price_type_field = $this->getFieldPrice($searchParams);
- $script = '((doc[\'' . $price_type_field . '\'].value > ' . $searchParams['precio_old'] . ' && doc[\'fk_id_tbl_poblaciones\'].value == ' . $searchParams['poblacion'] . ' )?0:1)';
- if (isset($searchParams['distritos']) && !\strpos(
- $searchParams['distritos'],
- ','
- ) && $searchParams['distritos'] != 0
- ) {
- $script = '((doc[\'' . $price_type_field . '\'].value > ' . $searchParams['precio_old'] . ' && doc[\'fk_id_tbl_distritos\'].value == ' . $searchParams['distritos'] . ' )?0:1)';
- }
- $script .= ' + rint(((doc[\'' . $price_type_field . '\'].value - ' . $searchParams['precio_old'] . ') / ' . $searchParams['precio_old'] . ') * 100) / 100';
- $sorting = [
- '_script' => [
- 'script' => $script,
- 'type' => 'number',
- 'order' => 'asc',
- ],
- ];
- return $sorting;
- }
- /**
- * @return array
- */
- protected function getOnlineBookingSorting()
- {
- $sorting = [
- '_script' => [
- 'script' => "(doc['booking_online'].value == 1) ? 0: 1",
- 'type' => 'number',
- 'order' => 'asc',
- ],
- ];
- return $sorting;
- }
- /**
- * @param $lat
- * @param $lon
- * @param $radius
- *
- * @return mixed
- */
- protected function getCloseLocationsFilter($lat, $lon, $radius)
- {
- if (!isset($radius) || empty($radius) || $radius < 0) {
- $radius = 10;
- }
- $filter = [
- 'type' => 'geo_distance',
- 'field' => 'geo_location.location',
- 'value' => [
- 'distance' => $radius . 'km',
- 'geo_location.location' => [
- 'lat' => $lat,
- 'lon' => $lon,
- ],
- ],
- ];
- return $filter;
- }
- /**
- * @params $searchParams
- *
- * @param $queryFilters
- *
- * @return array
- */
- protected function removeLocationFilters($searchParams, &$queryFilters)
- {
- if (isset($searchParams['distritos']) && \count(\explode(',', $searchParams['distritos'])) == 1) {
- $lat_lon = $this->getDistrictCoords();
- foreach ($queryFilters as $key => $value) {
- if ($value['field'] == 'or_distritos' || $value['field'] == 'or_barrios') {
- unset($queryFilters[$key]);
- }
- }
- } else {
- $lat_lon = $this->getLocationCoords();
- foreach ($queryFilters as $key => $value) {
- if ($value['field'] == 'or_distritos' || $value['field'] == 'or_barrios' || $value['field'] == 'fk_id_tbl_poblaciones') {
- unset($queryFilters[$key]);
- }
- }
- }
- return $lat_lon;
- }
- /**
- * @param $params
- *
- * @return mixed
- */
- protected function getPaymentSorting($params)
- {
- if (isset($params['distritos'])) {
- if (!\is_array($params['distritos'])) {
- $aDistritos = \explode(',', $params['distritos']);
- } else {
- $aDistritos = $params['distritos'];
- }
- $aCondDistritos = [];
- foreach ($aDistritos as $distrito) {
- $aCondDistritos[] = "doc['fk_id_tbl_distritos'].value != " . $distrito;
- }
- $condDistritos = \implode(' && ', $aCondDistritos);
- } else {
- $condDistritos = "doc['fk_id_tbl_distritos'].value != 0";
- }
- if (isset($params['barrios'])) {
- if (!\is_array($params['barrios'])) {
- $aBarrios = \explode(',', $params['barrios']);
- } else {
- $aBarrios = $params['barrios'];
- }
- $aCondBarrios = [];
- foreach ($aBarrios as $barrio) {
- $aCondBarrios[] = "doc['fk_id_tbl_barrios'].value != " . $barrio;
- }
- if (\count(\explode(',', $params['distritos'])) === 1) {
- $aCondBarrios[] = "doc['fk_id_tbl_barrios'].value != 0";
- }
- $condBarrios = \implode(' && ', $aCondBarrios);
- } else {
- $condBarrios = "doc['fk_id_tbl_barrios'].value != 0";
- }
- $sorting = [
- '_script' => [
- 'script' => '((doc[\'foto\'].value == 0 || (' . $condDistritos . '))?70:'
- . '((' . $condBarrios . ')?((doc[\'boosting_multirequest\'].value == 1)?5:50):0)) + '
- . '((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 1)?0:'
- . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == 0)?10:'
- . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?20:'
- . ' ((doc[\'pago\'].value == 1 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2 && doc[\'boosting_multirequest\'].value == -1)?60:'
- . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 1)?30:'
- . ' ((doc[\'pago\'].value == 0 && doc[\'dn_fk_id_tbl_tipo_usuarios\'].value == 2)?40:50)'
- . ' )'
- . ' )'
- . ' )'
- . ' )'
- . ')',
- 'type' => 'number',
- 'order' => 'asc', //,
- ],
- ];
- return $sorting;
- }
- /**
- * @param $searchParamOrderField
- * @param $config
- * @param $order
- * @return array
- */
- protected function orderSearchByFields($searchParamOrderField, $searchParamTypeOrder, $config, $order): array
- {
- if (\is_array($searchParamOrderField)) {
- $orderFieldList = \str_replace('alquiler ', '', $searchParamOrderField);
- } else {
- $orderFieldList = [];
- $orderFieldList[] = \str_replace('alquiler ', '', $searchParamOrderField);
- }
- $searchParamTypeOrderList = $searchParamTypeOrder;
- if (!\is_array($searchParamTypeOrder)) {
- $searchParamTypeOrderList = [$searchParamTypeOrder];
- }
- while (\count($searchParamTypeOrderList) < \count($orderFieldList)) {
- if (isset($this->search_params['type_order']) && $this->search_params['type_order']) {
- $searchParamTypeOrderList[] = $config['order_type'] = \str_replace('alquiler ', '', $this->search_params['type_order']);
- } else {
- $searchParamTypeOrderList[] = null;
- }
- }
- $orderList = \array_combine($orderFieldList, $searchParamTypeOrderList);
- foreach ($orderList as $orderField => $orderType) {
- $userOrder = ['order' => $orderField];
- if (ENABLE_SEARCH_ORDER_BY_PREMIUM) {
- $userOrder['order_type'] = $orderType;
- $order[] = $userOrder;
- } else {
- $userOrder['order_type'] = $orderType;
- // if order_field is "ordenación Enalquiler" or premium
- if (\strcasecmp($searchParamOrderField, 'orden') === 0) {
- // add the custom order after BOL availability order
- $order[] = $userOrder;
- } else {
- // else, BOL availability order goes last.
- \array_unshift($order, $userOrder);
- }
- }
- }
- return $order;
- }
- private function removeFilters($queryFilters, $_removeFilters)
- {
- foreach ($queryFilters as $key => $value) {
- if (\in_array($value['field'], $_removeFilters)) {
- unset($queryFilters[$key]);
- }
- }
- return $queryFilters;
- }
- private function processResults($results, $config)
- {
- $locale = $this->getEnvironment()->getCurrentLanguage();
- $aInfo = ['searchResults' => []];
- $dataProvider = new DataProvider();
- $resultsDataProvider = $dataProvider->getSearchResults($results);
- if ($resultsDataProvider) {
- $aInfo = ['searchResults' => $resultsDataProvider,
- 'total' => $results->getTotalHits(),
- ];
- if (isset($config['conFoto'])) {
- try {
- $conFoto = $results->getAggregation('conFoto');
- $aInfo['total_con_foto'] = $conFoto['doc_count'];
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- }
- if ($results) {
- if (isset($config['districts'])) {
- try {
- $agg = $results->getAggregation('districts');
- $aInfo['districts'] = $dataProvider->getDistrictCounts($agg);
- if (isset($config['neighborhoods'])) {
- $subagg = $results->getAggregation('neighborhoods');
- $aInfo['districts'] = $dataProvider->addDistrictNeighborhoodCounts($aInfo['districts'], $subagg);
- }
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- if (isset($config['neighborhoods'])) {
- try {
- $agg = $results->getAggregation('neighborhoods');
- $aInfo['neighborhoods'] = $dataProvider->getNeighborhoodCounts($agg);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- $locationsAggregationName = 'locations';
- if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
- $locationsAggregationName .= '_' . $locale;
- }
- if (isset($config[$locationsAggregationName])) {
- try {
- $agg = $results->getAggregation($locationsAggregationName);
- $aInfo['locations'] = $dataProvider->getLocationCounts($agg);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- $provinceAggregationName = 'provinces';
- if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
- $provinceAggregationName .= '_' . $locale;
- }
- if (isset($config[$provinceAggregationName])) {
- try {
- $agg = $results->getAggregation($provinceAggregationName);
- $aInfo['provinces'] = $dataProvider->getProvinceCounts($agg);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- if (isset($config['closeLocations'])) {
- try {
- $agg = $results->getAggregation('closeLocations');
- $aInfo['closeLocations'] = $dataProvider->getCloseLocationsCounts($agg);
- foreach ($aInfo['closeLocations'] as $key => $val) {
- if (isset($aInfo['locations'][$key])) {
- $aInfo['closeLocations'][$key]['total'] = $aInfo['locations'][$key]['total'];
- }
- }
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- if (isset($config['geoGrid'])) {
- try {
- $agg = $results->getAggregation('geogrid');
- $aInfo['geoGrid'] = $dataProvider->getGeoGridInfo($agg);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- if (isset($config['priceHistogram'])) {
- try {
- $agg = $results->getAggregation('priceHistogram');
- $aInfo['priceHistogram'] = $dataProvider->getPriceHistogram($agg);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- if (isset($config['priceHistogramOverBoundary'])) {
- try {
- $agg = $results->getAggregation('priceHistogramOverBoundary');
- $aInfo['priceHistogramOverBoundary'] = $dataProvider->getPriceHistogramOverBoundary($agg);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- }
- return $aInfo;
- }
- private function processSuggests($results)
- {
- $aInfo = [];
- $dataProvider = new DataProvider();
- if (isset($results['suggestion_home'])) {
- $aInfo['suggestions'] = $dataProvider->getSuggestHome($results);
- }
- return $aInfo;
- }
- private function processCounts($results, $config)
- {
- $locale = $this->getEnvironment()->getCurrentLanguage();
- $aInfo = [];
- $dataProvider = new DataProvider();
- if ($results) {
- if (isset($config['districts'])) {
- try {
- $agg = $results->getAggregation('districts');
- if (isset($this->search_params['poblacion'])) {
- $aInfo['districts'] = [$this->search_params['poblacion'] => $dataProvider->getSuggestDistrictsCounts($agg)];
- } else {
- $aInfo['districts'] = $dataProvider->getSuggestDistrictsCounts($agg);
- }
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- if (isset($config['neighborhoods'])) {
- try {
- $agg = $results->getAggregation('neighborhoods');
- $home = (isset($config['home']) && $config['home']) ? true : false;
- $aInfo['neighborhoods'] = $dataProvider->getSuggestNeighborhoodsCounts($agg, $home, $config['url']);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- $locationNameAggregationName = 'locations';
- if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
- $locationNameAggregationName .= '_' . $locale;
- }
- if (isset($config[$locationNameAggregationName])) {
- try {
- $agg = $results->getAggregation($locationNameAggregationName);
- if (isset($this->search_params['provincia'])) {
- $aInfo['locations'] = [$this->search_params['provincia'] => $dataProvider->getSuggestLocationsCounts($agg)];
- } else {
- $aInfo['locations'] = $dataProvider->getSuggestLocationsCounts($agg);
- }
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- $provinceNameAggregation = 'provinces';
- if (\defined('ENABLE_I18N') && true === ENABLE_I18N) {
- $provinceNameAggregation .= '_' . $locale;
- }
- if (isset($config[$provinceNameAggregation])) {
- try {
- $agg = $results->getAggregation($provinceNameAggregation);
- $aInfo['provinces'] = $dataProvider->getSuggestProvincesCounts($agg);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- }
- }
- }
- return $aInfo;
- }
- private function executeSearch(ElasticaQueryBuilder $queryBuilder)
- {
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- try {
- if (isset($this->search_params['debug']) && $this->search_params['debug'] && ENV != 'PROD') {
- die(\json_encode($queryBuilder->getQuery(), 128));
- }
- $results = $indexInstance->search($queryBuilder->getQuery());
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- return false;
- }
- return $results;
- }
- private function executeSuggest(ElasticaQueryBuilder $queryBuilder)
- {
- /* @var $clientInstance \Elastica\Client */
- $clientInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.clients.site');
- try {
- $response = $clientInstance->request('suggests/_suggest', Request::GET, $queryBuilder->getQuery());
- $results = $response->getData();
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- return false;
- }
- return $results;
- }
- private function aggregationSearch($config)
- {
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder = $this->addQueryAgregations($queryBuilder, $config);
- return $this->executeSearch($queryBuilder);
- }
- private function filteredSearch($config)
- {
- /** @var ElasticaQueryBuilder $queryBuilder */
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder = $this->addQueryType($queryBuilder, $config);
- if (isset($this->search_params['date_from']) && isset($this->search_params['date_to'])) {
- $queryBuilder->filterMust($config['queryFilters']);
- } else {
- $queryBuilder->filterAnd($config['queryFilters']);
- }
- $queryBuilder->size($config['size']);
- if (isset($config['fields'])) {
- $queryBuilder->fields($config['fields']);
- }
- if (isset($config['offset'])) {
- $queryBuilder->offset(($config['offset'] < 0) ? 0 : $config['offset']);
- }
- if (isset($config['order']) && \is_array($config['order'])) {
- foreach ($config['order'] as $order_field) {
- $type = (isset($order_field['order_type'])) ? $order_field['order_type'] : false;
- $queryBuilder->sort($order_field['order'], $type);
- }
- } else {
- if (isset($config['order']) && isset($config['order_type'])) {
- $queryBuilder->sort($config['order'], $config['order_type']);
- }
- }
- $queryBuilder = $this->addQueryAgregations($queryBuilder, $config);
- $queryBuilder = $this->addQueryHighlights($queryBuilder, $config);
- return $this->executeSearch($queryBuilder);
- }
- private function geoSearch($config)
- {
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder = $this->addQueryType($queryBuilder, $config);
- $order = $config['order'];
- foreach ($order as $key => $val) {
- if ($val == 'geo_location.location') {
- $order[$key] = ['_geo_distance' => [$val => $config['lat_lon'], 'order' => 'asc', 'unit' => 'km']];
- }
- }
- $queryBuilder->filterAnd($config['queryFilters']);
- if (isset($config['radius'])) {
- $queryBuilder->filterGeo($config['lat_lon'], $config['radius']);
- } else {
- $queryBuilder->filterGeo($config['lat_lon']);
- }
- $queryBuilder->size($config['size'])
- ->sortGeo($order);
- $queryBuilder = $this->addQueryAgregations($queryBuilder, $config);
- $results = $this->executeSearch($queryBuilder);
- return $results;
- }
- private function mapSearch($config)
- {
- $queryBuilder = new ElasticaQueryBuilder();
- $queryBuilder = $this->addQueryType($queryBuilder, $config);
- $queryBuilder->filterAnd($config['queryFilters']);
- $filtersArray = $queryBuilder->getQuery();
- $filtersArray['filter']['and'][] =
- [
- 'geo_bounding_box' => [
- 'location' => [
- 'top_left' => [
- 'lat' => $this->search_params['bounds']['top_left']['lat'],
- 'lon' => $this->search_params['bounds']['top_left']['lon'],
- ],
- 'bottom_right' => [
- 'lat' => $this->search_params['bounds']['bottom_right']['lat'],
- 'lon' => $this->search_params['bounds']['bottom_right']['lon'],
- ],
- ],
- ],
- ];
- $query = [
- 'query' => [
- 'filtered' => $filtersArray,
- ],
- 'aggs' => [
- 'geogrid' => [
- 'geohash_grid' => [
- 'field' => 'location',
- 'precision' => (empty($this->search_params['precision'])) ? 6 : (int) $this->search_params['precision'],
- ],
- 'aggs' => [
- 'cell' => [
- 'geo_bounds' => [
- 'field' => 'location',
- ],
- ],
- ],
- ],
- ],
- ];
- $indexInstance = \Enalquiler\Core\DI\DIContainer::getInstance()->get('elastica.index.properties');
- try {
- if (isset($this->search_params['debug']) && $this->search_params['debug'] && ENV != 'PROD') {
- // die('<pre> ' . json_encode($queryBuilder->getQuery(), 1) . '</pre><br>---------<br>');
- die('<pre> ' . \json_encode($query, 1) . '</pre><br>---------<br>');
- }
- //$results = $indexInstance->search($queryBuilder->getQuery());
- $results = $indexInstance->search($query, ['search_type' => 'count']);
- } catch (\Exception $e) {
- $this->logger->err('- ELASTIC SEARCH ERROR : ' . \print_r($this->search_params, 1) . ' ' . $e->getMessage());
- return false;
- }
- return $results;
- }
- private function calculateAggregationQueryFilters($queryFilters)
- {
- $aggregationsQueryFilters = [];
- foreach ($this->aggregations as $name => $value) {
- $aggregationQueryFilters[$name] = $value['default'];
- if (\count($queryFilters)) {
- foreach ($queryFilters as $aggName => $queryFilter) {
- if (isset($queryFilter['field']) && !\in_array($queryFilter['field'], $value['exclude'])) {
- $aggregationQueryFilters[$name][] = $queryFilter;
- }
- }
- }
- }
- return $aggregationQueryFilters;
- }
- private function addQueryAgregations($queryBuilder, $config)
- {
- foreach ($this->aggregations as $name => $value) {
- if (isset($config[$name])) {
- $agg_config = [
- 'name' => $name,
- 'type' => $config[$name]['type'],
- 'aggs_type' => $config[$name]['aggs_type'],
- 'filters' => $config[$name]['queryFilters'], ];
- if (isset($config[$name]['order'])) {
- $agg_config['order'] = $config[$name]['order'];
- }
- if (isset($config[$name]['order_type'])) {
- $agg_config['order_type'] = $config[$name]['order_type'];
- }
- if (isset($config[$name]['script'])) {
- $agg_config['script'] = $config[$name]['script'];
- }
- if (isset($config[$name]['field'])) {
- $agg_config['field'] = $config[$name]['field'];
- }
- if (isset($config[$name]['size'])) {
- $agg_config['size'] = $config[$name]['size'];
- }
- if (isset($config[$name]['interval'])) {
- $agg_config['interval'] = $config[$name]['interval'];
- }
- if (isset($config[$name]['min_doc_count'])) {
- $agg_config['min_doc_count'] = $config[$name]['min_doc_count'];
- }
- if (isset($config[$name]['min'])) {
- $agg_config['min'] = $config[$name]['min'];
- }
- if (isset($config[$name]['max'])) {
- $agg_config['max'] = $config[$name]['max'];
- }
- $queryBuilder->aggregation($agg_config);
- }
- }
- return $queryBuilder;
- }
- private function addQueryHighlights($queryBuilder, $config)
- {
- if (isset($config['textQuery']) && $config['textQuery']) {
- $queryBuilder->highlight($this->highlight);
- }
- return $queryBuilder;
- }
- private static function replaceQuery(&$item, &$value, $query): void
- {
- $item = \str_replace('*', $query, $item);
- }
- private static function replaceMinShouldMatch(&$item, &$value, $minShouldMatch): void
- {
- $item = \str_replace('?', $minShouldMatch, $item);
- }
- private function addQueryType($queryBuilder, $config)
- {
- if (isset($config['textQuery']) && $config['textQuery']) {
- $queryType = $this->getQueryType();
- \array_walk_recursive($queryType, 'self::replaceQuery', $this->processQueryString($config['textQuery']));
- $this->setQueryType($queryType);
- $queryBuilder->query($queryType);
- }
- if (isset($config['minShouldMatch']) && $config['minShouldMatch']) {
- $queryType = $this->getQueryType();
- \array_walk_recursive($queryType, 'self::replaceMinShouldMatch', $config['minShouldMatch']);
- $this->setQueryType($queryType);
- $queryBuilder->query($queryType);
- }
- return $queryBuilder;
- }
- private function setQueryAggregations($queryFilters, $config, $exclude = [])
- {
- $aggregationsQueryFilters = $this->calculateAggregationQueryFilters($queryFilters);
- foreach ($this->aggregations as $key => $value) {
- if (!\in_array($key, $exclude)) {
- $config[$key] = ['name' => $key];
- if (isset($value['script'])) {
- $config[$key]['script'] = $value['script'];
- }
- if (isset($value['field'])) {
- $config[$key]['field'] = $value['field'];
- }
- if (isset($aggregationsQueryFilters[$key])) {
- $config[$key]['queryFilters'] = $aggregationsQueryFilters[$key];
- }
- if (isset($value['order'])) {
- $config[$key]['order'] = $value['order'];
- }
- if (isset($value['aggs_type'])) {
- $config[$key]['aggs_type'] = $value['aggs_type'];
- }
- if (isset($value['order_type'])) {
- $config[$key]['order_type'] = $value['order_type'];
- }
- if (isset($value['type'])) {
- $config[$key]['type'] = $value['type'];
- }
- if (isset($value['size'])) {
- $config[$key]['size'] = $value['size'];
- }
- if (isset($value['interval'])) {
- $config[$key]['interval'] = $value['interval'];
- }
- if (isset($value['min_doc_count'])) {
- $config[$key]['min_doc_count'] = $value['min_doc_count'];
- }
- if (isset($value['min'])) {
- $config[$key]['min'] = $value['min'];
- }
- if (isset($value['max'])) {
- $config[$key]['max'] = $value['max'];
- }
- }
- }
- return $config;
- }
- private function getLocationCoords()
- {
- $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
- //TODO: Change to use doctrine entity
- $sql = 'SELECT longitud, latitud FROM tbl_poblaciones WHERE id = ' . $this->search_params['poblacion'];
- return \current($em->getConnection()->fetchAll($sql));
- }
- private function getLocationShowLevels()
- {
- $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
- //TODO: Change to use doctrine entity
- $sql = 'SELECT mostrar_niveles FROM tbl_poblaciones WHERE id = ' . $this->search_params['poblacion'];
- $result = \current($em->getConnection()->fetchAll($sql));
- return $result['mostrar_niveles'];
- }
- private function getDistrictCoords()
- {
- $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
- //TODO: Change to use doctrine entity
- $sql = 'SELECT longitud, latitud FROM tbl_distritos WHERE id = ' . $this->search_params['distritos'];
- return \current($em->getConnection()->fetchAll($sql));
- }
- private function getNeighborhoodCoords()
- {
- $em = \Enalquiler\Core\DI\DIContainer::getInstance()->get('doctrine')->getManager('read');
- //TODO: Change to use doctrine entity
- $sql = 'SELECT longitud, latitud FROM tbl_barrios WHERE id = ' . $this->search_params['barrio'];
- return \current($em->getConnection()->fetchAll($sql));
- }
- private function getQueryFiltersToSearch($params)
- {
- $queryFilters = [];
- $this->setFilterCocinaEquipada($queryFilters, $params);
- $this->setFilterAntiguedad($queryFilters, $params);
- $this->setFilterObranueva($queryFilters, $params);
- $this->setFilterTipoUsuario($queryFilters, $params);
- $this->setFiltersLocation($queryFilters, $params);
- $this->setFiltersPrecio($queryFilters, $params);
- $this->setFilterMetros2($queryFilters, $params);
- $this->setFilterHabitaciones($queryFilters, $params);
- $this->setFilterBanos($queryFilters, $params);
- $this->setFilterCocina($queryFilters, $params);
- $this->setFilterJardin($queryFilters, $params);
- $this->setFilterFecha($queryFilters, $params);
- $this->setFilterFechaPublicacion($queryFilters, $params);
- $this->setFilterFechaUltimoCambioPrecio($queryFilters, $params);
- $this->setFilterAmueblado($queryFilters, $params);
- $this->setFilterOpcionCompra($queryFilters, $params);
- $this->setFilterGaraje($queryFilters, $params);
- $this->setFilterExterior($queryFilters, $params);
- $this->setFilterAscensor($queryFilters, $params);
- $this->setFilterAnimales($queryFilters, $params);
- $this->setFilterAireAcondicionado($queryFilters, $params);
- $this->setFilterPiscina($queryFilters, $params);
- $this->setFilterTerraza($queryFilters, $params);
- $this->setFilterCalefaccion($queryFilters, $params);
- $this->setFilterMinusvalidos($queryFilters, $params);
- $this->setFilterFoto($queryFilters, $params);
- $this->setFilterMicrosite($queryFilters, $params);
- $this->setFilterExcludeIds($queryFilters, $params);
- $this->setFilterIds($queryFilters, $params);
- $this->setFilterIntegracion($queryFilters, $params);
- $this->setFilterSameUser($queryFilters, $params);
- $this->setFilterProvinceCapital($queryFilters, $params);
- $this->setFilterEsconderMapa($queryFilters, $params);
- $this->setFilterPago($queryFilters, $params);
- $this->setFilterMaxLevel($queryFilters, $params);
- $this->setFilterBajadaPrecio($queryFilters, $params);
- $this->setFilterOnlineBooking($queryFilters, $params);
- $this->setFilterBookingOnlineNextMonthsAvailable($queryFilters, $params);
- $this->setFilterGeohash($queryFilters, $params);
- $this->setFilterGeolocationPoints($queryFilters, $params);
- $this->setFilterGeoLocationRadius($queryFilters, $params);
- $this->setFilterAvailabilityDates($queryFilters, $params);
- $this->setAvailabilityMinimumDays($queryFilters, $params);
- $this->setFilterAccesoMinusvalidos($queryFilters, $params);
- $this->setFilterHasPositioning($queryFilters, $params);
- $this->setFilterFullProperty($queryFilters, $params);
- // Filters that only apply to FLATS category (piso, atico, loft, ... all but habitaciones)
- $flatQueryFilter[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 0];
- $this->setFilterPeopleCapacity($flatQueryFilter, $params);
- $this->setFilterTipoVivienda($flatQueryFilter, $params);
- $flatOnlyQueryFiltersAnd[] = ['type' => 'and', 'field' => 'and_properties', 'value' => $flatQueryFilter];
- // Filters that only apply to ROOMS category (habitacion)
- $roomsQueryFilters[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 1];
- $this->setFilterSmoker($roomsQueryFilters, $params);
- $this->setFilterRoomerGenderPreference($roomsQueryFilters, $params);
- $this->setFilterBedSize($roomsQueryFilters, $params);
- $this->setFilterRoomSize($roomsQueryFilters, $params);
- $this->setFilterPrivateBathroom($roomsQueryFilters, $params);
- $this->setFilterDoorLock($roomsQueryFilters, $params);
- $roomsOnlyQueryFiltersAnd[] = ['type' => 'and', 'field' => 'and_rooms', 'value' => $roomsQueryFilters];
- if (isset($params['online_booking']) && $params['online_booking'] == 1) {
- $queryFilters[] = [
- 'type' => 'or',
- 'field' => 'or_tipos',
- 'value' => \array_merge($roomsOnlyQueryFiltersAnd, $flatOnlyQueryFiltersAnd)
- ];
- } else {
- $queryFilters = \array_merge($queryFilters, $flatQueryFilter);
- }
- return $queryFilters;
- }
- private function setFilterSameUser(&$queryFilters, $params): void
- {
- if (isset($params['user'])) {
- if (!\is_array($params['user'])) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_usuarios', 'value' => $params['user']];
- } else {
- $aUsers = [];
- foreach ($params['user'] as $user) {
- $aUsers[] = ['type' => 'term', 'field' => 'fk_id_tbl_usuarios', 'value' => $user];
- }
- $queryFilters[] = ['type' => 'or', 'field' => 'or_usuarios', 'value' => $aUsers];
- }
- }
- }
- private function setFilterCocinaEquipada(&$queryFilters, $params): void
- {
- if (isset($params['cocina_equipada']) && $params['cocina_equipada']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'cocina_equipada', 'value' => 1];
- }
- }
- private function setFilterAntiguedad(&$queryFilters, $params): void
- {
- if (isset($params['antiguedad']) && $params['antiguedad']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_antiguedad_inmuebles', 'value' => (int) $params['antiguedad']];
- }
- }
- private function setFilterObranueva(&$queryFilters, $params): void
- {
- if (isset($params['obra_nueva']) && $params['obra_nueva']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_estado_inmuebles', 'value' => 3];
- }
- }
- private function setFilterTipoUsuario(&$queryFilters, $params): void
- {
- // hack para landings particular => forzamos el filtro por tipo
- if (isset($params['desde_footer']) && $params['desde_footer'] == 1 && isset($params['query_string']) && \strstr(
- $params['query_string'],
- 'particular'
- )) {
- $params['tipo_usuario'] = 1;
- }
- if (isset($params['tipo_usuario']) && $params['tipo_usuario']) {
- $tipo = ($params['tipo_usuario'] == 3) ? 2 : $params['tipo_usuario'];
- $queryFilters[] = ['type' => 'range', 'field' => 'dn_fk_id_tbl_tipo_usuarios', 'value' => ['gte' => $tipo,
- 'lte' => $tipo, ]];
- if ($params['tipo_usuario'] == 3) {
- $queryFilters[] = ['type' => 'term', 'field' => 'pago', 'value' => 1];
- }
- }
- }
- private function setFiltersLocation(&$queryFilters, $params): void
- {
- if (isset($params['provincia']) && $params['provincia']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_provincias', 'value' => $params['provincia']];
- }
- if (isset($params['poblacion']) && $params['poblacion']) {
- if (isset($params['pobprox']) && $params['pobprox']) {
- $i = 0;
- $aPoblaciones[$i] = $params['poblacion'];
- $aPobs = [
- ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $params['poblacion']],
- ];
- foreach ($params['pobprox'] as $pprox) {
- ++$i;
- $aPoblaciones[$i] = $pprox;
- $aPobs[] = ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $pprox];
- }
- $queryFilters[] = ['type' => 'or', 'field' => 'or_poblaciones', 'value' => $aPobs];
- } else {
- if (!\is_array($params['poblacion'])) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $params['poblacion']];
- } else {
- $aPobs = [];
- $i = 0;
- foreach ($params['poblacion'] as $pob) {
- $aPoblaciones[$i] = $pob;
- $aPobs[] = ['type' => 'term', 'field' => 'fk_id_tbl_poblaciones', 'value' => $pob];
- ++$i;
- }
- $queryFilters[] = ['type' => 'or', 'field' => 'or_poblaciones', 'value' => $aPobs];
- }
- }
- }
- $this->setFilterBarriosDistritos($queryFilters, $params);
- }
- private function setFilterTipoVivienda(&$queryFilters, $params): void
- {
- //tipo de vivienda
- if (isset($params['tipo']) && $params['tipo'] && $params['tipo'] != 1) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_categorias', 'value' => (int) $params['tipo']];
- }
- }
- private function setFilterCocina(&$queryFilters, $params): void
- {
- //tipo de cocina
- if (isset($params['cocina']) && $params['cocina'] && $params['cocina'] != 1) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_cocina', 'value' => (int) $params['cocina']];
- }
- }
- private function setFiltersPrecio(&$queryFilters, $params): void
- {
- if (!empty($params['precio_min']) && !empty($params['precio_max'])) {
- $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['gte' => $params['precio_min'],
- 'lte' => $params['precio_max'], ]];
- } elseif (!empty($params['precio_max'])) {
- $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['lte' => $params['precio_max']]];
- } elseif (!empty($params['precio_min'])) {
- $queryFilters[] = ['type' => 'range', 'field' => $this->getFieldPrice($params), 'value' => ['gte' => $params['precio_min']]];
- }
- }
- private function setFilterMetros2(&$queryFilters, $params): void
- {
- if (isset($params['metros2']) && $params['metros2']) {
- $queryFilters[] = ['type' => 'range', 'field' => 'metros2', 'value' => ['gte' => $params['metros2']]];
- }
- if (!empty($params['metros_min'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'metros2', 'value' => ['gte' => $params['metros_min']]];
- }
- if (!empty($params['metros_max'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'metros2', 'value' => ['lte' => $params['metros_max']]];
- }
- }
- private function setFilterHabitaciones(&$queryFilters, $params): void
- {
- if (!empty($params['habitaciones'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['gte' => $params['habitaciones']]];
- }
- if (!empty($params['habitaciones_min'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['gte' => $params['habitaciones_min']]];
- }
- if (!empty($params['habitaciones_max'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'num_habitaciones', 'value' => ['lte' => $params['habitaciones_max']]];
- }
- }
- private function setFilterBanos(&$queryFilters, $params): void
- {
- if (isset($params['banos']) && $params['banos']) {
- $queryFilters[] = ['type' => 'range', 'field' => 'num_banos', 'value' => ['gte' => $params['banos']]];
- }
- }
- private function setFilterJardin(&$queryFilters, $params): void
- {
- if (isset($params['jardin']) && $params['jardin']) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_jardin', 'value' => ['gt' => 1]];
- }
- }
- private function setFilterFecha(&$queryFilters, $params): void
- {
- if (isset($params['fecha']) && $params['fecha']) {
- $date = new \DateTime();
- switch ($params['fecha']) {
- case 1: // Last 24h
- $date->sub(new \DateInterval('PT24H'));
- $fecha = $date->getTimestamp();
- break;
- case 2: // Last 72h
- $date->sub(new \DateInterval('PT72H'));
- $fecha = $date->getTimestamp();
- break;
- case 3: //This week
- $date->sub(new \DateInterval('P7D'));
- $fecha = $date->getTimestamp();
- break;
- case 4: //This month
- $date->sub(new \DateInterval('P30D'));
- $fecha = $date->getTimestamp();
- break;
- default:
- $fecha = '';
- }
- if ($fecha) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fec_alta', 'value' => ['gte' => $fecha]];
- }
- }
- }
- private function setFilterFechaPublicacion(&$queryFilters, $params): void
- {
- if (isset($params['fec_publicacion']) && $params['fec_publicacion']) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fec_publicacion', 'value' => ['gte' => $params['fec_publicacion']]];
- }
- }
- private function setFilterFechaUltimoCambioPrecio(&$queryFilters, $params): void
- {
- if (isset($params['fec_ultimo_cambio_precio']) && $params['fec_ultimo_cambio_precio']) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fec_ultimo_cambio_precio', 'value' => ['gte' => $params['fec_ultimo_cambio_precio']]];
- }
- }
- private function setFilterAmueblado(&$queryFilters, $params): void
- {
- //online_booking check
- if (isset($params['online_booking']) && $params['online_booking'] == 1) {
- $params['amueblado'] = 1;
- }
- // hack para landings amueblado => forzamos el filtro por tipo
- if (isset($params['desde_footer']) && $params['desde_footer'] == 1 && isset($params['query_string']) && \strstr(
- $params['query_string'],
- 'amueblado'
- )) {
- $params['amueblado'] = 1;
- }
- if (isset($params['amueblado'])) {
- if (2 == $params['amueblado']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'amueblado', 'value' => 0];
- } else {
- $queryFilters[] = ['type' => 'range', 'field' => 'amueblado', 'value' => ['gte' => 1]];
- }
- }
- }
- private function setFilterOpcionCompra(&$queryFilters, $params): void
- {
- if (isset($params['opcion_compra']) && $params['opcion_compra']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'opcion_compra', 'value' => (int) $params['opcion_compra']];
- }
- }
- private function setFilterGaraje(&$queryFilters, $params): void
- {
- if (isset($params['garaje_incluido']) && $params['garaje_incluido']) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fk_id_tbl_parking', 'value' => ['gte' => 2, 'lte' => 3]];
- }
- }
- private function setFilterExterior(&$queryFilters, $params): void
- {
- if (isset($params['exterior']) && $params['exterior']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'exterior', 'value' => (int) $params['exterior']];
- }
- }
- private function setFilterAscensor(&$queryFilters, $params): void
- {
- if (isset($params['ascensor']) && $params['ascensor']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'ascensor', 'value' => (int) $params['ascensor']];
- }
- }
- private function setFilterAnimales(&$queryFilters, $params): void
- {
- if (isset($params['acepta_animales']) && $params['acepta_animales']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'acepta_animales', 'value' => (int) $params['acepta_animales']];
- }
- }
- private function setFilterAireAcondicionado(&$queryFilters, $params): void
- {
- if (isset($params['aa']) && $params['aa']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'aa', 'value' => (int) $params['aa']];
- }
- }
- private function setFilterPiscina(&$queryFilters, $params): void
- {
- if (isset($params['piscina']) && $params['piscina']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'piscina', 'value' => (int) $params['piscina']];
- }
- }
- private function setFilterTerraza(&$queryFilters, $params): void
- {
- if (isset($params['terraza']) && $params['terraza']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'terraza', 'value' => (int) $params['terraza']];
- }
- }
- private function setFilterCalefaccion(&$queryFilters, $params): void
- {
- if (isset($params['calefaccion']) && $params['calefaccion']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'calefaccion', 'value' => (int) $params['calefaccion']];
- }
- }
- private function setFilterMinusvalidos(&$queryFilters, $params): void
- {
- if (isset($params['minusvalidos']) && $params['minusvalidos']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'minusvalidos', 'value' => (int) $params['minusvalidos']];
- }
- }
- private function setFilterFoto(&$queryFilters, $params): void
- {
- if (isset($params['con_foto']) && $params['con_foto']) {
- $queryFilters[] = ['type' => 'range', 'field' => 'foto', 'value' => ['gte' => 1]];
- }
- }
- private function setFilterEsconderMapa(&$queryFilters, $params): void
- {
- if (isset($params['esconder_mapa']) && $params['esconder_mapa']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_esconder_en_mapa', 'value' => (int) $params['esconder_mapa']];
- }
- }
- private function setFilterPago(&$queryFilters, $params): void
- {
- if (isset($params['pago']) && $params['pago']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'pago', 'value' => (int) $params['pago']];
- }
- }
- private function setFilterBajadaPrecio(&$queryFilters, $params): void
- {
- if (isset($params['bajada_precio']) && ($params['bajada_precio'] == 1)) {
- $queryFilters[] = ['type' => 'range', 'field' => 'bajada_precio', 'value' => ['gt' => 0]];
- }
- }
- private function setFilterOnlineBooking(&$queryFilters, $params): void
- {
- /** @var BookingOnline $bookingOnlineService */
- $bookingOnlineService = Service::factory(Service::SRV_BOOKINGONLINE);
- if ($bookingOnlineService->isServiceEnabled() === false) {
- $queryFilters[] = ['type' => 'term', 'field' => 'booking_online', 'value' => 0];
- } else {
- if (isset($params['online_booking']) && $params['online_booking']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'booking_online', 'value' => 1];
- $order = [
- ['order' => 'bookingOnlineNextMonthsAvailable', 'order_type' => 'desc'],
- ['order' => 'orden', 'order_type' => 'asc'],
- ['order' => 'precio_por_metros2', 'order_type' => 'asc'],
- ];
- $this->addSearchParam(['order_booking_online' => $order]);
- } elseif (isset($params['online_booking']) && !$params['online_booking']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'booking_online', 'value' => 0];
- }
- }
- }
- private function setFilterBookingOnlineNextMonthsAvailable(&$queryFilters, $params): void
- {
- if (isset($params['bookingOnlineNextMonthsAvailable'])) {
- $queryFilters[] = [
- 'type' => 'term',
- 'field' => 'bookingOnlineNextMonthsAvailable',
- 'value' => $params['bookingOnlineNextMonthsAvailable'],
- ];
- }
- }
- private function setFilterGeohash(&$queryFilters, $params): void
- {
- if (isset($params['geohash'])) {
- $queryFilters[] = [
- 'type' => 'geohash_cell',
- 'field' => [
- 'location' => [
- 'geohash' => \strtolower($params['geohash']),
- ],
- 'precision' => \strlen($params['geohash']),
- ],
- ];
- }
- }
- private function setFilterGeolocationPoints(&$queryFilters, $params): void
- {
- if (isset($params['geolocation_points'])) {
- $queryFilters[] = [
- 'type' => 'geo_polygon',
- 'field' => [
- 'location' => [
- 'points' => $params['geolocation_points'],
- ],
- ],
- ];
- }
- }
- private function setFilterGeoLocationRadius(&$queryFilters, $params): void
- {
- if (isset($params['radius'], $params['lat_lon'])) {
- $queryFilters[] = [
- 'type' => 'geo_distance',
- 'field' => [
- 'location' => $params['lat_lon'],
- 'distance' => $params['radius'] . 'km',
- ],
- ];
- }
- }
- private function setFiltersGeo(&$queryFilters, $params): void
- {
- if (isset($params['lat_lon'])) {
- $queryFilters[] = [
- 'type' => 'geo',
- 'field' => 'lat_lon',
- 'value' => $params['lat_lon'],
- ];
- }
- if (isset($params['radius'])) {
- $queryFilters[] = [
- 'type' => 'geo',
- 'field' => 'radius',
- 'value' => $params['radius'],
- ];
- }
- if (isset($params['bounds'])) {
- $queryFilters[] = [
- 'type' => 'geo',
- 'field' => 'bounds',
- 'value' => $params['bounds'],
- ];
- }
- }
- private function setFilterMaxLevel(&$queryFilters, $params): void
- {
- if (isset($params['min_level']) && ($params['min_level'] == 0 || $params['min_level'] == -1 || $params['min_level'] == -2)) {
- $queryFilters[] = ['type' => 'range', 'field' => 'second_level', 'value' => ['gte' => $params['min_level']]];
- }
- }
- private function setFilterBarriosDistritos(&$queryFilters, $params): void
- {
- // si hay más de 1 distrito
- if (isset($params['distritos']) && \count($params['distritos']) > 0 && !(isset($params['barrio_mapa']) && $params['barrio_mapa'])) {
- if (!\is_array($params['distritos'])) {
- if (\strpos($params['distritos'], '_')) {
- $params['distritos'] = \explode('_', $params['distritos']);
- } elseif (\strpos($params['distritos'], ',')) {
- $params['distritos'] = \explode(',', $params['distritos']);
- } elseif (\strpos($params['distritos'], '%2C')) {
- $params['distritos'] = \explode('%2C', $params['distritos']);
- $this->logger->debug('Urlencoded comma in ' . $this->search_params['searchType']);
- } elseif ($params['distritos']) {
- $params['distritos'] = [$params['distritos']];
- }
- }
- if ($params['distritos']) {
- $districtFilters = [];
- foreach ($params['distritos'] as $district) {
- $districtFilters[] = [
- 'type' => 'term', 'field' => 'fk_id_tbl_distritos', 'value' => $district,
- ];
- }
- $queryFilters[] = ['type' => 'or', 'field' => 'or_distritos', 'value' => $districtFilters];
- }
- }
- // si hay solo 1 distrito, buscamos en sus barrios
- if (isset($params['distritos']) && \count($params['distritos']) > 0 && !(isset($params['distrito_mapa']) && $params['distrito_mapa'])) {
- //barrio
- if (isset($params['barrios']) && \count($params['barrios']) > 0) {
- if (!\is_array($params['barrios'])) {
- if (\strpos($params['barrios'], '_')) {
- $params['barrios'] = \explode('_', $params['barrios']);
- } elseif (\strpos($params['barrios'], ',')) {
- $params['barrios'] = \explode(',', $params['barrios']);
- } elseif ($params['barrios']) {
- $params['barrios'] = [$params['barrios']];
- }
- }
- if ($params['barrios']) {
- $neighborhoodFilters = [];
- foreach ($params['barrios'] as $neighborhood) {
- $neighborhoodFilters[] = [
- 'type' => 'term', 'field' => 'fk_id_tbl_barrios', 'value' => $neighborhood,
- ];
- }
- $queryFilters[] = ['type' => 'or', 'field' => 'or_barrios', 'value' => $neighborhoodFilters];
- }
- }
- }
- }
- private function setFilterMicrosite(&$queryFilters, $params): void
- {
- // microsite GRAN CUENTA
- if (isset($params['midgc']) && $params['midgc']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_campanas_tbl_pack_grandes_cuentas', 'value' => $params['midgc']];
- } elseif (isset($params['mid']) && $params['mid']) {
- /* @var $serviceMicrosite Enalquiler\Modules\Product\Service\Microsite */
- $serviceMicrosite = \Enalquiler\Core\DI\DIContainer::getInstance()->get('service.microsite');
- $microsite = $serviceMicrosite->getMicrositeById($params['mid']);
- if ($microsite) {
- $queryFilters[] = ['type' => 'term', 'field' => 'fk_id_tbl_usuarios', 'value' => $microsite->getUser()->getId()];
- }
- }
- }
- private function setFilterExcludeIds(&$queryFilters, $params): void
- {
- if (isset($params['excludeIds']) && \count($params['excludeIds'])) {
- $queryFilters[] = ['type' => 'not', 'field' => 'ids', 'value' => ['values' => \array_values($params['excludeIds'])]];
- }
- }
- private function setFilterIds(&$queryFilters, $params): void
- {
- if (isset($params['ids']) && \count($params['ids'])) {
- $queryFilters[] = ['type' => 'ids', 'field' => 'values', 'value' => \array_values($params['ids'])];
- }
- }
- private function setFilterIntegracion(&$queryFilters, $params): void
- {
- if (isset($params['fk_pid_tbl_usuarios']) && $params['fk_pid_tbl_usuarios'] !== false) {
- $queryFilters[] = ['type' => 'range', 'field' => 'fk_pid_tbl_usuarios', 'value' => ['gte' => $params['fk_pid_tbl_usuarios'],
- 'lte' => $params['fk_pid_tbl_usuarios'], ]];
- }
- }
- private function setFilterProvinceCapital(&$queryFilters, $params): void
- {
- if (isset($params['province_capital']) && $params['province_capital']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'province_capital', 'value' => $params['province_capital']];
- }
- }
- private function processQueryString($queryString)
- {
- $queryString = $this->eliminarStopWords($queryString);
- $queryString = $this->corrigeKeywords($queryString);
- $queryString = \trim(\utf8_encode($queryString));
- return $queryString;
- }
- private function eliminarStopWords($query)
- {
- $string_sin_stop_words = '';
- $palabras = \explode(' ', $query);
- $stop_words = \array_merge($this->parameters['elastica']['stopwords'], $this->getStopWordsPrecios());
- if (\count($stop_words) > 0) {
- foreach ($palabras as $palabra) {
- $palabra = \trim($palabra);
- if (!\in_array(\mb_strtolower($palabra), $stop_words)) {
- if ($string_sin_stop_words == '') {
- $string_sin_stop_words .= $palabra;
- } else {
- $string_sin_stop_words .= ' ' . $palabra;
- }
- }
- }
- }
- return $string_sin_stop_words;
- }
- private function getStopWordsPrecios()
- {
- include_once PATH_SRC . 'data/daoprog/DAOProg_tbl_filtro_precio.class.php';
- $precios = [];
- $DAOFiltroPrecio = new \DAOProg_tbl_filtro_precio();
- $DAOFiltroPrecio->selectAllFor(DEFAULT_PRICE_TYPE, 'indexable = 1');
- foreach ($DAOFiltroPrecio->aDO as $precio) {
- $precios[] = $precio['precio'];
- }
- return $precios;
- }
- private function corrigeKeywords($query)
- {
- $keywordsCorrections = $this->parameters['elastica']['keywordsCorrections'];
- foreach ($keywordsCorrections as $oldKeyword => $newKeyword) {
- $query = \preg_replace('/' . $oldKeyword . '/', $newKeyword, $query);
- }
- return $query;
- }
- private function getUrl($propertyData)
- {
- include_once PATH_SRC . 'core/' . CARPETA_SMARTY . '/libs/plugins/outputfilter.rewrite_urls.php';
- $url = DOMAIN_NAME . 'index.php/cod.ficha/id.' . $propertyData['id'] . '/po.' . TextUtilities::dirify($propertyData['nombre_pob']) . '/ca.' . TextUtilities::dirify($propertyData['categoria']) . '/tit.' . TextUtilities::dirify($propertyData['titulo']) . '/';
- $url = smarty_outputfilter_rewrite_urls($url, $this);
- return $url;
- }
- private function setFilterAvailabilityDates(&$queryFilters, $params): void
- {
- if (!empty($params['date_from']) || !empty($params['date_to'])) {
- $filter = [
- 'type' => 'nested',
- 'field' => [
- 'path' => 'availability_calendar',
- 'query' => [
- 'bool' => [
- 'must' => [],
- ],
- ],
- ],
- ];
- if (!empty($params['date_from'])) {
- $date = \date('Y-m-d', \strtotime(\str_replace('/', '-', $params['date_from'])));
- $filter['field']['query']['bool']['must'][] = ['range' => ['from' => ['lte' => $date]]];
- }
- if (!empty($params['date_to'])) {
- $date = \date('Y-m-d', \strtotime(\str_replace('/', '-', $params['date_to'])));
- $filter['field']['query']['bool']['must'][] = ['range' => ['to' => ['gte' => $date]]];
- }
- $queryFilters[] = $filter;
- }
- }
- private function setAvailabilityMinimumDays(&$queryFilters, $params): void
- {
- if (!empty($params['date_from']) && !empty($params['date_to'])) {
- $date_from = \DateTime::createFromFormat('d/m/Y', $params['date_from']);
- $date_to = \DateTime::createFromFormat('d/m/Y', $params['date_to']);
- $diff_days = $date_to->diff($date_from);
- $queryFilters[] = [
- 'type' => 'range',
- 'field' => 'booking_availability_minimun_days',
- 'value' => ['lte' => $diff_days->days],
- ];
- }
- }
- private function setFilterPeopleCapacity(&$queryFilters, $params): void
- {
- if (!empty($params['people_capacity'])) {
- $queryFilters[] = ['type' => 'range', 'field' => 'people_capacity', 'value' => ['gte' => (int) $params['people_capacity']]];
- }
- }
- private function setFilterAccesoMinusvalidos(&$queryFilters, $params): void
- {
- if (isset($params['acceso_minusvalidos']) && $params['acceso_minusvalidos']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'acceso_minusvalidos', 'value' => (int) $params['acceso_minusvalidos']];
- }
- }
- private function languages()
- {
- $parameters = DIContainer::getInstance()->get('core.parameters');
- return $parameters['core.supported_languages'];
- }
- private function setFilterHasPositioning($queryFilters, $params): void
- {
- if (isset($params['positioning']) && $params['positioning']) {
- $queryFilters[] = [
- 'type' => 'term',
- 'field' => 'has_positioning',
- 'value' => (int)$params['positioning']
- ];
- }
- }
- private function setFilterSmoker(&$queryFilters, $params): void
- {
- if (isset($params['smoke']) && $params['smoke']) {
- // $smokeFilter[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 1];
- if ($params['smoke'] == self::NOT_SMOKE_FILTER) {
- $queryFilters[] = ['type' => 'term', 'field' => 'smoke', 'value' => 0];
- } else {
- $queryFilters[] = ['type' => 'range', 'field' => 'smoke', 'value' => ['gt' => 0]];
- }
- // $smokeFilterAnd[] = ['type' => 'and', 'field' => 'and_rooms', 'value' => $smokeFilter];
- //
- // $propertyFilter[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 0];
- // $propertyFilterAnd[] = ['type' => 'and', 'field' => 'and_properties', 'value' => $propertyFilter];
- //
- // $queryFilters[] = [
- // 'type' => 'or',
- // 'field' => 'or_tipos',
- // 'value' => array_merge($smokeFilterAnd, $propertyFilterAnd)
- // ];
- }
- }
- private function setFilterRoomerGenderPreference(&$queryFilters, $params): void
- {
- if (isset($params['roomer_gender_preference']) && $params['roomer_gender_preference']) {
- $queryFilters[] = [
- 'type' => 'term',
- 'field' => 'roomer_gender_preference',
- 'value' => (int) $params['roomer_gender_preference']
- ];
- }
- }
- private function setFilterBedSize(&$queryFilters, $params): void
- {
- if (isset($params['bed']) && $params['bed'] && $params['bed'] > 0) {
- $queryFilters[] = ['type' => 'term', 'field' => 'bed', 'value' => (int) $params['bed']];
- }
- }
- private function setFilterRoomSize(&$queryFilters, $params): void
- {
- if (isset($params['room_size']) && $params['room_size'] && $params['room_size'] > 0) {
- $queryFilters[] = ['type' => 'range', 'field' => 'room_size', 'value' => ['gte' => (int) $params['room_size']]];
- }
- }
- private function setFilterPrivateBathroom(&$queryFilters, $params): void
- {
- if (isset($params['private_bathroom']) && $params['private_bathroom']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'private_bathroom', 'value' => (int) $params['private_bathroom']];
- }
- }
- private function setFilterDoorLock(&$queryFilters, $params): void
- {
- if (isset($params['door_lock']) && $params['door_lock']) {
- $queryFilters[] = ['type' => 'term', 'field' => 'door_lock', 'value' => (int) $params['door_lock']];
- }
- }
- private function setFilterFullProperty(&$queryFilters, $params): void
- {
- if (isset($params['full_property']) && $params['full_property']) {
- switch ($params['full_property']) {
- case self::ONLY_FULL_PROPERTY:
- $queryFilters[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 0];
- // $queryFilters[] = [
- // 'type' => 'bool',
- // 'field' => 'must_not',
- // 'value' => [
- // 'term' => ['fk_id_tbl_categorias' => (int) CATEGORY_ROOMS ]
- // ]
- // ];
- break;
- case self::ONLY_ROOMS:
- $queryFilters[] = ['type' => 'term', 'field' => 'isRoom', 'value' => 1];
- // $params['tipo'] = CATEGORY_ROOMS;
- // $queryFilters = $this->removeFilterTipoVivienda($queryFilters);
- // $this->_setFilterTipoVivienda($queryFilters, $params);
- break;
- default:
- break;
- }
- }
- }
- private function removeFilterTipoVivienda($queryFilters)
- {
- $newFilters = [];
- foreach ($queryFilters as $filter) {
- if ($filter['field'] != 'fk_id_tbl_categorias') {
- $newFilters[] = $filter;
- }
- }
- return $newFilters;
- }
- }
Add Comment
Please, Sign In to add comment