Completed
Push — master ( f9a038...cc9983 )
by Kamil
22:34
created

QueryBuilderWalker::stringValue()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
rs 8.6737
cc 5
eloc 12
nc 5
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
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
namespace Sylius\Bundle\GridBundle\Tests\DependencyInjection;
13
14
use Doctrine\ODM\PHPCR\Query\Builder\QueryBuilder;
15
use Sylius\Bundle\GridBundle\Doctrine\PHPCRODM\ExpressionVisitor;
16
use Doctrine\Common\Collections\Expr\Comparison;
17
use Doctrine\ODM\PHPCR\Query\Builder\ConverterInterface;
18
use Doctrine\ODM\PHPCR\Query\Builder\OperandStaticLiteral;
19
use Doctrine\ODM\PHPCR\Query\Builder\OperandDynamicField;
20
use Doctrine\ODM\PHPCR\Query\Builder\ConstraintComparison;
21
use Doctrine\ODM\PHPCR\Query\Builder\AbstractNode;
22
use Doctrine\ODM\PHPCR\Query\Builder\AbstractLeafNode;
23
use Doctrine\ODM\PHPCR\Query\Builder\ConstraintFieldIsset;
24
25
/**
26
 * Creates a string representation of any given PHPCR-ODM QueryBuilder
27
 * node in order that the tests can clearly assert the state of it.
28
 */
29
class QueryBuilderWalker
30
{
31
    /**
32
     * Create a stirng representation of the given query builder node.
33
     *
34
     * @param AbstractNode $node
35
     *
36
     * @return string
37
     */
38
    public function toString(AbstractNode $node)
39
    {
40
        return implode(' ', $this->walk($node));
41
    }
42
43
    private function walk(AbstractNode $node, $elements = [])
44
    {
45
        $elements[] = $this->stringValue($node);
46
47
        if ($node instanceof AbstractLeafNode) {
48
            return $elements;
49
        }
50
51
        $elements[] = '(';
52
53
        foreach ($node->getChildren() as $childNode) {
54
            $elements = $this->walk($childNode, $elements);
55
        }
56
57
        $elements[] = ')';
58
59
        return $elements;
60
    }
61
62
    private function stringValue(AbstractNode $node)
63
    {
64
        $refl = new \ReflectionClass(get_class($node));
65
        $nodeName = $refl->getShortName();
66
        if ($node instanceof ConstraintComparison) {
67
            return sprintf('%s', $node->getOperator());
68
        }
69
70
        if ($node instanceof OperandDynamicField) {
71
            return sprintf('%s(%s.%s)', $nodeName, $node->getAlias(), $node->getField());
72
        }
73
74
        if ($node instanceof OperandStaticLiteral) {
75
            return sprintf('%s("%s")', $nodeName, $node->getValue());
76
        }
77
78
        if ($node instanceof ConstraintFieldIsset) {
79
            return sprintf('%s("%s")', $nodeName, $node->getField());
80
        }
81
82
        return $nodeName;
83
    }
84
}
85