Completed
Push — master ( 446f2e...32b2c3 )
by Nelson
11:26
created

ExporterPlugin::export()   C

Complexity

Conditions 13
Paths 28

Size

Total Lines 67
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 41
nc 28
nop 3
dl 0
loc 67
rs 5.8281
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * PHP: Nelson Martell Library file
4
 *
5
 * Content:
6
 * - Trait definition
7
 *
8
 * Copyright © 2016 Nelson Martell (http://nelson6e65.github.io)
9
 *
10
 * Licensed under The MIT License (MIT)
11
 * For full copyright and license information, please see the LICENSE
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright 2016 Nelson Martell
15
 * @link      http://nelson6e65.github.io/php_nml/
16
 * @since     v0.6.0
17
 * @license   http://www.opensource.org/licenses/mit-license.php The MIT License (MIT)
18
 * */
19
20
namespace NelsonMartell\Test\Helpers;
21
22
use NelsonMartell as NML;
23
use NelsonMartell\Extensions\String;
24
use SebastianBergmann\Exporter\Exporter;
25
use \InvalidArgumentException;
26
27
/**
28
 * Plugin to export variables in test clases.
29
 *
30
 * @author Nelson Martell <[email protected]>
31
 * @internal
32
 * */
33
trait ExporterPlugin
34
{
35
    protected static $exporter = null;
36
37
    /**
38
     * Extract the string representation of specified object in one line.
39
     *
40
     * @param mixed   $obj   Object to export.
41
     * @param integer $depth How many levels of depth will export in arrays and objects. If $depth <= 0,
42
     *   only '...' will be returned for content of object or array. Default: ``2``.
43
     * @param bool    $short If class names are returned without namespace. Default: ``false``.
44
     *
45
     * @return string
46
     * @see Exporter::shortenedRecursiveExport()
47
     * @see Exporter::export()
48
     */
49
    public static function export($obj, $depth = 2, $short = false)
50
    {
51
        if (static::$exporter === null) {
52
            static::$exporter = new Exporter();
53
        }
54
55
        $depth = ((integer) $depth < 0) ? 0 : (integer) $depth;
56
        $short = (boolean) $short;
57
        $str   = null;
0 ignored issues
show
Unused Code introduced by
$str is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
58
59
        if (is_object($obj)) {
60
            $className = static::getClass($obj, $short);
61
62
            if ($depth <= 0) {
63
                // Do not show properties
64
                $content = '{...}';
65
            } else {
66
                $arrayObject = static::$exporter->toArray($obj);
67
                // Initial content without deep
68
                $content = static::export($arrayObject, 1, $short);
69
                // Replace array braces and separator
70
                $content = str_replace([' => ', '[ ', ' ]'], [': ', '{ ', ' }'], $content);
71
72
                // var_dump($content, $depth);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
73
74
                if ($depth > 1) {
75
                    foreach ($arrayObject as $key => $value) {
76
                        $format = '{0}: {1}';
77
78
                        if (is_object($value)) {
79
                            $sclass = static::getClass($value, $short);
80
81
                            $sVal = "$sclass({...})";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $sclass instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
82
                        } elseif (is_array($value)) {
83
                            $sVal = '[...]';
84
                        } else {
85
                            continue;
86
                        }
87
88
                        $search      = String::format($format, $key, $sVal);
89
                        $replacement = String::format($format, $key, static::export($value, $depth - 1, $short));
90
91
                        $content = str_replace($search, $replacement, $content);
92
                    }
93
                }
94
            }
95
96
            $str = String::format('{0}({1})', $className, $content);
97
            $str = str_replace(',  }', ' }', $str);
98
        } elseif (is_array($obj)) {
99
            if ($depth <= 0) {
100
                $str = count($obj) > 0 ? '[...]' : '';
101
            } else {
102
                $str = '';
103
                foreach ($obj as $key => $value) {
104
                    // Export all items recursively
105
                    $str .= String::format('{0} => {1}, ', $key, static::export($value, $depth - 1, $short));
106
                }
107
                $str = String::format('[ {0} ]', $str);
108
                $str = str_replace(',  ]', ' ]', $str);
109
            }
110
        } else {
111
            $str = static::$exporter->export($obj);
112
        }
113
114
        return $str;
115
    }
116
117
118
    /**
119
     * Exports class name of an object instance.
120
     *
121
     * @param object  $obj   Object to get the class name.
122
     * @param boolean $short Return only class name without namespace.
123
     *
124
     * @return string
125
     */
126
    public static function getClass($obj, $short = false)
127
    {
128
        if (!is_object($obj)) {
129
            throw new InvalidArgumentException('Object argument is not an object instance.');
130
        }
131
        $className = get_class($obj);
132
        if ($short) {
133
            $pos = strrpos($className, '\\');
134
            if ($pos !== false) {
135
                // Get class name without namespace
136
                $className = substr($className, $pos + 1);
137
            }
138
        }
139
        return $className;
140
    }
141
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
142