![]() Server : Apache System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64 User : corals ( 1002) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /home/corals/old/vendor/rector/rector/src/NodeManipulator/ |
<?php declare (strict_types=1); namespace Rector\Core\NodeManipulator; use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassConst; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Property; use PHPStan\Type\Type; use Rector\Core\PhpParser\Node\NodeFactory; use Rector\NodeTypeResolver\Node\AttributeKey; final class ClassInsertManipulator { /** * @readonly * @var \Rector\Core\PhpParser\Node\NodeFactory */ private $nodeFactory; public function __construct(NodeFactory $nodeFactory) { $this->nodeFactory = $nodeFactory; } /** * @api * @param \PhpParser\Node\Stmt\Property|\PhpParser\Node\Stmt\ClassConst|\PhpParser\Node\Stmt\ClassMethod $stmt */ public function addAsFirstMethod(Class_ $class, $stmt) : void { $scope = $class->getAttribute(AttributeKey::SCOPE); $stmt->setAttribute(AttributeKey::SCOPE, $scope); if ($this->isSuccessToInsertBeforeFirstMethod($class, $stmt)) { return; } if ($this->isSuccessToInsertAfterLastProperty($class, $stmt)) { return; } $class->stmts[] = $stmt; } /** * @internal Use PropertyAdder service instead */ public function addPropertyToClass(Class_ $class, string $name, ?Type $type) : void { $existingProperty = $class->getProperty($name); if ($existingProperty instanceof Property) { return; } $property = $this->nodeFactory->createPrivatePropertyFromNameAndType($name, $type); $this->addAsFirstMethod($class, $property); } /** * @param Stmt[] $stmts * @return Stmt[] */ private function insertBefore(array $stmts, Stmt $stmt, int $key) : array { \array_splice($stmts, $key, 0, [$stmt]); return $stmts; } /** * @param \PhpParser\Node\Stmt\ClassConst|\PhpParser\Node\Stmt\ClassMethod|\PhpParser\Node\Stmt\Property $stmt */ private function isSuccessToInsertBeforeFirstMethod(Class_ $class, $stmt) : bool { foreach ($class->stmts as $key => $classStmt) { if (!$classStmt instanceof ClassMethod) { continue; } $class->stmts = $this->insertBefore($class->stmts, $stmt, $key); return \true; } return \false; } /** * @param \PhpParser\Node\Stmt\ClassConst|\PhpParser\Node\Stmt\ClassMethod|\PhpParser\Node\Stmt\Property $stmt */ private function isSuccessToInsertAfterLastProperty(Class_ $class, $stmt) : bool { $previousElement = null; foreach ($class->stmts as $key => $classStmt) { if ($previousElement instanceof Property && !$classStmt instanceof Property) { $class->stmts = $this->insertBefore($class->stmts, $stmt, $key); return \true; } $previousElement = $classStmt; } return \false; } }