rector/rules/RemovingStatic/Printer/FactoryClassPrinter.php
Tomas Votruba 345a89a7e2 Updated Rector to commit a657258f317da1f6fd42069bf3b09198d3cfd635
a657258f31 cleanup CHANGELOG, is part of GitHub releases now (#2)
2021-05-10 00:23:30 +00:00

68 lines
2.9 KiB
PHP

<?php
declare (strict_types=1);
namespace Rector\RemovingStatic\Printer;
use RectorPrefix20210510\Nette\Utils\Strings;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Namespace_;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\Core\PhpParser\Printer\BetterStandardPrinter;
use Rector\Core\Provider\CurrentFileProvider;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
use RectorPrefix20210510\Symplify\SmartFileSystem\SmartFileSystem;
final class FactoryClassPrinter
{
/**
* @var NodeNameResolver
*/
private $nodeNameResolver;
/**
* @var SmartFileSystem
*/
private $smartFileSystem;
/**
* @var BetterStandardPrinter
*/
private $betterStandardPrinter;
/**
* @var CurrentFileProvider
*/
private $currentFileProvider;
public function __construct(\Rector\Core\PhpParser\Printer\BetterStandardPrinter $betterStandardPrinter, \RectorPrefix20210510\Symplify\SmartFileSystem\SmartFileSystem $smartFileSystem, \Rector\NodeNameResolver\NodeNameResolver $nodeNameResolver, \Rector\Core\Provider\CurrentFileProvider $currentFileProvider)
{
$this->nodeNameResolver = $nodeNameResolver;
$this->betterStandardPrinter = $betterStandardPrinter;
$this->smartFileSystem = $smartFileSystem;
$this->currentFileProvider = $currentFileProvider;
}
public function printFactoryForClass(\PhpParser\Node\Stmt\Class_ $factoryClass, \PhpParser\Node\Stmt\Class_ $oldClass) : void
{
$parentNode = $oldClass->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::PARENT_NODE);
if ($parentNode instanceof \PhpParser\Node\Stmt\Namespace_) {
$newNamespace = clone $parentNode;
$newNamespace->stmts = [];
$newNamespace->stmts[] = $factoryClass;
$nodeToPrint = $newNamespace;
} else {
$nodeToPrint = $factoryClass;
}
$factoryClassFilePath = $this->createFactoryClassFilePath($oldClass);
$factoryClassContent = $this->betterStandardPrinter->prettyPrintFile([$nodeToPrint]);
$this->smartFileSystem->dumpFile($factoryClassFilePath, $factoryClassContent);
}
private function createFactoryClassFilePath(\PhpParser\Node\Stmt\Class_ $oldClass) : string
{
$file = $this->currentFileProvider->getFile();
$smartFileInfo = $file->getSmartFileInfo();
$directoryPath = \RectorPrefix20210510\Nette\Utils\Strings::before($smartFileInfo->getRealPath(), \DIRECTORY_SEPARATOR, -1);
$resolvedOldClass = $this->nodeNameResolver->getName($oldClass);
if ($resolvedOldClass === null) {
throw new \Rector\Core\Exception\ShouldNotHappenException();
}
$bareClassName = \RectorPrefix20210510\Nette\Utils\Strings::after($resolvedOldClass, '\\', -1) . 'Factory.php';
return $directoryPath . \DIRECTORY_SEPARATOR . $bareClassName;
}
}