Passed
Pull Request — master (#63)
by Wilmer
33:01 queued 21:11
created

VarDumper   F

Complexity

Total Complexity 62

Size/Duplication

Total Lines 385
Duplicated Lines 0 %

Test Coverage

Coverage 92.52%

Importance

Changes 16
Bugs 2 Features 0
Metric Value
eloc 144
c 16
b 2
f 0
dl 0
loc 385
ccs 136
cts 147
cp 0.9252
rs 3.44
wmc 62

15 Methods

Rating   Name   Duplication   Size   Complexity  
A exportVariable() 0 3 1
A create() 0 3 1
A __construct() 0 3 1
D exportInternal() 0 58 20
A getPropertyName() 0 13 3
A getObjectProperties() 0 8 3
A dump() 0 3 1
C dumpInternal() 0 56 14
A export() 0 5 1
A exportClosure() 0 7 2
A getObjectDescription() 0 3 1
A withOffset() 0 6 1
A asString() 0 10 2
A exportObjectFallback() 0 20 6
A exportObject() 0 37 5

How to fix   Complexity   

Complex Class

Complex classes like VarDumper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use VarDumper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\VarDumper;
6
7
use __PHP_Incomplete_Class;
8
use Closure;
9
use Exception;
10
use IteratorAggregate;
11
use JsonSerializable;
12
use ReflectionObject;
13
use ReflectionException;
14
use Yiisoft\Arrays\ArrayableInterface;
15
16
use function array_keys;
17
use function get_class;
18
use function gettype;
19
use function highlight_string;
20
use function method_exists;
21
use function next;
22
use function preg_replace;
23
use function spl_object_id;
24
use function str_repeat;
25
use function strtr;
26
use function trim;
27
use function var_export;
28
29
/**
30
 * VarDumper provides enhanced versions of the PHP functions {@see var_dump()} and {@see var_export()}.
31
 * It can:
32
 *
33
 * - Correctly identify the recursively referenced objects in a complex object structure.
34
 * - Recursively control depth to avoid indefinite recursive display of some peculiar variables.
35
 * - Export closures and objects.
36
 * - Highlight output.
37
 * - Format output.
38
 */
39
final class VarDumper
40
{
41
    /**
42
     * @var mixed Variable to dump.
43
     */
44
    private $variable;
45
    /**
46
     * @var string[] Variables using in closure scope.
47
     */
48
    private array $useVarInClosures = [];
49
    private bool $serializeObjects = true;
50
    /**
51
     * @var string Offset to use to indicate nesting level.
52
     */
53
    private string $offset = '    ';
54
    private static ?ClosureExporter $closureExporter = null;
55
56
    /**
57
     * @param mixed $variable Variable to dump.
58
     */
59 83
    private function __construct($variable)
60
    {
61 83
        $this->variable = $variable;
62
    }
63
64
    /**
65
     * @param mixed $variable Variable to dump.
66
     *
67
     * @return static An instance containing variable to dump.
68
     */
69 83
    public static function create($variable): self
70
    {
71 83
        return new self($variable);
72
    }
73
74
    /**
75
     * Prints a variable.
76
     *
77
     * This method achieves the similar functionality as {@see var_dump()} and {@see print_r()}
78
     * but is more robust when handling complex objects.
79
     *
80
     * @param mixed $variable Variable to be dumped.
81
     * @param int $depth Maximum depth that the dumper should go into the variable. Defaults to 10.
82
     * @param bool $highlight Whether the result should be syntax-highlighted.
83
     *
84
     * @throws ReflectionException
85
     */
86 6
    public static function dump($variable, int $depth = 10, bool $highlight = true): void
87
    {
88 6
        echo self::create($variable)->asString($depth, $highlight);
89
    }
90
91
    /**
92
     * Sets offset string to use to indicate nesting level.
93
     *
94
     * @param string $offset The offset string.
95
     *
96
     * @return static New instance with a given offset.
97
     */
98
    public function withOffset(string $offset): self
99
    {
100
        $new = clone $this;
101
        $new->offset = $offset;
102
103
        return $new;
104
    }
105
106
    /**
107
     * Dumps a variable in terms of a string.
108
     *
109
     * This method achieves the similar functionality as {@see var_dump()} and {@see print_r()}
110
     * but is more robust when handling complex objects.
111
     *
112
     * @param int $depth Maximum depth that the dumper should go into the variable. Defaults to 10.
113
     * @param bool $highlight Whether the result should be syntax-highlighted.
114
     *
115
     * @throws ReflectionException
116
     *
117
     * @return string The string representation of the variable.
118
     */
119 32
    public function asString(int $depth = 10, bool $highlight = false): string
120
    {
121 32
        $output = $this->dumpInternal($this->variable, true, $depth, 0);
122
123 32
        if ($highlight) {
124 1
            $result = highlight_string("<?php\n" . $output, true);
125 1
            $output = preg_replace('/&lt;\\?php<br \\/>/', '', $result, 1);
126
        }
127
128 32
        return $output;
129
    }
130
131
    /**
132
     * Exports a variable as a string containing PHP code.
133
     *
134
     * The string is a valid PHP expression that can be evaluated by PHP parser
135
     * and the evaluation result will give back the variable value.
136
     *
137
     * This method is similar to {@see var_export()}. The main difference is that
138
     * it generates more compact string representation using short array syntax.
139
     *
140
     * It also handles closures with {@see ClosureExporter} and objects
141
     * by using the PHP functions {@see serialize()} and {@see unserialize()}.
142
     *
143
     * @param bool $format Whatever to format code.
144
     * @param string[] $useVariables Array of variables used in `use` statement (['$params', '$config'])
145
     * @param bool $serializeObjects If it is true all objects will be serialized except objects with closure(s). If it
146
     * is false only objects of internal classes will be serialized.
147
     *
148
     * @throws ReflectionException
149
     *
150
     * @return string A PHP code representation of the variable.
151
     */
152 53
    public function export(bool $format = true, array $useVariables = [], bool $serializeObjects = true): string
153
    {
154 53
        $this->useVarInClosures = $useVariables;
155 53
        $this->serializeObjects = $serializeObjects;
156 53
        return $this->exportInternal($this->variable, $format, 0);
157
    }
158
159
    /**
160
     * @param mixed $var Variable to be dumped.
161
     * @param bool $format Whatever to format code.
162
     * @param int $depth Maximum depth.
163
     * @param int $level Current depth.
164
     *
165
     * @throws ReflectionException
166
     *
167
     * @return string
168
     */
169 32
    private function dumpInternal($var, bool $format, int $depth, int $level): string
170
    {
171 32
        switch (gettype($var)) {
172 32
            case 'resource':
173 31
            case 'resource (closed)':
174 1
                return '{resource}';
175 31
            case 'NULL':
176 1
                return 'null';
177 30
            case 'array':
178 6
                if ($depth <= $level) {
179 1
                    return '[...]';
180
                }
181
182 5
                if (empty($var)) {
183 2
                    return '[]';
184
                }
185
186 3
                $output = '';
187 3
                $keys = array_keys($var);
188 3
                $spaces = str_repeat($this->offset, $level);
189 3
                $output .= '[';
190
191 3
                foreach ($keys as $name) {
192 3
                    if ($format) {
193 3
                        $output .= "\n" . $spaces . $this->offset;
194
                    }
195 3
                    $output .= $this->exportVariable($name);
196 3
                    $output .= ' => ';
197 3
                    $output .= $this->dumpInternal($var[$name], $format, $depth, $level + 1);
198
                }
199
200 3
                return $format
201 3
                    ? $output . "\n" . $spaces . ']'
202 3
                    : $output . ']';
203 28
            case 'object':
204 16
                if ($var instanceof Closure) {
205 11
                    return $this->exportClosure($var);
206
                }
207
208 7
                if ($depth <= $level) {
209 1
                    return $this->getObjectDescription($var) . ' (...)';
210
                }
211
212 6
                $spaces = str_repeat($this->offset, $level);
213 6
                $output = $this->getObjectDescription($var) . "\n" . $spaces . '(';
214 6
                $objectProperties = $this->getObjectProperties($var);
215
216
                /** @psalm-var mixed $value */
217 6
                foreach ($objectProperties as $name => $value) {
218 4
                    $propertyName = strtr(trim((string) $name), "\0", '::');
219 4
                    $output .= "\n" . $spaces . $this->offset . '[' . $propertyName . '] => ';
220 4
                    $output .= $this->dumpInternal($value, $format, $depth, $level + 1);
221
                }
222 6
                return $output . "\n" . $spaces . ')';
223
            default:
224 14
                return $this->exportVariable($var);
225
        }
226
    }
227
228
    /**
229
     * @param mixed $variable Variable to be exported.
230
     * @param bool $format Whatever to format code.
231
     * @param int $level Current depth.
232
     *
233
     * @throws ReflectionException
234
     *
235
     * @return string
236
     */
237 53
    private function exportInternal($variable, bool $format, int $level): string
238
    {
239 53
        $spaces = str_repeat($this->offset, $level);
240 53
        switch (gettype($variable)) {
241 53
            case 'NULL':
242 2
                return 'null';
243 51
            case 'array':
244 9
                if (empty($variable)) {
245 2
                    return '[]';
246
                }
247
248 7
                $keys = array_keys($variable);
249 7
                $outputKeys = $keys !== array_keys($keys);
250 7
                $output = '[';
251
252 7
                foreach ($keys as $key) {
253 7
                    if ($format) {
254 4
                        $output .= "\n" . $spaces . $this->offset;
255
                    }
256 7
                    if ($outputKeys) {
257 3
                        $output .= $this->exportVariable($key);
258 3
                        $output .= ' => ';
259
                    }
260 7
                    $output .= $this->exportInternal($variable[$key], $format, $level + 1);
261 7
                    if ($format || next($keys) !== false) {
262 6
                        $output .= ',';
263
                    }
264
                }
265
266 7
                return $format
267 4
                    ? $output . "\n" . $spaces . ']'
268 7
                    : $output . ']';
269 49
            case 'object':
270 32
                if ($variable instanceof Closure) {
271 25
                    return $this->exportClosure($variable, $level);
272
                }
273
274 12
                $reflectionObject = new ReflectionObject($variable);
275
                try {
276 12
                    if ($this->serializeObjects || $reflectionObject->isInternal() || $reflectionObject->isAnonymous()) {
277 10
                        return "unserialize({$this->exportVariable(serialize($variable))})";
278
                    }
279
280 2
                    return $this->exportObject($variable, $reflectionObject, $format, $level);
281 6
                } catch (Exception $e) {
282
                    // Serialize may fail, for example: if object contains a `\Closure` instance so we use a fallback.
283 6
                    if ($this->serializeObjects && !$reflectionObject->isInternal() && !$reflectionObject->isAnonymous()) {
284
                        try {
285 4
                            return $this->exportObject($variable, $reflectionObject, $format, $level);
286
                        } catch (Exception $e) {
287
                            return $this->exportObjectFallback($variable, $format, $level);
288
                        }
289
                    }
290
291 2
                    return $this->exportObjectFallback($variable, $format, $level);
292
                }
293
            default:
294 19
                return $this->exportVariable($variable);
295
        }
296
    }
297
298 6
    private function getPropertyName(string $property): string
299
    {
300 6
        $property = str_replace("\0", '::', trim($property));
301
302 6
        if (strpos($property, '*::') === 0) {
303
            return substr($property, 3);
304
        }
305
306 6
        if (($pos = strpos($property, '::')) !== false) {
307 4
            return substr($property, $pos + 2);
308
        }
309
310 2
        return $property;
311
    }
312
313
    /**
314
     * @param object $variable
315
     * @param bool $format
316
     * @param int $level
317
     *
318
     * @throws ReflectionException
319
     *
320
     * @return string
321
     */
322 2
    private function exportObjectFallback(object $variable, bool $format, int $level): string
323
    {
324 2
        if ($variable instanceof ArrayableInterface) {
325
            return $this->exportInternal($variable->toArray(), $format, $level);
326
        }
327
328 2
        if ($variable instanceof JsonSerializable) {
329
            return $this->exportInternal($variable->jsonSerialize(), $format, $level);
330
        }
331
332 2
        if ($variable instanceof IteratorAggregate) {
333
            return $this->exportInternal(iterator_to_array($variable), $format, $level);
334
        }
335
336
        /** @psalm-suppress RedundantCondition */
337 2
        if ('__PHP_Incomplete_Class' !== get_class($variable) && method_exists($variable, '__toString')) {
338
            return $this->exportVariable($variable->__toString());
339
        }
340
341 2
        return $this->exportVariable(self::create($variable)->asString());
342
    }
343
344 6
    private function exportObject(object $variable, ReflectionObject $reflectionObject, bool $format, int $level): string
345
    {
346 6
        $spaces = str_repeat($this->offset, $level);
347 6
        $objectProperties = $this->getObjectProperties($variable);
348 6
        $class = get_class($variable);
349 6
        $use = $this->useVarInClosures === [] ? '' : ' use (' . implode(', ', $this->useVarInClosures) . ')';
350 6
        $lines = ['(static function ()' . $use . ' {',];
351 6
        if ($reflectionObject->getConstructor() === null) {
352 2
            $lines = array_merge($lines, [
353 2
                $this->offset . '$object = new ' . $class . '();',
354 2
                $this->offset . '(function ()' . $use . ' {',
355
            ]);
356
        } else {
357 4
            $lines = array_merge($lines, [
358 4
                $this->offset . '$class = new \ReflectionClass(\'' . $class . '\');',
359 4
                $this->offset . '$object = $class->newInstanceWithoutConstructor();',
360 4
                $this->offset . '(function ()' . $use . ' {',
361
            ]);
362
        }
363 6
        $endLines = [
364 6
            $this->offset . '})->bindTo($object, \'' . $class . '\')();',
365
            '',
366 6
            $this->offset . 'return $object;',
367
            '})()',
368
        ];
369
370
        /**
371
         * @psalm-var mixed $value
372
         * @psalm-var string $name
373
         */
374 6
        foreach ($objectProperties as $name => $value) {
375 6
            $propertyName = $this->getPropertyName($name);
376 6
            $lines[] = $this->offset . $this->offset . '$this->' . $propertyName . ' = ' .
377 6
                $this->exportInternal($value, $format, $level + 2) . ';';
378
        }
379
380 6
        return implode("\n" . ($format ? $spaces : ''), array_merge($lines, $endLines));
381
    }
382
383
    /**
384
     * Exports a {@see \Closure} instance.
385
     *
386
     * @param Closure $closure Closure instance.
387
     *
388
     * @throws ReflectionException
389
     *
390
     * @return string
391
     */
392 36
    private function exportClosure(Closure $closure, int $level = 0): string
393
    {
394 36
        if (self::$closureExporter === null) {
395 1
            self::$closureExporter = new ClosureExporter();
396
        }
397
398 36
        return self::$closureExporter->export($closure, $level);
0 ignored issues
show
Bug introduced by
The method export() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

398
        return self::$closureExporter->/** @scrutinizer ignore-call */ export($closure, $level);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
399
    }
400
401
    /**
402
     * @param mixed $variable
403
     *
404
     * @return string
405
     */
406 41
    private function exportVariable($variable): string
407
    {
408 41
        return var_export($variable, true);
409
    }
410
411 7
    private function getObjectDescription(object $object): string
412
    {
413 7
        return get_class($object) . '#' . spl_object_id($object);
414
    }
415
416 12
    private function getObjectProperties(object $var): array
417
    {
418 12
        if (!$var instanceof __PHP_Incomplete_Class && method_exists($var, '__debugInfo')) {
419
            /** @var array $var */
420 1
            $var = $var->__debugInfo();
421
        }
422
423 12
        return (array) $var;
424
    }
425
}
426