Issues (15)

src/Service/ConditionManager.php (1 issue)

1
<?php
2
/**
3
 * Copyright © 2018 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
 * Class ConditionManager
18
 * @api
19
 */
20
class ConditionManager
21
{
22
    /**
23
     * Operator Pool
24
     *
25
     * @var \LogicTree\Operator\OperatorPool
26
     */
27
    private $operatorPool;
28
29
    /**
30
     * Combine Condition Manager constructor
31
     *
32
     * @param \LogicTree\Operator\OperatorPool|null $operatorPool
33
     */
34
    public function __construct(?OperatorPool $operatorPool = null)
35
    {
36
        $this->operatorPool = $operatorPool ?? new OperatorPool();
37
    }
38
39
    /**
40
     * Execute the logic tree structure conditions
41
     *
42
     * @param \LogicTree\Node\NodeInterface $node
43
     * @param \LogicTree\DataSource $dataSource
44
     * @return bool
45
     */
46
    public function execute(NodeInterface $node, DataSource $dataSource): bool
47
    {
48
        $result = true;
49
50
        if ($node instanceof CombineInterface) {
51
            $result = $this->executeCombine($node, $dataSource);
52
        } elseif ($node instanceof ConditionInterface) {
53
            $result = $this->executeCondition($node, $dataSource->getValue($node->getValueIdentifier()));
54
        }
55
56
        return $result;
57
    }
58
59
    /**
60
     * Execute the combination of conditions expressions
61
     *
62
     * @param \LogicTree\Node\CombineInterface $combine
63
     * @param \LogicTree\DataSource $dataSource
64
     * @return bool
65
     */
66
    private function executeCombine(CombineInterface $combine, DataSource $dataSource): bool
67
    {
68
        $operator = $this->operatorPool->getOperator(OperatorPool::TYPE_LOGICAL, $combine->getOperator());
69
        $expressions = [];
0 ignored issues
show
Short array syntax is not allowed
Loading history...
70
71
        foreach ($combine->getChildren() as $child) {
72
            $expressions[] = $this->execute($child, $dataSource);
73
        }
74
75
        return ($combine->isInvert() xor $operator->execute(...$expressions));
76
    }
77
78
    /**
79
     * Execute the condition expression
80
     *
81
     * @param \LogicTree\Node\ConditionInterface $condition
82
     * @param mixed $value
83
     * @return bool
84
     */
85
    private function executeCondition(ConditionInterface $condition, $value): bool
86
    {
87
        $operator = $this->operatorPool->getOperator(OperatorPool::TYPE_COMPARATOR, $condition->getOperator());
88
89
        return $operator->execute($value, $condition->getValueCompare());
90
    }
91
}
92