Completed
Pull Request — master (#1056)
by Gabriel
01:43
created

DoctrineExtension::setUpSqlFormatter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\Twig;
4
5
use SqlFormatter;
6
use Symfony\Component\VarDumper\Cloner\Data;
7
use Twig\Extension\AbstractExtension;
8
use Twig\TwigFilter;
9
10
/**
11
 * This class contains the needed functions in order to do the query highlighting
12
 */
13
class DoctrineExtension extends AbstractExtension
14
{
15
    /**
16
     * Define our functions
17
     *
18
     * @return TwigFilter[]
19
     */
20
    public function getFilters()
21
    {
22
        return [
23
            new TwigFilter('doctrine_pretty_query', [$this, 'formatQuery'], ['is_safe' => ['html'], 'deprecated' => true]),
24
            new TwigFilter('doctrine_prettify_sql', [$this, 'prettifySql'], ['is_safe' => ['html']]),
25
            new TwigFilter('doctrine_format_sql', [$this, 'formatSql'], ['is_safe' => ['html']]),
26
            new TwigFilter('doctrine_replace_query_parameters', [$this, 'replaceQueryParameters']),
27
        ];
28
    }
29
30
    /**
31
     * Get the possible combinations of elements from the given array
32
     *
33
     * @param array $elements
34
     * @param int   $combinationsLevel
35
     *
36
     * @return array
37
     */
38
    private function getPossibleCombinations(array $elements, $combinationsLevel)
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);
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();
177
178
        if ($highlightOnly) {
179
            $html = SqlFormatter::highlight($sql);
180
            $html = preg_replace('/<pre class=".*">([^"]*+)<\/pre>/Us', '\1', $html);
181
        } else {
182
            $html = SqlFormatter::format($sql);
183
            $html = preg_replace('/<pre class="(.*)">([^"]*+)<\/pre>/Us', '<div class="\1"><pre>\2</pre></div>', $html);
184
        }
185
186
        return $html;
187
    }
188
189
    public function prettifySql(string $sql) : string
190
    {
191
        $this->setUpSqlFormatter();
192
193
        return SqlFormatter::highlight($sql);
194
    }
195
196
    public function formatSql(string $sql, bool $highlight) : string
197
    {
198
        $this->setUpSqlFormatter();
199
200
        return SqlFormatter::format($sql, $highlight);
201
    }
202
203
    private function setUpSqlFormatter() : void
204
    {
205
        SqlFormatter::$pre_attributes            = 'class="highlight highlight-sql"';
206
        SqlFormatter::$quote_attributes          = 'class="string"';
207
        SqlFormatter::$backtick_quote_attributes = 'class="string"';
208
        SqlFormatter::$reserved_attributes       = 'class="keyword"';
209
        SqlFormatter::$boundary_attributes       = 'class="symbol"';
210
        SqlFormatter::$number_attributes         = 'class="number"';
211
        SqlFormatter::$word_attributes           = 'class="word"';
212
        SqlFormatter::$error_attributes          = 'class="error"';
213
        SqlFormatter::$comment_attributes        = 'class="comment"';
214
        SqlFormatter::$variable_attributes       = 'class="variable"';
215
    }
216
217
    /**
218
     * Get the name of the extension
219
     *
220
     * @return string
221
     */
222
    public function getName()
223
    {
224
        return 'doctrine_extension';
225
    }
226
}
227