VarExporter   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A export() 0 12 1
A formatLine() 0 9 3
A formatLines() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Frostaly\VarExporter;
6
7
use Frostaly\VarExporter\Contracts\EncoderInterface;
8
9
/**
10
 * Generate PHP code from variables.
11
 *
12
 * VarExporter is an alternative to var_export() with more features.
13
 *
14
 * By leveraging OPcache, the generated PHP code is faster than doing the same with unserialize().
15
 */
16
final class VarExporter
17
{
18
    /**
19
     * Export the given value to PHP code.
20
     *
21
     * @param mixed $value The variable to export.
22
     * @param int $indent The indentation level.
23
     * @param EncoderInterface[] $encoders The registered encoders.
24
     */
25
    public static function export(mixed $value, int $indent = 0, ?array $encoders = null): string
26
    {
27
        $encoder = new Encoder($encoders ?? [
28
            new Encoders\ArrayEncoder(),
29
            new Encoders\NativeEncoder(),
30
            new Encoders\StdClassEncoder(),
31
            new Encoders\SetStateEncoder(),
32
            new Encoders\SerializeEncoder(),
33
            new Encoders\ObjectEncoder(),
0 ignored issues
show
Bug introduced by
The type Frostaly\VarExporter\Encoders\ObjectEncoder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
        ]);
35
36
        return self::formatLine($encoder->encode($value), $indent);
37
    }
38
39
    /**
40
     * Iteratively reduce line segments to a string.
41
     */
42
    private static function formatLine(array $segments, int $depth): string
43
    {
44
        $code = '';
45
        foreach ($segments as $segment) {
46
            $code .= is_array($segment)
47
                ? self::formatLines($segment, $depth)
48
                : $segment;
49
        }
50
        return $code;
51
    }
52
53
    /**
54
     * Iteratively reduce multiple lines to a string.
55
     */
56
    private static function formatLines(array $lines, int $depth): string
57
    {
58
        $code = '';
59
        $newLine = PHP_EOL . str_repeat('    ', ++$depth);
60
        foreach ($lines as $segments) {
61
            $code .= $newLine . self::formatLine($segments, $depth);
62
        }
63
        return $code . PHP_EOL . str_repeat('    ', --$depth);
64
    }
65
}
66