Skip to content
Snippets Groups Projects
Commit 37709576 authored by Timothy Winters's avatar Timothy Winters Committed by Simonas Šerlinskas
Browse files

BoolQuery constructor allows building container queries (#293)

parent 01f8fe81
No related branches found
No related tags found
No related merge requests found
......@@ -35,10 +35,18 @@ class BoolQuery implements BuilderInterface
/**
* Constructor to prepare container.
*
* @param array $container
*/
public function __construct()
public function __construct(array $container = [])
{
$this->container = [];
foreach ($container as $type => $queries) {
$queries = is_array($queries) ? $queries : [$queries];
array_walk($queries, function ($query) use ($type) {
$this->add($query, $type);
});
}
}
/**
......
......@@ -32,6 +32,66 @@ class BoolQueryTest extends \PHPUnit\Framework\TestCase
$bool->add(new MatchAllQuery(), 'acme');
}
/**
* Tests constructor builds container
*/
public function testBoolConstructor()
{
$bool = new BoolQuery([
BoolQuery::SHOULD => [new TermQuery('key1', 'value1')],
BoolQuery::MUST => [
new TermQuery('key2', 'value2'),
new TermQuery('key3', 'value3'),
],
BoolQuery::MUST_NOT => new TermQuery('key4', 'value4')
]);
$expected = [
'bool' => [
'should' => [
[
'term' => [
'key1' => 'value1',
],
],
],
'must' => [
[
'term' => [
'key2' => 'value2',
],
],
[
'term' => [
'key3' => 'value3',
],
],
],
'must_not' => [
[
'term' => [
'key4' => 'value4',
],
],
],
],
];
$this->assertEquals($expected, $bool->toArray());
}
/**
* Tests exception thrown if invalid BoolQuery type key is specified
*
* @expectedException \UnexpectedValueException
* @expectedExceptionMessage The bool operator acme is not supported
*/
public function testBoolConstructorException()
{
new BoolQuery([
'acme' => [new TermQuery('key1', 'value1')],
]);
}
/**
* Tests toArray() method.
*/
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment