SyntaxHighlighter::highlight()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

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 8
nc 3
nop 1
1
<?php
2
3
namespace PhpSchool\PSX;
4
5
use PhpParser\Error;
6
use PhpParser\Parser;
7
8
/**
9
 * Class SyntaxHighlighter
10
 * @package PhpSchool\PSX
11
 * @author Aydin Hassan <[email protected]>
12
 */
13
14
class SyntaxHighlighter
15
{
16
    /**
17
     * @var \PhpParser\Parser
18
     */
19
    private $parser;
20
21
    /**
22
     * @var SyntaxHighlightPrinter
23
     */
24
    private $printer;
25
26
    /**
27
     * @param Parser $parser
28
     * @param SyntaxHighlightPrinter $printer
29
     */
30
    public function __construct(Parser $parser, SyntaxHighlightPrinter $printer)
31
    {
32
        $this->parser = $parser;
33
        $this->printer = $printer;
34
    }
35
36
    /**
37
     * @param string $code
38
     * @return string
39
     */
40
    public function highlight($code)
41
    {
42
        if (!is_string($code)) {
43
            throw new \InvalidArgumentException('Argument 1 should be a string of valid PHP code');
44
        }
45
        try {
46
            $statements = $this->parser->parse($code);
47
        } catch (Error $e) {
48
            throw new \InvalidArgumentException('PHP could not be parsed');
49
        }
50
51
        return $this->printer->prettyPrintFile($statements);
0 ignored issues
show
Bug introduced by
It seems like $statements defined by $this->parser->parse($code) on line 46 can also be of type null; however, PhpSchool\PSX\SyntaxHigh...nter::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...
52
    }
53
}
54