diff --git a/src/SearchQuery.php b/src/SearchQuery.php index f2dd5bb..9396ac1 100644 --- a/src/SearchQuery.php +++ b/src/SearchQuery.php @@ -4,6 +4,8 @@ namespace CultuurNet\SearchV3; +use CultuurNet\SearchV3\Parameter\Query; + final class SearchQuery implements SearchQueryInterface { /** @@ -94,18 +96,32 @@ public function setLimit(int $limit): void public function toArray(): array { $query = []; + $advancedQueries = []; + foreach ($this->parameters as $parameter) { $key = $parameter->getKey(); + if ($parameter instanceof Query) { + $advancedQueries[] = $parameter->getValue(); + continue; + } + if (isset($query[$key])) { if ($parameter->allowsMultiple()) { $query[$key] = is_array($query[$key]) ? $query[$key] : [$query[$key]]; $query[$key][] = $parameter->getValue(); - } else { - continue; } + continue; + } + + $query[$key] = $parameter->getValue(); + } + + if (!empty($advancedQueries)) { + if (count($advancedQueries) === 1) { + $query['q'] = $advancedQueries[0]; } else { - $query[$key] = $parameter->getValue(); + $query['q'] = '(' . implode(') AND (', $advancedQueries) . ')'; } } diff --git a/test/SearchQueryTest.php b/test/SearchQueryTest.php index d9fb4fd..14a6f9f 100644 --- a/test/SearchQueryTest.php +++ b/test/SearchQueryTest.php @@ -8,6 +8,7 @@ use CultuurNet\SearchV3\Parameter\Facet; use CultuurNet\SearchV3\Parameter\Id; use CultuurNet\SearchV3\Parameter\Label; +use CultuurNet\SearchV3\Parameter\Query; use CultuurNet\SearchV3\ValueObjects\CalendarSummaryFormat; use PHPUnit\Framework\TestCase; @@ -192,6 +193,57 @@ public function testToArrayMethodWithDuplicateFacetKeys(): void $this->assertEquals($expectedQuery, $result); } + public function testToArrayMethodWithOneAdvancedQuery(): void + { + $this->searchQuery->addParameter(new Query('foo:bar')); + + $expectedQuery = [ + 'sort' => [ + 'title' => 'asc', + ], + 'embed' => true, + 'start' => 10, + 'limit' => 50, + 'labels' => 'test-label', + 'facets' => 'regions', + 'embedCalendarSummaries' => [ + 'md-html', + 'lg-text', + ], + 'q' => 'foo:bar', + ]; + + $result = $this->searchQuery->toArray(); + + $this->assertEquals($expectedQuery, $result); + } + + public function testToArrayMethodWithMultipleAdvancedQueries(): void + { + $this->searchQuery->addParameter(new Query('foo:bar')); + $this->searchQuery->addParameter(new Query('het depot')); + + $expectedQuery = [ + 'sort' => [ + 'title' => 'asc', + ], + 'embed' => true, + 'start' => 10, + 'limit' => 50, + 'labels' => 'test-label', + 'facets' => 'regions', + 'embedCalendarSummaries' => [ + 'md-html', + 'lg-text', + ], + 'q' => '(foo:bar) AND (het depot)', + ]; + + $result = $this->searchQuery->toArray(); + + $this->assertEquals($expectedQuery, $result); + } + public function testToStringMethod(): void { $expectedQueryString = 'labels=test-label&facets=regions&embedCalendarSummaries[0]=md-html&embedCalendarSummaries[1]=lg-text&sort[title]=asc&embed=1&start=10&limit=50';