ConditionManager::executeCombine()   A
last analyzed

Complexity

Conditions 2
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
nc 4
nop 2
dl 0
loc 10
rs 10
c 2
b 0
f 1
1
<?php
2
/**
3
 * Copyright © Thomas Klein, All rights reserved.
4
 * See LICENSE bundled with this library for license details.
5
 */
6
declare(strict_types=1);
7
8
namespace LogicTree\Service;
9
10
use LogicTree\DataSource;
11
use LogicTree\Node\CombineInterface;
12
use LogicTree\Node\ConditionInterface;
13
use LogicTree\Node\NodeInterface;
14
use LogicTree\Operator\OperatorPool;
15
16
/**
17
 * @api
18
 */
19
class ConditionManager
20
{
21
    /**
22
     * @var OperatorPool
23
     */
24
    private $operatorPool;
25
26
    public function __construct(?OperatorPool $operatorPool = null)
27
    {
28
        $this->operatorPool = $operatorPool ?? new OperatorPool();
29
    }
30
31
    public function execute(NodeInterface $node, DataSource $dataSource): bool
32
    {
33
        $result = true;
34
35
        if ($node instanceof CombineInterface) {
36
            $result = $this->executeCombine($node, $dataSource);
37
        } elseif ($node instanceof ConditionInterface) {
38
            $result = $this->executeCondition($node, $dataSource->getValue($node->getValueIdentifier()));
39
        }
40
41
        return $result;
42
    }
43
44
    private function executeCombine(CombineInterface $combine, DataSource $dataSource): bool
45
    {
46
        $operator = $this->operatorPool->getOperator(OperatorPool::TYPE_LOGICAL, $combine->getOperator());
47
        $expressions = [];
48
49
        foreach ($combine->getChildren() as $child) {
50
            $expressions[] = $this->execute($child, $dataSource);
51
        }
52
53
        return ($combine->isInvert() xor $operator->execute(...$expressions));
54
    }
55
56
    private function executeCondition(ConditionInterface $condition, $value): bool
57
    {
58
        $operator = $this->operatorPool->getOperator(OperatorPool::TYPE_COMPARATOR, $condition->getOperator());
59
60
        return $operator->execute($value, $condition->getValueCompare());
61
    }
62
}
63