|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace phpseclib\rectorRules\Rector\V3toV4; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Name; |
| 9 | +use PhpParser\Node\Name\FullyQualified; |
| 10 | +use PhpParser\Node\UseItem; |
| 11 | +use Rector\Rector\AbstractRector; |
| 12 | + |
| 13 | +/** |
| 14 | + * Renames the phpseclib3\ root namespace to phpseclib4\ everywhere — in use |
| 15 | + * statements and in fully-qualified names used inline. |
| 16 | + * |
| 17 | + * Short names (e.g. RSA in "use phpseclib3\Crypt\RSA; new RSA()") are left |
| 18 | + * alone: renaming the use statement is sufficient for them to resolve correctly. |
| 19 | + * |
| 20 | + * Classes deliberately skipped here (handled by dedicated rules): |
| 21 | + * - phpseclib3\File\X509 → split into X509 / CSR / CRL / SPKAC (X509 rule) |
| 22 | + * - phpseclib3\Crypt\Random → removed; replaced by random_bytes() (CryptRandom rule) |
| 23 | + */ |
| 24 | +final class Namespace_ extends AbstractRector |
| 25 | +{ |
| 26 | + private const SKIP = [ |
| 27 | + 'phpseclib3\File\X509', |
| 28 | + 'phpseclib3\Crypt\Random', |
| 29 | + ]; |
| 30 | + |
| 31 | + public function getNodeTypes(): array |
| 32 | + { |
| 33 | + return [UseItem::class, FullyQualified::class]; |
| 34 | + } |
| 35 | + |
| 36 | + public function refactor(Node $node): ?Node |
| 37 | + { |
| 38 | + if ($node instanceof UseItem) { |
| 39 | + $name = $node->name->toString(); |
| 40 | + if (!str_starts_with($name, 'phpseclib3\\')) { |
| 41 | + return null; |
| 42 | + } |
| 43 | + if (in_array($name, self::SKIP, true)) { |
| 44 | + return null; |
| 45 | + } |
| 46 | + $node->name = new Name('phpseclib4\\' . substr($name, strlen('phpseclib3\\'))); |
| 47 | + return $node; |
| 48 | + } |
| 49 | + |
| 50 | + // FullyQualified — only rename if written explicitly in source (not resolved from a short name). |
| 51 | + // Resolved short names occupy file-character span of the alias only (e.g. 4 chars for "SFTP"), |
| 52 | + // while explicit FQNs span the full string including the leading backslash. |
| 53 | + $name = $node->toString(); |
| 54 | + if (!str_starts_with($name, 'phpseclib3\\')) { |
| 55 | + return null; |
| 56 | + } |
| 57 | + if (in_array($name, self::SKIP, true)) { |
| 58 | + return null; |
| 59 | + } |
| 60 | + $expectedSpan = strlen('\\' . $name); |
| 61 | + $actualSpan = $node->getEndFilePos() - $node->getStartFilePos() + 1; |
| 62 | + if ($actualSpan !== $expectedSpan) { |
| 63 | + // Span doesn't match the full FQN — this was resolved from a short name via a use import. |
| 64 | + return null; |
| 65 | + } |
| 66 | + |
| 67 | + return new FullyQualified('phpseclib4\\' . substr($name, strlen('phpseclib3\\'))); |
| 68 | + } |
| 69 | +} |
0 commit comments