diff --git a/core_search_facets/src/Plugin/facets/facet_source/CoreNodeSearchFacetSource.php b/core_search_facets/src/Plugin/facets/facet_source/CoreNodeSearchFacetSource.php index 0fd5dcc..f328499 100644 --- a/core_search_facets/src/Plugin/facets/facet_source/CoreNodeSearchFacetSource.php +++ b/core_search_facets/src/Plugin/facets/facet_source/CoreNodeSearchFacetSource.php @@ -158,6 +158,11 @@ class CoreNodeSearchFacetSource extends FacetSourcePluginBase implements CoreSea case 'entity_reference': $query_types['string'] = 'core_node_search_string'; break; + + case 'created': + $query_types['string'] = 'core_node_search_date'; + break; + } return $query_types; @@ -237,6 +242,7 @@ class CoreNodeSearchFacetSource extends FacetSourcePluginBase implements CoreSea 'type' => $this->t('Content Type'), 'uid' => $this->t('Author'), 'langcode' => $this->t('Language'), + 'created' => $this->t('Post date'), ]; } diff --git a/core_search_facets/src/Plugin/facets/query_type/CoreNodeSearchDate.php b/core_search_facets/src/Plugin/facets/query_type/CoreNodeSearchDate.php new file mode 100644 index 0000000..ce894f7 --- /dev/null +++ b/core_search_facets/src/Plugin/facets/query_type/CoreNodeSearchDate.php @@ -0,0 +1,200 @@ +get('facets.utility.date_handler'); + + /** @var \Drupal\core_search_facets\Plugin\CoreSearchFacetSourceInterface $facet_source */ + $facet_source = $this->facet->getFacetSource(); + + // Gets the last active date, bails if there isn't one. + $active_items = $this->facet->getActiveItems(); + if (!$active_item = end($active_items)) { + return; + } + + // Gets facet query and this facet's query info. + /** @var \Drupal\core_search_facets\FacetsQuery $facet_query */ + $facet_query = $facet_source->getFacetQueryExtender(); + $query_info = $facet_source->getQueryInfo($this->facet); + $tables_joined = []; + + // Obtain the start and end dates. + if (preg_match($date_handler::FACETS_REGEX_DATE_RANGE, $active_item, $matches)) { + $start = strtotime($matches[1]); + $end = strtotime($matches[8]); + } + + foreach ($query_info['fields'] as $field_info) { + + // Adds join to the facet query. + $facet_query->addFacetJoin($query_info, $field_info['table_alias']); + + // Adds adds join to search query, makes sure it is only added once. + if (isset($query_info['joins'][$field_info['table_alias']])) { + if (!isset($tables_joined[$field_info['table_alias']])) { + $tables_joined[$field_info['table_alias']] = TRUE; + $join_info = $query_info['joins'][$field_info['table_alias']]; + $this->query->join($join_info['table'], $join_info['alias'], $join_info['condition']); + } + } + + // Adds field conditions to the facet and search query. + $field = $field_info['table_alias'] . '.' . $field_info['field']; + $this->query->condition($field, $start, '>='); + $this->query->condition($field, $end, '<'); + $facet_query->condition($field, $start, '>='); + $facet_query->condition($field, $end, '<'); + } + } + + /** + * {@inheritdoc} + */ + public function build() { + /** @var \Drupal\facets\Utility\FacetsDateHandler $date_handler */ + $date_handler = \Drupal::getContainer()->get('facets.utility.date_handler'); + + // Gets base facet query, adds facet field and filters. + /* @var \Drupal\core_search_facets\Plugin\CoreSearchFacetSourceInterface $facet_source */ + $facet_source = $this->facet->getFacetSource(); + $query_info = $facet_source->getQueryInfo($this->facet); + + /** @var \Drupal\core_search_facets\FacetsQuery $facet_query */ + $facet_query = $facet_source->getFacetQueryExtender(); + $facet_query->addFacetField($query_info); + + foreach ($query_info['joins'] as $table_alias => $join_info) { + $facet_query->addFacetJoin($query_info, $table_alias); + } + + if ($facet_query->getSearchExpression()) { + // Executes query, iterates over results. + $result = $facet_query->execute(); + + foreach ($result as $record) { + $raw_values[$record->value] = $record->count; + } + ksort($raw_values); + + // Gets active facets, starts building hierarchy. + $parent = $gap = NULL; + + // @TODO for the moment working when none active items. + foreach ($this->facet->getActiveItems() as $value => $item) { + // If the item is active, the count is the result set count. + /*$build[$value] = array('#count' => $this->facet->getResultCount()); + + // Gets next "gap" increment, mintue being the lowest be can go. + $date_gap = facets_get_date_gap($item['start'], $item['end']); + $gap = facetsGetNextDateGap($date_gap, facets_DATE_MINUTE); + + // If there is a previous item, there is a parent, uses a reference so the + // arrays are populated when they are updated. + if (is_null($parent)) { + $build[$parent]['#item_children'][$value] = &$build[$value]; + $build[$value]['#item_parents'][$parent] = $parent; + } + + // Stores the last value iterated over. + $parent = $value;*/ + } + + // Mind the gap! Calculates gap from min and max timestamps. + $timestamps = array_keys($raw_values); + if (is_null($parent)) { + if (count($raw_values) > 1) { + $gap = $date_handler::FACETS_DATE_DAY;// $date_handler->facetsGetTimestampGap(min($timestamps), max($timestamps));// + } + else { + $gap = $date_handler::FACETS_DATE_HOUR; + } + } + + // Converts all timestamps to dates in ISO 8601 format. + $dates = []; + foreach ($timestamps as $timestamp) { + $dates[$timestamp] = $date_handler->isoDate($timestamp, $gap); + } + + // Treat each date as the range start and next date as the range end. + $range_end = []; + $previous = NULL; + foreach (array_unique($dates) as $date) { + if (is_null($previous)) { + $range_end[$previous] = $date_handler->getNextDateIncrement($previous, $gap); + } + $previous = $date; + } + $range_end[$previous] = $date_handler->getNextDateIncrement($previous, $gap); + + $facet_results = []; + foreach ($raw_values as $value => $count) { + $new_value = '[' . $dates[$value] . ' TO ' . $range_end[$dates[$value]] . ']'; + + // Groups dates by the range they belong to. + /** @var \Drupal\facets\Result\Result $last_element */ + $last_value = end($facet_results); + if ($last_value) { + if ($new_value != $last_value->getRawValue()) { + $facet_results[] = new Result($new_value, $value, $count); + } + else { + $last_value->setCount($last_value->getCount() + 1); + } + } + else { + $facet_results[] = new Result($new_value, $value, $count); + } + + /*if (!isset($build[$new_value])) { + $build[$new_value] = array('#count' => $count); + } + else { + $build[$new_value]['#count'] += $count; + } + + // Adds parent information if not already set. + if (is_null($parent) && !isset($build[$new_value]['#item_parents'])) { + $build[$parent]['#item_children'][$new_value] = &$build[$new_value]; + $build[$new_value]['#item_parents'][$parent] = $parent; + }*/ + + } + $this->facet->setResults($facet_results); + } + return $this->facet; + + } + +} diff --git a/facets.services.yml b/facets.services.yml index 1be585e..7432eed 100644 --- a/facets.services.yml +++ b/facets.services.yml @@ -22,3 +22,5 @@ services: - '@plugin.manager.facets.facet_source' - '@plugin.manager.facets.processor' - '@entity_type.manager' + facets.utility.date_handler: + class: Drupal\facets\utility\FacetsDateHandler diff --git a/src/Plugin/facets/url_processor/QueryString.php b/src/Plugin/facets/url_processor/QueryString.php index ce36f54..1ea72fa 100644 --- a/src/Plugin/facets/url_processor/QueryString.php +++ b/src/Plugin/facets/url_processor/QueryString.php @@ -129,7 +129,7 @@ class QueryString extends UrlProcessorPluginBase { // Explode the active params on the separator. foreach ($active_params as $param) { - list($key, $value) = explode(self::SEPARATOR, $param); + list($key, $value) = explode(self::SEPARATOR, $param, 2); if (!isset($this->activeFilters[$key])) { $this->activeFilters[$key] = [$value]; } diff --git a/src/Result/Result.php b/src/Result/Result.php index b748f64..247600c 100644 --- a/src/Result/Result.php +++ b/src/Result/Result.php @@ -98,6 +98,13 @@ class Result implements ResultInterface { /** * {@inheritdoc} */ + public function setCount($count) { + $this->count = $count; + } + + /** + * {@inheritdoc} + */ public function setActiveState($active) { $this->active = $active; } diff --git a/src/Utility/FacetsDateHandler.php b/src/Utility/FacetsDateHandler.php new file mode 100644 index 0000000..de98ed1 --- /dev/null +++ b/src/Utility/FacetsDateHandler.php @@ -0,0 +1,370 @@ + 6, + static::FACETS_DATE_MONTH => 5, + static::FACETS_DATE_DAY => 4, + static::FACETS_DATE_HOUR => 3, + static::FACETS_DATE_MINUTE => 2, + static::FACETS_DATE_SECOND => 1, + ); + + // Gets gap numbers for both the gap and minimum gap, checks if the next gap + // is within the limit set by the $min_gap parameter. + $gap_num = isset($gap_numbers[$gap]) ? $gap_numbers[$gap] : 6; + $min_num = isset($gap_numbers[$min_gap]) ? $gap_numbers[$min_gap] : 1; + return ($gap_num > $min_num) ? array_search($gap_num - 1, $gap_numbers) : $min_gap; + } + + /** + * Determines the best search gap to use for an arbitrary date range. + * + * Generally, we use the maximum gap that fits between the start and end date. + * If they are more than a year apart, 1 year; if they are more than a month + * apart, 1 month; etc. + * + * This function uses Unix timestamps for its computation and so is not useful + * for dates outside that range. + * + * @param int $start_time + * A string containing the start date as an ISO date string. + * @param int $end_time + * A string containing the end date as an ISO date string. + * @param string|NULL $min_gap + * (Optional) The minimum gap that should be returned. + * + * @return string + * A string containing the gap, see FACETS_DATE_* constants for valid + * values. Returns FALSE of either of the dates cannot be converted to a + * timestamp. + */ + public function getTimestampGap($start_time, $end_time, $min_gap = NULL) { + $time_diff = $end_time - $start_time; + switch (TRUE) { + // NOTE: 31536000 == 60 * 60 * 24 * 365 + case ($time_diff >= 31536000): + $gap = static::FACETS_DATE_YEAR; + break; + + case ($time_diff >= 86400 * gmdate('t', $start_time)): + $gap = static::FACETS_DATE_MONTH; + break; + + case ($time_diff >= 86400): + $gap = static::FACETS_DATE_DAY; + break; + + case ($time_diff >= 3600): + $gap = static::FACETS_DATE_HOUR; + break; + + case ($time_diff >= 60): + $gap = static::FACETS_DATE_MINUTE; + break; + + default: + $gap = static::FACETS_DATE_SECOND; + break; + } + + // Return the calculated gap if a minimum gap was not passed of the calculated + // gap is a larger interval than the minimum gap. + if (is_null($min_gap) || $this->gapCompare($gap, $min_gap) >= 0) { + return $gap; + } + else { + return $min_gap; + } + } + + /** + * Converts ISO date strings to Unix timestamps, passes values to the + * FACETS_get_timestamp_gap() function to calculate the gap. + * + * @param string $start_date + * A string containing the start date as an ISO date string. + * @param string $end_date + * A string containing the end date as an ISO date string. + * @param string|NULL $min_gap + * (Optional) The minimum gap that should be returned. + * + * @return string + * A string containing the gap, see FACETS_DATE_* constants for valid + * values. Returns FALSE of either of the dates cannot be converted to a + * timestamp. + * + * @see FACETS_get_timestamp_gap() + */ + public function getDateGap($start_date, $end_date, $min_gap = NULL) { + $range = array(strtotime($start_date), strtotime($end_date)); + if (!in_array(FALSE, $range, TRUE)) { + return $this->getTimestampGap($range[0], $range[1], $min_gap); + } + return FALSE; + } + + /** + * Returns a formatted date based on the passed timestamp and gap. + * + * This function assumes that gaps less than one day will be displayed in a + * search context in which a larger containing gap including a day is already + * displayed. So, HOUR, MINUTE, and SECOND gaps only display time information, + * without date. + * + * @param int $timestamp + * An integer containing the Unix timestamp. + * @param string $gap + * A string containing the gap, see FACETS_DATE_* constants for valid + * values, defaults to YEAR. + * + * @return string + * A gap-appropriate display date used in the facet link. + */ + public function formatTimestamp($timestamp, $gap = FACETS_DATE_YEAR) { + switch ($gap) { + case static::FACETS_DATE_MONTH: + return format_date($timestamp, 'custom', 'F Y', 'UTC'); + + case static::FACETS_DATE_DAY: + return format_date($timestamp, 'custom', 'F j, Y', 'UTC'); + + case static::FACETS_DATE_HOUR: + return format_date($timestamp, 'custom', 'g A', 'UTC'); + + case static::FACETS_DATE_MINUTE: + return format_date($timestamp, 'custom', 'g:i A', 'UTC'); + + case static::FACETS_DATE_SECOND: + return format_date($timestamp, 'custom', 'g:i:s A', 'UTC'); + + default: + return format_date($timestamp, 'custom', 'Y', 'UTC'); + } + } + + /** + * Returns a formatted date based on the passed ISO date string and gap. + * + * @param $date + * A string containing the date as an ISO date string. + * @param $gap + * A string containing the gap, see FACETS_DATE_* constants for valid + * values, defaults to YEAR. + * @param $callback + * The formatting callback, defaults to "FACETS_format_timestamp". + * + * @return + * A gap-appropriate display date used in the facet link. + * + * @see FACETS_format_timestamp() + */ + public function formatDate($date, $gap = self::FACETS_DATE_YEAR, $callback = 'facets_format_timestamp') { + $timestamp = strtotime($date); + return $callback($timestamp, $gap); + } + + /** + * Returns the next increment from the given ISO date and gap. This function is + * useful for getting the upper limit of a date range from the given start + * date. + * + * @param string $date + * A string containing the date as an ISO date string. + * @param string $gap + * A string containing the gap, see FACETS_DATE_* constants for valid + * values, defaults to YEAR. + * + * @return string + * A string containing the date, FALSE if the passed date could not be parsed. + */ + public function getNextDateIncrement($date, $gap) { + if (preg_match(static::FACETS_REGEX_DATE, $date, $match)) { + + // Increments the timestamp. + switch ($gap) { + case static::FACETS_DATE_MONTH: + $match[2] += 1; + break; + case static::FACETS_DATE_DAY: + $match[3] += 1; + break; + case static::FACETS_DATE_HOUR: + $match[4] += 1; + break; + case static::FACETS_DATE_MINUTE: + $match[5] += 1; + break; + case static::FACETS_DATE_SECOND: + $match[6] += 1; + break; + default: + $match[1] += 1; + break; + } + + // Gets the next increment. + return $this->isoDate( + gmmktime($match[4], $match[5], $match[6], $match[2], $match[3], $match[1]) + ); + } + return FALSE; + } + + /** + * Compares two timestamp gaps. + * + * @param string $gap1 + * @param string $gap2 + * + * @return int + * Returns -1 if gap1 is less than gap2, 1 if gap1 is greater than gap2, and 0 + * if they are equal. + */ + public function gapCompare($gap1, $gap2) { + + $gap_numbers = array( + static::FACETS_DATE_YEAR => 6, + static::FACETS_DATE_MONTH => 5, + static::FACETS_DATE_DAY => 4, + static::FACETS_DATE_HOUR => 3, + static::FACETS_DATE_MINUTE => 2, + static::FACETS_DATE_SECOND => 1, + ); + + $gap1_num = isset($gap_numbers[$gap1]) ? $gap_numbers[$gap1] : 6; + $gap2_num = isset($gap_numbers[$gap2]) ? $gap_numbers[$gap2] : 6; + + if ($gap1_num == $gap2_num) { + return 0; + } + else { + return ($gap1_num < $gap2_num) ? -1 : 1; + } + } +} + diff --git a/tests/src/Unit/Utility/FacetsDateHandlerTest.php b/tests/src/Unit/Utility/FacetsDateHandlerTest.php new file mode 100644 index 0000000..0ac9739 --- /dev/null +++ b/tests/src/Unit/Utility/FacetsDateHandlerTest.php @@ -0,0 +1,194 @@ +assertEquals($iso_date, $fd->isoDate(static::TIMESTAMP, $gap)); + } + + /** + * Tests for ::getNextDateGap. + */ + public function testGetNextDateGap() { + $fd = new FacetsDateHandler(); + + $gap = $fd->getNextDateGap($fd::FACETS_DATE_SECOND); + $this->assertEquals($fd::FACETS_DATE_SECOND, $gap); + + $gap = $fd->getNextDateGap($fd::FACETS_DATE_MINUTE); + $this->assertEquals($fd::FACETS_DATE_SECOND, $gap); + + $gap = $fd->getNextDateGap($fd::FACETS_DATE_SECOND, $fd::FACETS_DATE_MINUTE); + $this->assertEquals($fd::FACETS_DATE_MINUTE, $gap); + + $gap = $fd->getNextDateGap($fd::FACETS_DATE_MINUTE, $fd::FACETS_DATE_MINUTE); + $this->assertEquals($fd::FACETS_DATE_MINUTE, $gap); + + $gap = $fd->getNextDateGap($fd::FACETS_DATE_SECOND, $fd::FACETS_DATE_HOUR); + $this->assertEquals($fd::FACETS_DATE_HOUR, $gap); + + $gap = $fd->getNextDateGap($fd::FACETS_DATE_MINUTE, $fd::FACETS_DATE_HOUR); + $this->assertEquals($fd::FACETS_DATE_HOUR, $gap); + + $gap = $fd->getNextDateGap($fd::FACETS_DATE_HOUR, $fd::FACETS_DATE_HOUR); + $this->assertEquals($fd::FACETS_DATE_HOUR, $gap); + } + + /** + * Tests for ::getTimestampGap + */ + public function testGetTimestampGap() { + $fd = new FacetsDateHandler(); + + // The best search gap between two dates must be a year. + $date_gap = $fd->getTimestampGap(static::TIMESTAMP, static::TIMESTAMP + 31536000); + $this->assertEquals($fd::FACETS_DATE_YEAR, $date_gap); + + // The best search gap between two dates must be a month. + $date_gap = $fd->getTimestampGap(static::TIMESTAMP, static::TIMESTAMP + 86400 * 60); + $this->assertEquals($fd::FACETS_DATE_MONTH, $date_gap); + + // The best search gap between two dates must be a day. + $date_gap = $fd->getTimestampGap(static::TIMESTAMP, static::TIMESTAMP + 86400); + $this->assertEquals($fd::FACETS_DATE_DAY, $date_gap); + + // The best search gap between two dates must be an hour. + $date_gap = $fd->getTimestampGap(static::TIMESTAMP, static::TIMESTAMP + 3600); + $this->assertEquals($fd::FACETS_DATE_HOUR, $date_gap); + + // The best search gap between two dates must be a minute. + $date_gap = $fd->getTimestampGap(static::TIMESTAMP, static::TIMESTAMP + 60); + $this->assertEquals($fd::FACETS_DATE_MINUTE, $date_gap); + + // The best search gap between two dates must be a second. + $date_gap = $fd->getTimestampGap(static::TIMESTAMP, static::TIMESTAMP + 59); + $this->assertEquals($fd::FACETS_DATE_SECOND, $date_gap); + } + + /** + * Tests for ::getDateGap method. + */ + public function testGetDateGap() { + $fd = new FacetsDateHandler(); + + // Cannot convert to timestamp. + $this->assertFalse($fd->getDateGap(static::TIMESTAMP, static::TIMESTAMP)); + + // The min. gap is MONTH but the result is larger. + $this->assertEquals($fd::FACETS_DATE_YEAR, $fd->getDateGap('1983-03-03T20:43:04Z', '1987-11-26T20:43:04Z', $fd::FACETS_DATE_MONTH)); + + // The gap is YEAR. + $this->assertEquals($fd::FACETS_DATE_YEAR, $fd->getDateGap('1983-03-03T20:43:04Z', '1987-11-26T20:43:04Z')); + + // The gap is MONTH. + $this->assertEquals($fd::FACETS_DATE_MONTH, $fd->getDateGap('1983-03-03T20:43:04Z', '1983-11-26T20:43:04Z')); + + // The gap is DAY. + $this->assertEquals($fd::FACETS_DATE_DAY, $fd->getDateGap('1983-03-03T20:43:04Z', '1983-03-26T20:43:04Z')); + + // The gap is HOUR. + $this->assertEquals($fd::FACETS_DATE_HOUR, $fd->getDateGap('1983-03-03T20:43:04Z', '1983-03-03T21:44:04Z')); + + // The gap is MINUTE. + $this->assertEquals($fd::FACETS_DATE_MINUTE, $fd->getDateGap('1983-03-03T20:43:04Z', '1983-03-03T20:44:04Z')); + + // The gap is SECOND. + $this->assertEquals($fd::FACETS_DATE_SECOND, $fd->getDateGap('1983-03-03T20:43:04Z', '1983-03-03T20:43:55Z')); + } + + /** + * Tests for ::nextDateIncrement method. + * + * @dataProvider provideNextDateIncrementData + */ + public function testNextDateIncrement($incremented_iso_date, $gap) { + $fd = new FacetsDateHandler(); + + $this->assertEquals($incremented_iso_date, $fd->getNextDateIncrement(static::ISO_DATE, $gap)); + } + + /** + * Tests for ::gapCompare method. + */ + public function testGapCompare() { + $fd = new FacetsDateHandler(); + + // Timestamps are equals. + $this->assertEquals(0, $fd->gapCompare(static::TIMESTAMP, static::TIMESTAMP)); + + // Timestamps are equals. + $this->assertEquals(0, $fd->gapCompare($fd::FACETS_DATE_YEAR, $fd::FACETS_DATE_YEAR)); + + // gap1 is less than gap2 + $this->assertEquals(-1, $fd->gapCompare($fd::FACETS_DATE_MONTH, $fd::FACETS_DATE_YEAR)); + + // gap1 is less than gap2 + $this->assertEquals(1, $fd->gapCompare($fd::FACETS_DATE_MONTH, $fd::FACETS_DATE_DAY)); + } + + /** + * Returns a data provider for the ::testIsoDate(). + * + * @return array + */ + public function provideIsoDates() { + return [ + ['1987-11-26T20:43:04Z', FacetsDateHandler::FACETS_DATE_SECOND], + ['1987-11-26T20:43:00Z', FacetsDateHandler::FACETS_DATE_MINUTE], + ['1987-11-26T20:00:00Z', FacetsDateHandler::FACETS_DATE_HOUR], + ['1987-11-26T00:00:00Z', FacetsDateHandler::FACETS_DATE_DAY], + ['1987-11-01T00:00:00Z', FacetsDateHandler::FACETS_DATE_MONTH], + ['1987-01-01T00:00:00Z', FacetsDateHandler::FACETS_DATE_YEAR], + ['1987-11-26T20:43:04Z', FacetsDateHandler::FACETS_DATE_ISO8601], + ]; + } + + /** + * Returns a data provider for the ::testNextDateIncrement(). + * + * @return array + */ + public function provideNextDateIncrementData() { + return [ + ['1987-11-26T20:43:05Z', FacetsDateHandler::FACETS_DATE_SECOND], + ['1987-11-26T20:44:04Z', FacetsDateHandler::FACETS_DATE_MINUTE], + ['1987-11-26T21:43:04Z', FacetsDateHandler::FACETS_DATE_HOUR], + ['1987-11-27T20:43:04Z', FacetsDateHandler::FACETS_DATE_DAY], + ['1987-12-26T20:43:04Z', FacetsDateHandler::FACETS_DATE_MONTH], + ['1988-11-26T20:43:04Z', FacetsDateHandler::FACETS_DATE_YEAR], + ]; + } + +} +