DoctrineExtension   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 213
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 35
lcom 1
cbo 6
dl 0
loc 213
rs 9.6
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
B getPossibleCombinations() 0 38 8
B replaceQueryParameters() 0 30 8
A getFilters() 0 9 1
B escapeFunction() 0 37 11
A formatQuery() 0 15 2
A prettifySql() 0 6 1
A formatSql() 0 6 1
A setUpSqlFormatter() 0 15 2
A getName() 0 4 1
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\Twig;
4
5
use Doctrine\SqlFormatter\HtmlHighlighter;
6
use Doctrine\SqlFormatter\NullHighlighter;
7
use Doctrine\SqlFormatter\SqlFormatter;
8
use Symfony\Component\VarDumper\Cloner\Data;
9
use Twig\Extension\AbstractExtension;
10
use Twig\TwigFilter;
11
12
/**
13
 * This class contains the needed functions in order to do the query highlighting
14
 */
15
class DoctrineExtension extends AbstractExtension
16
{
17
    /** @var SqlFormatter */
18
    private $sqlFormatter;
19
20
    /**
21
     * Define our functions
22
     *
23
     * @return TwigFilter[]
24
     */
25
    public function getFilters()
26
    {
27
        return [
28
            new TwigFilter('doctrine_pretty_query', [$this, 'formatQuery'], ['is_safe' => ['html'], 'deprecated' => true]),
29
            new TwigFilter('doctrine_prettify_sql', [$this, 'prettifySql'], ['is_safe' => ['html']]),
30
            new TwigFilter('doctrine_format_sql', [$this, 'formatSql'], ['is_safe' => ['html']]),
31
            new TwigFilter('doctrine_replace_query_parameters', [$this, 'replaceQueryParameters']),
32
        ];
33
    }
34
35
    /**
36
     * Get the possible combinations of elements from the given array
37
     */
38
    private function getPossibleCombinations(array $elements, int $combinationsLevel) : array
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
39
    {
40
        $baseCount = count($elements);
41
        $result    = [];
42
43
        if ($combinationsLevel === 1) {
44
            foreach ($elements as $element) {
45
                $result[] = [$element];
46
            }
47
48
            return $result;
49
        }
50
51
        $nextLevelElements = $this->getPossibleCombinations($elements, $combinationsLevel - 1);
52
53
        foreach ($nextLevelElements as $nextLevelElement) {
54
            $lastElement = $nextLevelElement[$combinationsLevel - 2];
55
            $found       = false;
56
57
            foreach ($elements as $key => $element) {
58
                if ($element === $lastElement) {
59
                    $found = true;
60
                    continue;
61
                }
62
63
                if ($found !== true || $key >= $baseCount) {
64
                    continue;
65
                }
66
67
                $tmp              = $nextLevelElement;
68
                $newCombination   = array_slice($tmp, 0);
69
                $newCombination[] = $element;
70
                $result[]         = array_slice($newCombination, 0);
71
            }
72
        }
73
74
        return $result;
75
    }
76
77
    /**
78
     * Escape parameters of a SQL query
79
     * DON'T USE THIS FUNCTION OUTSIDE ITS INTENDED SCOPE
80
     *
81
     * @internal
82
     *
83
     * @param mixed $parameter
84
     *
85
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
86
     */
87
    public static function escapeFunction($parameter)
88
    {
89
        $result = $parameter;
90
91
        switch (true) {
92
            // Check if result is non-unicode string using PCRE_UTF8 modifier
93
            case is_string($result) && ! preg_match('//u', $result):
94
                $result = '0x' . strtoupper(bin2hex($result));
95
                break;
96
97
            case is_string($result):
98
                $result = "'" . addslashes($result) . "'";
99
                break;
100
101
            case is_array($result):
102
                foreach ($result as &$value) {
103
                    $value = static::escapeFunction($value);
104
                }
105
106
                $result = implode(', ', $result) ?: 'NULL';
107
                break;
108
109
            case is_object($result):
110
                $result = addslashes((string) $result);
111
                break;
112
113
            case $result === null:
114
                $result = 'NULL';
115
                break;
116
117
            case is_bool($result):
118
                $result = $result ? '1' : '0';
119
                break;
120
        }
121
122
        return $result;
123
    }
124
125
    /**
126
     * Return a query with the parameters replaced
127
     *
128
     * @param string     $query
129
     * @param array|Data $parameters
130
     *
131
     * @return string
132
     */
133
    public function replaceQueryParameters($query, $parameters)
134
    {
135
        if ($parameters instanceof Data) {
136
            $parameters = $parameters->getValue(true);
137
        }
138
139
        $i = 0;
140
141
        if (! array_key_exists(0, $parameters) && array_key_exists(1, $parameters)) {
142
            $i = 1;
143
        }
144
145
        return preg_replace_callback(
146
            '/\?|((?<!:):[a-z0-9_]+)/i',
147
            static function ($matches) use ($parameters, &$i) {
148
                $key = substr($matches[0], 1);
149
150
                if (! array_key_exists($i, $parameters) && ($key === false || ! array_key_exists($key, $parameters))) {
151
                    return $matches[0];
152
                }
153
154
                $value  = array_key_exists($i, $parameters) ? $parameters[$i] : $parameters[$key];
155
                $result = DoctrineExtension::escapeFunction($value);
156
                $i++;
157
158
                return $result;
159
            },
160
            $query
161
        );
162
    }
163
164
    /**
165
     * Formats and/or highlights the given SQL statement.
166
     *
167
     * @param  string $sql
168
     * @param  bool   $highlightOnly If true the query is not formatted, just highlighted
169
     *
170
     * @return string
171
     */
172
    public function formatQuery($sql, $highlightOnly = false)
173
    {
174
        @trigger_error(sprintf('The "%s()" method is deprecated and will be removed in DoctrineBundle 3.0.', __METHOD__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
175
176
        $this->setUpSqlFormatter(true, true);
177
178
        if ($highlightOnly) {
179
            return $this->sqlFormatter->highlight($sql);
180
        }
181
182
        return sprintf(
183
            '<div class="highlight highlight-sql"><pre>%s</pre></div>',
184
            $this->sqlFormatter->format($sql)
185
        );
186
    }
187
188
    public function prettifySql(string $sql) : string
189
    {
190
        $this->setUpSqlFormatter();
191
192
        return $this->sqlFormatter->highlight($sql);
193
    }
194
195
    public function formatSql(string $sql, bool $highlight) : string
196
    {
197
        $this->setUpSqlFormatter($highlight);
198
199
        return $this->sqlFormatter->format($sql);
200
    }
201
202
    private function setUpSqlFormatter(bool $highlight = true, bool $legacy = false) : void
203
    {
204
        $this->sqlFormatter = new SqlFormatter($highlight ? new HtmlHighlighter([
205
            HtmlHighlighter::HIGHLIGHT_PRE            => 'class="highlight highlight-sql"',
206
            HtmlHighlighter::HIGHLIGHT_QUOTE          => 'class="string"',
207
            HtmlHighlighter::HIGHLIGHT_BACKTICK_QUOTE => 'class="string"',
208
            HtmlHighlighter::HIGHLIGHT_RESERVED       => 'class="keyword"',
209
            HtmlHighlighter::HIGHLIGHT_BOUNDARY       => 'class="symbol"',
210
            HtmlHighlighter::HIGHLIGHT_NUMBER         => 'class="number"',
211
            HtmlHighlighter::HIGHLIGHT_WORD           => 'class="word"',
212
            HtmlHighlighter::HIGHLIGHT_ERROR          => 'class="error"',
213
            HtmlHighlighter::HIGHLIGHT_COMMENT        => 'class="comment"',
214
            HtmlHighlighter::HIGHLIGHT_VARIABLE       => 'class="variable"',
215
        ], ! $legacy) : new NullHighlighter());
216
    }
217
218
    /**
219
     * Get the name of the extension
220
     *
221
     * @return string
222
     */
223
    public function getName()
224
    {
225
        return 'doctrine_extension';
226
    }
227
}
228