Dumper   B
last analyzed

Complexity

Total Complexity 42

Size/Duplication

Total Lines 135
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 42
c 3
b 0
f 0
lcom 0
cbo 2
dl 0
loc 135
rs 8.295

3 Methods

Rating   Name   Duplication   Size   Complexity  
C dump() 0 23 12
C dumpInline() 0 56 23
C dumpInlineArray() 0 28 7

How to fix   Complexity   

Complex Class

Complex classes like Dumper 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 Dumper, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Scabbia2 Yaml Component
4
 * https://github.com/eserozvataf/scabbia2
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 *
9
 * @link        https://github.com/eserozvataf/scabbia2-yaml for the canonical source repository
10
 * @copyright   2010-2016 Eser Ozvataf. (http://eser.ozvataf.com/)
11
 * @license     http://www.apache.org/licenses/LICENSE-2.0 - Apache License, Version 2.0
12
 *
13
 * -------------------------
14
 * Portions of this code are from Symfony YAML Component under the MIT license.
15
 *
16
 * (c) Fabien Potencier <[email protected]>
17
 *
18
 * For the full copyright and license information, please view the LICENSE-MIT
19
 * file that was distributed with this source code.
20
 *
21
 * Modifications made:
22
 * - Scabbia Framework code styles applied.
23
 * - All dump methods are moved under Dumper class.
24
 * - Redundant classes removed.
25
 * - Namespace changed.
26
 * - Tests ported to Scabbia2.
27
 * - Encoding checks removed.
28
 */
29
30
namespace Scabbia\Yaml;
31
32
use Scabbia\Yaml\Inline;
33
34
/**
35
 * Dumper dumps PHP variables to YAML strings
36
 *
37
 * @package     Scabbia\Yaml
38
 * @author      Fabien Potencier <[email protected]>
39
 * @author      Eser Ozvataf <[email protected]>
40
 * @since       2.0.0
41
 */
42
class Dumper
43
{
44
    /**
45
     * Dumps a PHP value to YAML
46
     *
47
     * @param mixed   $input                  The PHP value
48
     * @param int     $inline                 The level where you switch to inline YAML
49
     * @param int     $indentation            The level of indentation (used internally)
50
     *
51
     * @return string  The YAML representation of the PHP value
52
     */
53
    public static function dump($input, $inline = 0, $indentation = 0)
54
    {
55
        $output = "";
56
        $prefix = $indentation ? str_repeat(" ", $indentation) : "";
57
58
        if ($inline <= 0 || !is_array($input) || count($input) === 0) {
59
            $output .= $prefix . self::dumpInline($input);
60
        } else {
61
            $isAHash = array_keys($input) !== range(0, count($input) - 1);
62
63
            foreach ($input as $key => $value) {
64
                $willBeInlined = (($inline - 1 <= 0) || !is_array($value) || count($value) === 0);
65
66
                $output .= $prefix .
67
                    ($isAHash ? self::dumpInline($key) . ":" : "-") .
68
                    ($willBeInlined ? " " : "\n") .
69
                    self::dump($value, $inline - 1, ($willBeInlined ? 0 : $indentation)) .
70
                    ($willBeInlined ? "\n" : "");
71
            }
72
        }
73
74
        return $output;
75
    }
76
77
    /**
78
     * Dumps a given PHP variable to a YAML string
79
     *
80
     * @param mixed   $value                  The PHP variable to convert
81
     *
82
     * @return string The YAML string representing the PHP array
83
     */
84
    public static function dumpInline($value)
85
    {
86
        if (is_resource($value)) {
87
            return "null";
88
        } elseif (is_object($value)) {
89
            return "!!php/object:" . serialize($value);
90
        } elseif (is_array($value)) {
91
            return self::dumpInlineArray($value);
92
        } elseif ($value === null) {
93
            return "null";
94
        } elseif ($value === true) {
95
            return "true";
96
        } elseif ($value === false) {
97
            return "false";
98
        } elseif (ctype_digit($value)) {
99
            return is_string($value) ? "\"$value\"" : (int)$value;
100
        } elseif (is_numeric($value)) {
101
            $locale = setlocale(LC_NUMERIC, 0);
102
            if ($locale !== false) {
103
                setlocale(LC_NUMERIC, "C");
104
            }
105
106
            if (is_float($value)) {
107
                $repr = (string)$value;
108
109
                if (is_infinite($value)) {
110
                    $repr = str_ireplace("INF", ".Inf", $repr);
111
                } elseif (floor($value) == $value && $repr == $value) {
112
                    // Preserve float data type since storing a whole number will result in integer value.
113
                    $repr = "!!float {$repr}";
114
                }
115
            } elseif (is_string($value)) {
116
                $repr = "'$value'";
117
            } else {
118
                $repr = (string)$value;
119
            }
120
121
            if ($locale !== false) {
122
                setlocale(LC_NUMERIC, $locale);
123
            }
124
125
            return $repr;
126
        } elseif ($value === "") {
127
            return "''";
128
        } elseif (strstr($value, "\n") !== false) {
129
            return "|\n  " . preg_replace("/\\n/", "\n  ", $value);
130
        } elseif (Escaper::requiresDoubleQuoting($value)) {
0 ignored issues
show
Bug introduced by
It seems like $value defined by parameter $value on line 84 can also be of type boolean or resource; however, Scabbia\Yaml\Escaper::requiresDoubleQuoting() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
131
            return Escaper::escapeWithDoubleQuotes($value);
0 ignored issues
show
Bug introduced by
It seems like $value defined by parameter $value on line 84 can also be of type boolean or resource; however, Scabbia\Yaml\Escaper::escapeWithDoubleQuotes() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
132
        } elseif (Escaper::requiresSingleQuoting($value) ||
0 ignored issues
show
Bug introduced by
It seems like $value defined by parameter $value on line 84 can also be of type boolean or resource; however, Scabbia\Yaml\Escaper::requiresSingleQuoting() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
133
            preg_match(Inline::getHexRegex(), $value) ||
134
            preg_match(Inline::getTimestampRegex(), $value)) {
135
            return Escaper::escapeWithSingleQuotes($value);
0 ignored issues
show
Bug introduced by
It seems like $value defined by parameter $value on line 84 can also be of type boolean or resource; however, Scabbia\Yaml\Escaper::escapeWithSingleQuotes() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
136
        } else {
137
            return $value;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $value; (string|boolean|resource) is incompatible with the return type documented by Scabbia\Yaml\Dumper::dumpInline of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
138
        }
139
    }
140
141
    /**
142
     * Dumps a PHP array to a YAML string
143
     *
144
     * @param array   $value                  The PHP array to dump
145
     *
146
     * @return string The YAML string representing the PHP array
147
     */
148
    protected static function dumpInlineArray(array $value)
149
    {
150
        // array
151
        $keys = array_keys($value);
152
        $keysCount = count($keys);
153
        $func = function ($v, $w) {
154
            return (int)$v + $w;
155
        };
156
157
        if (($keysCount === 1 && $keys[0] === "0") ||
158
            ($keysCount > 1 && array_reduce($keys, $func, 0) == $keysCount * ($keysCount - 1) / 2)
159
        ) {
160
            $output = [];
161
            foreach ($value as $val) {
162
                $output[] = self::dumpInline($val);
163
            }
164
165
            return "[" . implode(", ", $output) . "]";
166
        }
167
168
        // mapping
169
        $output = [];
170
        foreach ($value as $key => $val) {
171
            $output[] = self::dumpInline($key) . ": " . self::dumpInline($val);
172
        }
173
174
        return "{ " . implode(", ", $output) . " }";
175
    }
176
}
177