diff --git a/src/Query/Compound/BoolQuery.php b/src/Query/Compound/BoolQuery.php index 7bb6a8594afec39731cfc704198eb3f2f3bbc5b7..ecdebe6c7c980a314d097e40e171e2bb1373f11a 100644 --- a/src/Query/Compound/BoolQuery.php +++ b/src/Query/Compound/BoolQuery.php @@ -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); + }); + } } /** diff --git a/tests/Unit/Query/Compound/BoolQueryTest.php b/tests/Unit/Query/Compound/BoolQueryTest.php index cc91a7b66083830a07063390d3c6b82d0471965f..93fe2db74fee48f5c0b832c12fe5a3eeb7b9e101 100644 --- a/tests/Unit/Query/Compound/BoolQueryTest.php +++ b/tests/Unit/Query/Compound/BoolQueryTest.php @@ -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. */