Completed
Pull Request — master (#1984)
by Maciej
19:41
created

CriteriaMerger::merge()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.7
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ODM\MongoDB\Query;
6
7
use function array_filter;
8
use function array_values;
9
use function count;
10
11
/**
12
 * Utility class for merging query criteria.
13
 *
14
 * This is mainly used to incorporate filter and ReferenceMany mapping criteria
15
 * into a query. Each criteria array will be joined with "$and" to avoid cases
16
 * where criteria might be inadvertently overridden with array_merge().
17
 */
18
final class CriteriaMerger
19
{
20
    /**
21
     * Combines any number of criteria arrays as clauses of an "$and" query.
22
     *
23
     * @param array ...$criterias Any number of query criteria arrays
24
     */
25 74
    public function merge(...$criterias) : array
26
    {
27
        $nonEmptyCriterias = array_values(array_filter($criterias, static function (array $criteria) {
28 73
            return ! empty($criteria);
29 74
        }));
30
31 74
        switch (count($nonEmptyCriterias)) {
32 74
            case 0:
33 11
                return [];
34
35 73
            case 1:
36 68
                return $nonEmptyCriterias[0];
37
38
            default:
39 22
                return ['$and' => $nonEmptyCriterias];
40
        }
41
    }
42
}
43