Completed
Pull Request — master (#397)
by Kristof
03:59
created

SearchQueryFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace CultuurNet\UDB3\Offer\Security;
4
5
use CultuurNet\Search\Parameter\Query;
6
use CultuurNet\UDB3\ValueObject\SapiVersion;
7
use ValueObjects\StringLiteral\StringLiteral;
8
9
class SearchQueryFactory implements SearchQueryFactoryInterface
10
{
11
    /**
12
     * @var SapiVersion
13
     */
14
    private $sapiVersion;
15
16
    /**
17
     * @param SapiVersion $sapiVersion
18
     */
19
    public function __construct(SapiVersion $sapiVersion)
20
    {
21
        $this->sapiVersion = $sapiVersion;
22
    }
23
24
    /**
25
     * @inheritdoc
26
     */
27
    public function createFromConstraint(
28
        StringLiteral $constraint,
29
        StringLiteral $offerId
30
    ) {
31
        return new Query($this->createQueryString($constraint, $offerId));
32
    }
33
34
    /**
35
     * @inheritdoc
36
     */
37
    public function createFromConstraints(
38
        array $constraints,
39
        StringLiteral $offerId
40
    ) {
41
        $queryString = '';
42
43
        foreach ($constraints as $constraint) {
44
            if (strlen($queryString)) {
45
                $queryString .= ' OR ';
46
            }
47
48
            $queryString .= $this->createQueryString($constraint, $offerId);
49
        }
50
51
        return new Query($queryString);
52
    }
53
54
    /**
55
     * @param StringLiteral $constraint
56
     * @param StringLiteral $offerId
57
     * @return string
58
     */
59
    private function createQueryString(
60
        StringLiteral $constraint,
61
        StringLiteral $offerId
62
    ) {
63
        $constraintStr = '(' . strtolower($constraint->toNative()) . ')';
64
        $offerIdStr = $offerId->toNative();
65
66
        if ($this->sapiVersion->sameValueAs(SapiVersion::V3())) {
67
            $id = 'id';
68
        } else {
69
            $id = 'cdbid';
70
        }
71
72
        return '(' . $constraintStr . ' AND ' . $id . ':' . $offerIdStr . ')';
73
    }
74
}
75