1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Composer\Config\Reader; |
6
|
|
|
|
7
|
|
|
use PhpParser\Node\Stmt; |
8
|
|
|
use PhpParser\Node\Stmt\Use_; |
9
|
|
|
use PhpParser\ParserFactory; |
10
|
|
|
use Yiisoft\Composer\Config\Util\PhpPrinter; |
11
|
|
|
|
12
|
1 |
|
/** |
13
|
|
|
* PhpReader - reads PHP files. |
14
|
1 |
|
*/ |
15
|
|
|
class PhpReader extends AbstractReader |
16
|
1 |
|
{ |
17
|
1 |
|
protected function readRaw(string $path) |
18
|
1 |
|
{ |
19
|
|
|
$ast = $this->parsePhp($path); |
20
|
1 |
|
$this->extractUses($ast); |
21
|
|
|
$newCode = $this->printPhp($ast); |
22
|
|
|
|
23
|
|
|
//$newFile = $this->builder->getOutputPath(basename($path) . '.' .md5($newCode) . '.ast'); |
24
|
|
|
$newFile = $path . '.new.php'; |
25
|
|
|
file_put_contents($newFile, $newCode); |
26
|
|
|
$output = $this->requireWithParams($newFile); |
27
|
|
|
@unlink($newFile); |
|
|
|
|
28
|
|
|
|
29
|
|
|
return $output; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @return mixed |
34
|
|
|
*/ |
35
|
|
|
protected function requireWithParams(string $path) |
36
|
|
|
{ |
37
|
|
|
$params = $this->builder->getVars()['params'] ?? []; |
38
|
|
|
|
39
|
|
|
$result = static function (array $params) { |
40
|
|
|
return require func_get_arg(1); |
41
|
|
|
}; |
42
|
|
|
|
43
|
|
|
return $result($params, $path); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
|
47
|
|
|
protected function parsePhp(string $path): array |
48
|
|
|
{ |
49
|
|
|
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); |
50
|
|
|
|
51
|
|
|
return $parser->parse(file_get_contents($path)); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
protected function extractUses($ast) |
55
|
|
|
{ |
56
|
|
|
/** @var Stmt $node */ |
57
|
|
|
foreach ($ast as $node){ |
58
|
|
|
if (isset($node->type) && $node->type == Use_::TYPE_NORMAL and !empty($node->uses)) { |
59
|
|
|
foreach ($node->uses as $use) { |
60
|
|
|
$className = end($use->name->parts); |
61
|
|
|
$this->builder->uses[$className] = 'use ' . implode('\\', $use->name->parts) . ';'; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
protected function printPhp(array $ast): string |
68
|
|
|
{ |
69
|
|
|
$printer = new PhpPrinter([ |
70
|
|
|
//'builder' => $this->builder, |
71
|
|
|
//'context' => $path, |
72
|
|
|
]); |
73
|
|
|
|
74
|
|
|
return $printer->prettyPrintFile($ast); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: