Completed
Pull Request — master (#205)
by Darius
03:09
created

MSearch::toArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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