Completed
Pull Request — master (#348)
by
unknown
10:14
created

BuilderBag   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 110
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 12
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 110
rs 10
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
declare(strict_types=1);
13
14
namespace ONGR\ElasticsearchDSL;
15
16
class BuilderBag
17
{
18
    private array $bag = [];
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_ARRAY, expecting T_FUNCTION or T_CONST
Loading history...
19
20
    public function __construct(array $builders = [])
21
    {
22
        foreach ($builders as $builder) {
23
            $this->add($builder);
24
        }
25
    }
26
27
    public function add(BuilderInterface $builder): ?string
28
    {
29
        $name = bin2hex(random_bytes(30));
30
31
        if (method_exists($builder, 'getName')) {
32
            $name = $builder->getName();
33
        }
34
35
        $this->bag[$name] = $builder;
36
37
        return $name;
38
    }
39
40
    public function has(string $name): bool
41
    {
42
        return isset($this->bag[$name]);
43
    }
44
45
    public function remove(string $name): void
46
    {
47
        unset($this->bag[$name]);
48
    }
49
50
    public function clear(): void
51
    {
52
        $this->bag = [];
53
    }
54
55
    public function get(string $name): BuilderInterface
56
    {
57
        return $this->bag[$name];
58
    }
59
60
    public function all(?string $type = null): array
61
    {
62
        return array_filter(
63
            $this->bag,
64
            /** @var BuilderInterface $builder */
65
            function (BuilderInterface $builder) use ($type) {
66
                return $type === null || $builder->getType() == $type;
67
            }
68
        );
69
    }
70
71
    public function toArray(): array
72
    {
73
        $output = [];
74
        foreach ($this->all() as $builder) {
75
            $output = array_merge($output, $builder->toArray());
76
        }
77
78
        return $output;
79
    }
80
}
81