Completed
Branch develop (972ca0)
by Nate
02:45
created

ArrayPrinter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 48
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 3
A printArray() 0 9 1
1
<?php
2
/*
3
 * Copyright (c) 2015 Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
namespace Tebru\Retrofit\Generation\Printer;
8
9
use PhpParser\Lexer;
10
use PhpParser\Parser;
11
use PhpParser\PrettyPrinter\Standard;
12
use PhpParser\PrettyPrinterAbstract;
13
14
/**
15
 * Class ArrayPrinter
16
 *
17
 * @author Nate Brunette <[email protected]>
18
 */
19
class ArrayPrinter
20
{
21
    /**
22
     * @var Parser
23
     */
24
    private $parser;
25
26
    /**
27
     * @var PrettyPrinterAbstract
28
     */
29
    private $printer;
30
31
    /**
32
     * Constructor
33
     *
34
     * @param Parser $parser
35
     * @param PrettyPrinterAbstract $printer
36
     */
37
    public function __construct(Parser $parser = null, PrettyPrinterAbstract $printer = null)
38
    {
39
        if (null === $parser) {
40
            $parser = new Parser(new Lexer());
41
        }
42
43
        if (null === $printer) {
44
            $printer = new Standard();
45
        }
46
47
        $this->parser = $parser;
48
        $this->printer = $printer;
49
    }
50
51
    /**
52
     * Take a PHP array and convert it to a string
53
     *
54
     * @param array $array
55
     * @return string
56
     */
57
    public function printArray(array $array)
58
    {
59
        $string = var_export($array, true);
60
        $string = preg_replace('/\'\$(.+)\'/', '$' . '\\1', $string);
61
62
        $statements = $this->parser->parse($string);
63
64
        return $this->printer->prettyPrintFile($statements);
0 ignored issues
show
Bug introduced by
It seems like $statements defined by $this->parser->parse($string) on line 62 can also be of type null; however, PhpParser\PrettyPrinterAbstract::prettyPrintFile() does only seem to accept array<integer,object<PhpParser\Node>>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
65
    }
66
}
67