phabel/src/Target/Php70/AnonymousClassReplacer.php

60 lines
1.4 KiB
PHP
Raw Normal View History

2020-08-03 21:31:32 +02:00
<?php
2020-08-13 18:30:12 +02:00
namespace Phabel\Target\Php70;
2020-08-03 21:31:32 +02:00
2020-08-14 14:43:29 +02:00
use Phabel\Context;
2020-08-13 18:30:12 +02:00
use Phabel\Plugin;
2020-08-14 14:43:29 +02:00
use Phabel\RootNode;
2020-08-03 21:31:32 +02:00
use PhpParser\Node;
2020-08-14 14:43:29 +02:00
use PhpParser\Node\Expr\New_;
2020-09-05 20:52:54 +02:00
use PhpParser\Node\Identifier;
2020-08-14 14:43:29 +02:00
use PhpParser\Node\Stmt\Namespace_;
2020-08-03 21:31:32 +02:00
2020-08-13 18:30:12 +02:00
class AnonymousClassReplacer extends Plugin
2020-08-03 21:31:32 +02:00
{
/**
2020-08-14 14:43:29 +02:00
* Anonymous class count.
2020-08-03 21:31:32 +02:00
*/
2020-08-14 14:43:29 +02:00
private int $count = 0;
2020-08-03 21:31:32 +02:00
/**
2020-08-14 14:43:29 +02:00
* Current file name hash.
2020-08-03 21:31:32 +02:00
*/
2020-08-14 14:43:29 +02:00
private string $fileName = '';
/**
* {@inheritDoc}
*/
public function shouldRunFile(string $file): bool
2020-08-03 21:31:32 +02:00
{
2020-08-14 14:43:29 +02:00
$this->fileName = \hash('sha256', $file);
return parent::shouldRunFile($file);
}
2020-08-03 21:31:32 +02:00
2020-08-14 14:43:29 +02:00
/**
* Leave new.
*
* @param New_ $node New stmt
* @param Context $ctx Context
*
* @return void
*/
public function leaveNew(New_ $node, Context $ctx): void
{
2020-08-03 21:31:32 +02:00
$classNode = $node->class;
if (!$classNode instanceof Node\Stmt\Class_) {
return;
}
2020-09-05 20:52:54 +02:00
$classNode->name = new Identifier('PhabelAnonymousClass'.$this->fileName.($this->count++));
2020-08-03 21:31:32 +02:00
2020-09-05 20:52:54 +02:00
$node->class = new Node\Name($classNode->name->name);
2020-08-03 21:31:32 +02:00
2020-08-14 14:43:29 +02:00
foreach ($ctx->parents as $node) {
if ($node instanceof Namespace_ || $node instanceof RootNode) {
2020-09-05 20:52:54 +02:00
$ctx->insertBefore($ctx->getCurrentChild($node), $classNode);
2020-08-14 20:40:01 +02:00
return;
2020-08-14 14:43:29 +02:00
}
}
throw new \RuntimeException('Could not find hook for inserting anonymous class!');
2020-08-03 21:31:32 +02:00
}
}