Completed
Push — master ( fc51f9...b3b654 )
by Freek
03:59
created

Converter::getPhp5Code()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 16
rs 9.4285
cc 1
eloc 8
nc 1
nop 0
1
<?php
2
3
namespace Spatie\Php7to5;
4
5
use PhpParser\NodeTraverser;
6
use PhpParser\ParserFactory;
7
use Spatie\Php7to5\Exceptions\InvalidParameter;
8
9
class Converter
10
{
11
    /** @var string */
12
    protected $pathToPhp7Code;
13
14
    public function __construct(string $pathToPhp7Code)
15
    {
16
        if (!file_exists($pathToPhp7Code)) {
17
            throw InvalidParameter::fileDoesNotExist($pathToPhp7Code);
18
        }
19
20
        $this->pathToPhp7Code = $pathToPhp7Code;
21
    }
22
23
    public function saveAsPhp5(string $destination)
24
    {
25
        file_put_contents($destination, $this->getPhp5Code());
26
    }
27
28
    public function getPhp5Code() : string
29
    {
30
        ini_set('xdebug.max_nesting_level', 3000);
31
32
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
33
34
        $php7code = file_get_contents($this->pathToPhp7Code);
35
36
        $php7Statements = $parser->parse($php7code);
37
38
        $traverser = $this->getTraverser();
39
40
        $php5Statements = $traverser->traverse($php7Statements);
41
42
        return (new \PhpParser\PrettyPrinter\Standard())->prettyPrintFile($php5Statements);
43
    }
44
45
    protected function getTraverser() : NodeTraverser
46
    {
47
        $traverser = new NodeTraverser();
48
49
        foreach (glob(__DIR__.'/NodeVisitors/*.php') as $nodeVisitorFile) {
50
            $className = pathinfo($nodeVisitorFile, PATHINFO_FILENAME);
51
52
            $fullClassName = '\\Spatie\\Php7to5\\NodeVisitors\\'.$className;
53
54
            $traverser->addVisitor(new $fullClassName());
55
        }
56
57
        return $traverser;
58
    }
59
}
60