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
|
|
|
/** |
15
|
|
|
* @param string $pathToPhp7Code |
16
|
|
|
* |
17
|
|
|
* @throws \Spatie\Php7to5\Exceptions\InvalidParameter |
18
|
|
|
*/ |
19
|
|
|
public function __construct($pathToPhp7Code) |
20
|
|
|
{ |
21
|
|
|
if (!file_exists($pathToPhp7Code)) { |
22
|
|
|
throw InvalidParameter::fileDoesNotExist($pathToPhp7Code); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
$this->pathToPhp7Code = $pathToPhp7Code; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $destination |
30
|
|
|
*/ |
31
|
|
|
public function saveAsPhp5($destination) |
32
|
|
|
{ |
33
|
|
|
file_put_contents($destination, $this->getPhp5Code()); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @return string |
38
|
|
|
*/ |
39
|
|
|
public function getPhp5Code() |
40
|
|
|
{ |
41
|
|
|
ini_set('xdebug.max_nesting_level', 9000); |
42
|
|
|
|
43
|
|
|
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); |
44
|
|
|
|
45
|
|
|
$php7code = file_get_contents($this->pathToPhp7Code); |
46
|
|
|
|
47
|
|
|
$php7Statements = $parser->parse($php7code); |
48
|
|
|
|
49
|
|
|
$traverser = $this->getTraverser(); |
50
|
|
|
|
51
|
|
|
$php5Statements = $traverser->traverse($php7Statements); |
|
|
|
|
52
|
|
|
|
53
|
|
|
return (new \PhpParser\PrettyPrinter\Standard())->prettyPrintFile($php5Statements); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @return \PhpParser\NodeTraverser |
58
|
|
|
*/ |
59
|
|
|
public static function getTraverser() |
60
|
|
|
{ |
61
|
|
|
$traverser = new NodeTraverser(); |
62
|
|
|
|
63
|
|
|
foreach (glob(__DIR__.'/NodeVisitors/*.php') as $nodeVisitorFile) { |
64
|
|
|
$className = pathinfo($nodeVisitorFile, PATHINFO_FILENAME); |
65
|
|
|
|
66
|
|
|
$fullClassName = '\\Spatie\\Php7to5\\NodeVisitors\\'.$className; |
67
|
|
|
|
68
|
|
|
$traverser->addVisitor(new $fullClassName()); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return $traverser; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
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:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.