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

Converter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 51
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A saveAsPhp5() 0 4 1
A getPhp5Code() 0 16 1
A getTraverser() 0 14 2
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