Completed
Pull Request — master (#205)
by Darius
02:57
created

MSearch::addSearch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
13
namespace ONGR\ElasticsearchDSL;
14
15
use Elasticsearch\Common\Exceptions\InvalidArgumentException;
16
17
/**
18
 * Multi Search object that can be executed by manager
19
 *
20
 * Class MSearch
21
 * @package ONGR\ElasticsearchDSL
22
 */
23
class MSearch
24
{
25
26
    /**
27
     * @var array
28
     */
29
    private $queries;
30
31
    /**
32
     * @param Search $search
33
     * @param null $options
34
     * @throws \InvalidArgumentException
35
     *
36
     * @return Msearch
37
     */
38
    public function addSearch(Search $search, $options = null)
39
    {
40
        $this->validOptions($options);
41
42
        $this->queries[] = [
43
            'header' => is_null($options) ? [] : $options,
44
            'body' => $search
45
        ];
46
47
        return $this;
48
    }
49
50
    /**
51
     * @return array
52
     */
53
    public function toArray()
54
    {
55
        $result = [];
56
57
        foreach ($this->queries as $query)
58
        {
59
            /** @var Search $search */
60
            $search = $query['body'];
61
            $result[] = $query['header'];
62
            $result[] = $search->toArray();
63
        }
64
65
        return $result;
66
    }
67
68
    /**
69
     * @param $options
70
     */
71
    private function validOptions($options)
72
    {
73
        if ($options === null) {
74
            return;
75
        }
76
77
        $validOptions = [
78
            'index',
79
            'search_type',
80
            'preference',
81
            'routing'
82
        ];
83
84
        foreach ($options as $key => $option) {
85
            if (!in_array($key, $validOptions)) {
86
                throw new InvalidArgumentException("Multi search option {$key} is not supported");
87
            }
88
        }
89
    }
90
91
}
92