Completed
Push — master ( 2ac042...4e5e3b )
by Nate
02:40
created

ArrayPrinter::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 3
eloc 7
nc 4
nop 2
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
use Tebru\Retrofit\Exception\RetrofitException;
14
15
/**
16
 * Class ArrayPrinter
17
 *
18
 * @author Nate Brunette <[email protected]>
19
 */
20
class ArrayPrinter
21
{
22
    /**
23
     * @var Parser
24
     */
25
    private $parser;
26
27
    /**
28
     * @var PrettyPrinterAbstract
29
     */
30
    private $printer;
31
32
    /**
33
     * Constructor
34
     *
35
     * @param Parser $parser
36
     * @param PrettyPrinterAbstract $printer
37
     */
38
    public function __construct(Parser $parser = null, PrettyPrinterAbstract $printer = null)
39
    {
40
        if (null === $parser) {
41
            $parser = new Parser(new Lexer());
42
        }
43
44
        if (null === $printer) {
45
            $printer = new Standard();
46
        }
47
48
        $this->parser = $parser;
49
        $this->printer = $printer;
50
    }
51
52
    /**
53
     * Take a PHP array and convert it to a string
54
     *
55
     * @param array $array
56
     * @return string
57
     * @throws RetrofitException
58
     */
59
    public function printArray(array $array)
60
    {
61
        $string = var_export($array, true);
62
        $string = preg_replace('/\'\$(.+)\'/', '$' . '\\1', $string);
63
64
        $statements = $this->parser->parse($string);
65
66
        if (null === $statements) {
67
            throw new RetrofitException('There was an error parsing the array');
68
        }
69
70
        return $this->printer->prettyPrintFile($statements);
71
    }
72
}
73