repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
erusev/parsedown
https://github.com/erusev/parsedown/blob/0b274ac959624e6c6d647e9c9b6c2d20da242004/test/ParsedownTest.php
test/ParsedownTest.php
<?php require 'SampleExtensions.php'; use PHPUnit\Framework\TestCase; class ParsedownTest extends TestCase { final function __construct($name = null, array $data = array(), $dataName = '') { $this->dirs = $this->initDirs(); $this->Parsedown = $this->initParsedown(); parent::__construct($name, $data, $dataName); } private $dirs; protected $Parsedown; /** * @return array */ protected function initDirs() { $dirs []= dirname(__FILE__).'/data/'; return $dirs; } /** * @return Parsedown */ protected function initParsedown() { $Parsedown = new TestParsedown(); return $Parsedown; } /** * @dataProvider data * @param $test * @param $dir */ function test_($test, $dir) { $markdown = file_get_contents($dir . $test . '.md'); $expectedMarkup = file_get_contents($dir . $test . '.html'); $expectedMarkup = str_replace("\r\n", "\n", $expectedMarkup); $expectedMarkup = str_replace("\r", "\n", $expectedMarkup); $this->Parsedown->setSafeMode(substr($test, 0, 3) === 'xss'); $this->Parsedown->setStrictMode(substr($test, 0, 6) === 'strict'); $actualMarkup = $this->Parsedown->text($markdown); $this->assertEquals($expectedMarkup, $actualMarkup); } function testRawHtml() { $markdown = "```php\nfoobar\n```"; $expectedMarkup = '<pre><code class="language-php"><p>foobar</p></code></pre>'; $expectedSafeMarkup = '<pre><code class="language-php">&lt;p&gt;foobar&lt;/p&gt;</code></pre>'; $unsafeExtension = new UnsafeExtension; $actualMarkup = $unsafeExtension->text($markdown); $this->assertEquals($expectedMarkup, $actualMarkup); $unsafeExtension->setSafeMode(true); $actualSafeMarkup = $unsafeExtension->text($markdown); $this->assertEquals($expectedSafeMarkup, $actualSafeMarkup); } function testTrustDelegatedRawHtml() { $markdown = "```php\nfoobar\n```"; $expectedMarkup = '<pre><code class="language-php"><p>foobar</p></code></pre>'; $expectedSafeMarkup = $expectedMarkup; $unsafeExtension = new TrustDelegatedExtension; $actualMarkup = $unsafeExtension->text($markdown); $this->assertEquals($expectedMarkup, $actualMarkup); $unsafeExtension->setSafeMode(true); $actualSafeMarkup = $unsafeExtension->text($markdown); $this->assertEquals($expectedSafeMarkup, $actualSafeMarkup); } function data() { $data = array(); foreach ($this->dirs as $dir) { $Folder = new DirectoryIterator($dir); foreach ($Folder as $File) { /** @var $File DirectoryIterator */ if ( ! $File->isFile()) { continue; } $filename = $File->getFilename(); $extension = pathinfo($filename, PATHINFO_EXTENSION); if ($extension !== 'md') { continue; } $basename = $File->getBasename('.md'); if (file_exists($dir . $basename . '.html')) { $data []= array($basename, $dir); } } } return $data; } public function test_no_markup() { $markdownWithHtml = <<<MARKDOWN_WITH_MARKUP <div>_content_</div> sparse: <div> <div class="inner"> _content_ </div> </div> paragraph <style type="text/css"> p { color: red; } </style> comment <!-- html comment --> MARKDOWN_WITH_MARKUP; $expectedHtml = <<<EXPECTED_HTML <p>&lt;div&gt;<em>content</em>&lt;/div&gt;</p> <p>sparse:</p> <p>&lt;div&gt; &lt;div class="inner"&gt; <em>content</em> &lt;/div&gt; &lt;/div&gt;</p> <p>paragraph</p> <p>&lt;style type="text/css"&gt; p { color: red; } &lt;/style&gt;</p> <p>comment</p> <p>&lt;!-- html comment --&gt;</p> EXPECTED_HTML; $parsedownWithNoMarkup = new TestParsedown(); $parsedownWithNoMarkup->setMarkupEscaped(true); $this->assertEquals($expectedHtml, $parsedownWithNoMarkup->text($markdownWithHtml)); } public function testLateStaticBinding() { $parsedown = Parsedown::instance(); $this->assertInstanceOf('Parsedown', $parsedown); // After instance is already called on Parsedown // subsequent calls with the same arguments return the same instance $sameParsedown = TestParsedown::instance(); $this->assertInstanceOf('Parsedown', $sameParsedown); $this->assertSame($parsedown, $sameParsedown); $testParsedown = TestParsedown::instance('test late static binding'); $this->assertInstanceOf('TestParsedown', $testParsedown); $sameInstanceAgain = TestParsedown::instance('test late static binding'); $this->assertSame($testParsedown, $sameInstanceAgain); } }
php
MIT
0b274ac959624e6c6d647e9c9b6c2d20da242004
2026-01-04T15:02:39.892991Z
false
erusev/parsedown
https://github.com/erusev/parsedown/blob/0b274ac959624e6c6d647e9c9b6c2d20da242004/test/SampleExtensions.php
test/SampleExtensions.php
<?php class UnsafeExtension extends Parsedown { protected function blockFencedCodeComplete($Block) { $text = $Block['element']['element']['text']; unset($Block['element']['element']['text']); // WARNING: There is almost always a better way of doing things! // // This example is one of them, unsafe behaviour is NOT needed here. // Only use this if you trust the input and have no idea what // the output HTML will look like (e.g. using an external parser). $Block['element']['element']['rawHtml'] = "<p>$text</p>"; return $Block; } } class TrustDelegatedExtension extends Parsedown { protected function blockFencedCodeComplete($Block) { $text = $Block['element']['element']['text']; unset($Block['element']['element']['text']); // WARNING: There is almost always a better way of doing things! // // This behaviour is NOT needed in the demonstrated case. // Only use this if you are sure that the result being added into // rawHtml is safe. // (e.g. using an external parser with escaping capabilities). $Block['element']['element']['rawHtml'] = "<p>$text</p>"; $Block['element']['element']['allowRawHtmlInSafeMode'] = true; return $Block; } }
php
MIT
0b274ac959624e6c6d647e9c9b6c2d20da242004
2026-01-04T15:02:39.892991Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/.php-cs-fixer.dist.php
.php-cs-fixer.dist.php
<?php $finder = PhpCsFixer\Finder::create() ->exclude('PhpParser/Parser') ->in(__DIR__ . '/lib') ->in(__DIR__ . '/test') ->in(__DIR__ . '/grammar') ; $config = new PhpCsFixer\Config(); return $config->setRiskyAllowed(true) ->setRules([ '@PSR12' => true, // We use PSR12 with consistent brace placement. 'curly_braces_position' => [ 'functions_opening_brace' => 'same_line', 'classes_opening_brace' => 'same_line', ], // declare(strict_types=1) on the same line as <?php. 'blank_line_after_opening_tag' => false, 'declare_strict_types' => true, // Keep argument formatting for now. 'method_argument_space' => ['on_multiline' => 'ignore'], 'phpdoc_align' => ['align' => 'left'], 'phpdoc_trim' => true, 'no_empty_phpdoc' => true, 'no_superfluous_phpdoc_tags' => ['allow_mixed' => true], 'no_extra_blank_lines' => true, ]) ->setFinder($finder) ;
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/tools/fuzzing/generateCorpus.php
tools/fuzzing/generateCorpus.php
<?php declare(strict_types=1); $testDir = __DIR__ . '/../../test'; require $testDir . '/bootstrap.php'; require $testDir . '/PhpParser/CodeTestParser.php'; require $testDir . '/PhpParser/CodeParsingTest.php'; $inputDirs = [$testDir . '/code/parser', $testDir . '/code/prettyPrinter']; if ($argc < 2) { echo "Usage: php generateCorpus.php dir/\n"; exit(1); } $corpusDir = $argv[1]; if (!is_dir($corpusDir)) { mkdir($corpusDir, 0777, true); } $testParser = new PhpParser\CodeTestParser(); $codeParsingTest = new PhpParser\CodeParsingTest(); foreach ($inputDirs as $inputDir) { foreach (PhpParser\filesInDir($inputDir, 'test') as $fileName => $code) { list($_name, $tests) = $testParser->parseTest($code, 2); foreach ($tests as list($_modeLine, list($input, $_expected))) { $path = $corpusDir . '/' . md5($input) . '.txt'; file_put_contents($path, $input); } } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/tools/fuzzing/target.php
tools/fuzzing/target.php
<?php declare(strict_types=1); /** @var PhpFuzzer\Fuzzer $fuzzer */ use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Scalar; use PhpParser\Node\Stmt; use PhpParser\NodeVisitor; if (class_exists(PhpParser\Parser\Php7::class)) { echo "The PHP-Parser target can only be used with php-fuzzer.phar,\n"; echo "otherwise there is a conflict with php-fuzzer's own use of PHP-Parser.\n"; exit(1); } $autoload = __DIR__ . '/../../vendor/autoload.php'; if (!file_exists($autoload)) { echo "Cannot find PHP-Parser installation in " . __DIR__ . "/PHP-Parser\n"; exit(1); } require $autoload; $lexer = new PhpParser\Lexer(); $parser = new PhpParser\Parser\Php7($lexer); $prettyPrinter = new PhpParser\PrettyPrinter\Standard(); $nodeDumper = new PhpParser\NodeDumper(); $visitor = new class extends PhpParser\NodeVisitorAbstract { private const CAST_NAMES = [ 'int', 'integer', 'double', 'float', 'real', 'string', 'binary', 'array', 'object', 'bool', 'boolean', 'unset', ]; private $tokens; public $hasProblematicConstruct; public function setTokens(array $tokens): void { $this->tokens = $tokens; } public function beforeTraverse(array $nodes): void { $this->hasProblematicConstruct = false; } public function leaveNode(PhpParser\Node $node) { // We don't precisely preserve nop statements. if ($node instanceof Stmt\Nop) { return NodeVisitor::REMOVE_NODE; } // We don't precisely preserve redundant trailing commas in array destructuring. if ($node instanceof Expr\List_) { while (!empty($node->items) && $node->items[count($node->items) - 1] === null) { array_pop($node->items); } } // For T_NUM_STRING the parser produced negative integer literals. Convert these into // a unary minus followed by a positive integer. if ($node instanceof Scalar\Int_ && $node->value < 0) { if ($node->value === \PHP_INT_MIN) { // PHP_INT_MIN == -PHP_INT_MAX - 1 return new Expr\BinaryOp\Minus( new Expr\UnaryMinus(new Scalar\Int_(\PHP_INT_MAX)), new Scalar\Int_(1)); } return new Expr\UnaryMinus(new Scalar\Int_(-$node->value)); } // If a constant with the same name as a cast operand occurs inside parentheses, it will // be parsed back as a cast. E.g. "foo(int)" will fail to parse, because the argument is // interpreted as a cast. We can run into this with inputs like "foo(int\n)", where the // newline is not preserved. if ($node instanceof Expr\ConstFetch && $node->name->isUnqualified() && in_array($node->name->toLowerString(), self::CAST_NAMES) ) { $this->hasProblematicConstruct = true; } // The parser does not distinguish between use X and use \X, as they are semantically // equivalent. However, use \keyword is legal PHP, while use keyword is not, so we inspect // tokens to detect this situation here. if ($node instanceof Stmt\Use_ && $node->uses[0]->name->isUnqualified() && $this->tokens[$node->uses[0]->name->getStartTokenPos()]->is(\T_NAME_FULLY_QUALIFIED) ) { $this->hasProblematicConstruct = true; } if ($node instanceof Stmt\GroupUse && $node->prefix->isUnqualified() && $this->tokens[$node->prefix->getStartTokenPos()]->is(\T_NAME_FULLY_QUALIFIED) ) { $this->hasProblematicConstruct = true; } // clone($x, ) is not preserved precisely. if ($node instanceof Expr\FuncCall && $node->name instanceof Node\Name && $node->name->toLowerString() == 'clone' && count($node->args) == 1 ) { $this->hasProblematicConstruct = true; } } }; $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor($visitor); $fuzzer->setTarget(function(string $input) use($lexer, $parser, $prettyPrinter, $nodeDumper, $visitor, $traverser) { $stmts = $parser->parse($input); $printed = $prettyPrinter->prettyPrintFile($stmts); $visitor->setTokens($parser->getTokens()); $stmts = $traverser->traverse($stmts); if ($visitor->hasProblematicConstruct) { return; } try { $printedStmts = $parser->parse($printed); } catch (PhpParser\Error $e) { throw new Error("Failed to parse pretty printer output"); } $visitor->setTokens($parser->getTokens()); $printedStmts = $traverser->traverse($printedStmts); $same = $nodeDumper->dump($stmts) == $nodeDumper->dump($printedStmts); if (!$same && !preg_match('/<\?php<\?php/i', $input)) { throw new Error("Result after pretty printing differs"); } }); $fuzzer->setMaxLen(1024); $fuzzer->addDictionary(__DIR__ . '/php.dict'); $fuzzer->setAllowedExceptions([PhpParser\Error::class]);
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/grammar/rebuildParsers.php
grammar/rebuildParsers.php
<?php declare(strict_types=1); require __DIR__ . '/phpyLang.php'; $parserToDefines = [ 'Php7' => ['PHP7' => true], 'Php8' => ['PHP8' => true], ]; $grammarFile = __DIR__ . '/php.y'; $skeletonFile = __DIR__ . '/parser.template'; $tmpGrammarFile = __DIR__ . '/tmp_parser.phpy'; $tmpResultFile = __DIR__ . '/tmp_parser.php'; $resultDir = __DIR__ . '/../lib/PhpParser/Parser'; $kmyacc = getenv('KMYACC'); if (!$kmyacc) { // Use phpyacc from dev dependencies by default. $kmyacc = __DIR__ . '/../vendor/bin/phpyacc'; } $options = array_flip($argv); $optionDebug = isset($options['--debug']); $optionKeepTmpGrammar = isset($options['--keep-tmp-grammar']); /////////////////// /// Main script /// /////////////////// foreach ($parserToDefines as $name => $defines) { echo "Building temporary $name grammar file.\n"; $grammarCode = file_get_contents($grammarFile); $grammarCode = replaceIfBlocks($grammarCode, $defines); $grammarCode = preprocessGrammar($grammarCode); file_put_contents($tmpGrammarFile, $grammarCode); $additionalArgs = $optionDebug ? '-t -v' : ''; echo "Building $name parser.\n"; $output = execCmd("$kmyacc $additionalArgs -m $skeletonFile -p $name $tmpGrammarFile"); $resultCode = file_get_contents($tmpResultFile); $resultCode = removeTrailingWhitespace($resultCode); ensureDirExists($resultDir); file_put_contents("$resultDir/$name.php", $resultCode); unlink($tmpResultFile); if (!$optionKeepTmpGrammar) { unlink($tmpGrammarFile); } } //////////////////////////////// /// Utility helper functions /// //////////////////////////////// function ensureDirExists($dir) { if (!is_dir($dir)) { mkdir($dir, 0777, true); } } function execCmd($cmd) { $output = trim(shell_exec("$cmd 2>&1") ?? ''); if ($output !== "") { echo "> " . $cmd . "\n"; echo $output; } return $output; } function replaceIfBlocks(string $code, array $defines): string { return preg_replace_callback('/\n#if\s+(\w+)\n(.*?)\n#endif/s', function ($matches) use ($defines) { $value = $defines[$matches[1]] ?? false; return $value ? $matches[2] : ''; }, $code); }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/grammar/phpyLang.php
grammar/phpyLang.php
<?php declare(strict_types=1); /////////////////////////////// /// Utility regex constants /// /////////////////////////////// const LIB = '(?(DEFINE) (?<singleQuotedString>\'[^\\\\\']*+(?:\\\\.[^\\\\\']*+)*+\') (?<doubleQuotedString>"[^\\\\"]*+(?:\\\\.[^\\\\"]*+)*+") (?<string>(?&singleQuotedString)|(?&doubleQuotedString)) (?<comment>/\*[^*]*+(?:\*(?!/)[^*]*+)*+\*/) (?<code>\{[^\'"/{}]*+(?:(?:(?&string)|(?&comment)|(?&code)|/)[^\'"/{}]*+)*+}) )'; const PARAMS = '\[(?<params>[^[\]]*+(?:\[(?&params)\][^[\]]*+)*+)\]'; const ARGS = '\((?<args>[^()]*+(?:\((?&args)\)[^()]*+)*+)\)'; /////////////////////////////// /// Preprocessing functions /// /////////////////////////////// function preprocessGrammar($code) { $code = resolveNodes($code); $code = resolveMacros($code); $code = resolveStackAccess($code); $code = str_replace('$this', '$self', $code); return $code; } function resolveNodes($code) { return preg_replace_callback( '~\b(?<name>[A-Z][a-zA-Z_\\\\]++)\s*' . PARAMS . '~', function ($matches) { // recurse $matches['params'] = resolveNodes($matches['params']); $params = magicSplit( '(?:' . PARAMS . '|' . ARGS . ')(*SKIP)(*FAIL)|,', $matches['params'] ); $paramCode = ''; foreach ($params as $param) { $paramCode .= $param . ', '; } return 'new ' . $matches['name'] . '(' . $paramCode . 'attributes())'; }, $code ); } function resolveMacros($code) { return preg_replace_callback( '~\b(?<!::|->)(?!array\()(?<name>[a-z][A-Za-z]++)' . ARGS . '~', function ($matches) { // recurse $matches['args'] = resolveMacros($matches['args']); $name = $matches['name']; $args = magicSplit( '(?:' . PARAMS . '|' . ARGS . ')(*SKIP)(*FAIL)|,', $matches['args'] ); if ('attributes' === $name) { assertArgs(0, $args, $name); return '$this->getAttributes($this->tokenStartStack[#1], $this->tokenEndStack[$stackPos])'; } if ('stackAttributes' === $name) { assertArgs(1, $args, $name); return '$this->getAttributes($this->tokenStartStack[' . $args[0] . '], ' . ' $this->tokenEndStack[' . $args[0] . '])'; } if ('init' === $name) { return '$$ = array(' . implode(', ', $args) . ')'; } if ('push' === $name) { assertArgs(2, $args, $name); return $args[0] . '[] = ' . $args[1] . '; $$ = ' . $args[0]; } if ('pushNormalizing' === $name) { assertArgs(2, $args, $name); return 'if (' . $args[1] . ' !== null) { ' . $args[0] . '[] = ' . $args[1] . '; } $$ = ' . $args[0] . ';'; } if ('toBlock' == $name) { assertArgs(1, $args, $name); return 'if (' . $args[0] . ' instanceof Stmt\Block) { $$ = ' . $args[0] . '->stmts; } ' . 'else if (' . $args[0] . ' === null) { $$ = []; } ' . 'else { $$ = [' . $args[0] . ']; }'; } if ('parseVar' === $name) { assertArgs(1, $args, $name); return 'substr(' . $args[0] . ', 1)'; } if ('parseEncapsed' === $name) { assertArgs(3, $args, $name); return 'foreach (' . $args[0] . ' as $s) { if ($s instanceof Node\InterpolatedStringPart) {' . ' $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, ' . $args[1] . ', ' . $args[2] . '); } }'; } if ('makeNop' === $name) { assertArgs(1, $args, $name); return $args[0] . ' = $this->maybeCreateNop($this->tokenStartStack[#1], $this->tokenEndStack[$stackPos])'; } if ('makeZeroLengthNop' == $name) { assertArgs(1, $args, $name); return $args[0] . ' = $this->maybeCreateZeroLengthNop($this->tokenPos);'; } return $matches[0]; }, $code ); } function assertArgs($num, $args, $name) { if ($num != count($args)) { die('Wrong argument count for ' . $name . '().'); } } function resolveStackAccess($code) { $code = preg_replace('/\$\d+/', '$this->semStack[$0]', $code); $code = preg_replace('/#(\d+)/', '$$1', $code); return $code; } function removeTrailingWhitespace($code) { $lines = explode("\n", $code); $lines = array_map('rtrim', $lines); return implode("\n", $lines); } ////////////////////////////// /// Regex helper functions /// ////////////////////////////// function regex($regex) { return '~' . LIB . '(?:' . str_replace('~', '\~', $regex) . ')~'; } function magicSplit($regex, $string) { $pieces = preg_split(regex('(?:(?&string)|(?&comment)|(?&code))(*SKIP)(*FAIL)|' . $regex), $string); foreach ($pieces as &$piece) { $piece = trim($piece); } if ($pieces === ['']) { return []; } return $pieces; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/updateTests.php
test/updateTests.php
<?php declare(strict_types=1); namespace PhpParser; require __DIR__ . '/bootstrap.php'; require __DIR__ . '/PhpParser/CodeTestParser.php'; require __DIR__ . '/PhpParser/CodeParsingTest.php'; $dir = __DIR__ . '/code/parser'; $testParser = new CodeTestParser(); $codeParsingTest = new CodeParsingTest(); foreach (filesInDir($dir, 'test') as $fileName => $code) { if (false !== strpos($code, '@@{')) { // Skip tests with evaluate segments continue; } list($name, $tests) = $testParser->parseTest($code, 2); $newTests = []; foreach ($tests as list($modeLine, list($input, $expected))) { $modes = $codeParsingTest->parseModeLine($modeLine); $parser = $codeParsingTest->createParser($modes['version'] ?? null); list(, $output) = $codeParsingTest->getParseOutput($parser, $input, $modes); $newTests[] = [$modeLine, [$input, $output]]; } $newCode = $testParser->reconstructTest($name, $newTests); file_put_contents($fileName, $newCode); }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/bootstrap.php
test/bootstrap.php
<?php declare(strict_types=1); namespace PhpParser; require __DIR__ . '/../vendor/autoload.php'; function canonicalize($str) { // normalize EOL style $str = str_replace("\r\n", "\n", $str); // trim newlines at end $str = rtrim($str, "\n"); // remove trailing whitespace on all lines $lines = explode("\n", $str); $lines = array_map(function ($line) { return rtrim($line, " \t"); }, $lines); return implode("\n", $lines); } function filesInDir($directory, $fileExtension) { $directory = realpath($directory); $it = new \RecursiveDirectoryIterator($directory); $it = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::LEAVES_ONLY); $it = new \RegexIterator($it, '(\.' . preg_quote($fileExtension) . '$)'); foreach ($it as $file) { $fileName = $file->getPathname(); yield $fileName => file_get_contents($fileName); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/fixtures/Suit.php
test/fixtures/Suit.php
<?php declare(strict_types=1); enum Suit { case Hearts; case Diamonds; case Clubs; case Spades; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/CompatibilityTest.php
test/PhpParser/CompatibilityTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; use PhpParser\Node\InterpolatedStringPart; use PhpParser\Node\Name; use PhpParser\Node\Scalar; use PhpParser\Node\Stmt; class CompatibilityTest extends \PHPUnit\Framework\TestCase { /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testAliases1(): void { $var = new Expr\Variable('x'); $node = new Node\ClosureUse($var); $this->assertTrue($node instanceof Expr\ClosureUse); $node = new Node\ArrayItem($var); $this->assertTrue($node instanceof Expr\ArrayItem); $node = new Node\StaticVar($var); $this->assertTrue($node instanceof Stmt\StaticVar); $node = new Scalar\Float_(1.0); $this->assertTrue($node instanceof Scalar\DNumber); $node = new Scalar\Int_(1); $this->assertTrue($node instanceof Scalar\LNumber); $part = new InterpolatedStringPart('foo'); $this->assertTrue($part instanceof Scalar\EncapsedStringPart); $node = new Scalar\InterpolatedString([$part]); $this->assertTrue($node instanceof Scalar\Encapsed); $node = new Node\DeclareItem('strict_types', new Scalar\Int_(1)); $this->assertTrue($node instanceof Stmt\DeclareDeclare); $node = new Node\PropertyItem('x'); $this->assertTrue($node instanceof Stmt\PropertyProperty); $node = new Node\UseItem(new Name('X')); $this->assertTrue($node instanceof Stmt\UseUse); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testAliases2(): void { $var = new Expr\Variable('x'); $node = new Node\Expr\ClosureUse($var); $this->assertTrue($node instanceof Node\ClosureUse); $node = new Node\Expr\ArrayItem($var); $this->assertTrue($node instanceof Node\ArrayItem); $node = new Node\Stmt\StaticVar($var); $this->assertTrue($node instanceof Node\StaticVar); $node = new Node\Scalar\DNumber(1.0); $this->assertTrue($node instanceof Scalar\Float_); $node = new Node\Scalar\LNumber(1); $this->assertTrue($node instanceof Scalar\Int_); $part = new Node\Scalar\EncapsedStringPart('foo'); $this->assertTrue($part instanceof Node\InterpolatedStringPart); $node = new Scalar\Encapsed([$part]); $this->assertTrue($node instanceof Scalar\InterpolatedString); $node = new Stmt\DeclareDeclare('strict_types', new Scalar\LNumber(1)); $this->assertTrue($node instanceof Node\DeclareItem); $node = new Stmt\PropertyProperty('x'); $this->assertTrue($node instanceof Node\PropertyItem); $node = new Stmt\UseUse(new Name('X')); $this->assertTrue($node instanceof Node\UseItem); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/ErrorTest.php
test/PhpParser/ErrorTest.php
<?php declare(strict_types=1); namespace PhpParser; class ErrorTest extends \PHPUnit\Framework\TestCase { public function testConstruct() { $attributes = [ 'startLine' => 10, 'endLine' => 11, ]; $error = new Error('Some error', $attributes); $this->assertSame('Some error', $error->getRawMessage()); $this->assertSame($attributes, $error->getAttributes()); $this->assertSame(10, $error->getStartLine()); $this->assertSame(11, $error->getEndLine()); $this->assertSame('Some error on line 10', $error->getMessage()); return $error; } /** * @depends testConstruct */ public function testSetMessageAndLine(Error $error): void { $error->setRawMessage('Some other error'); $this->assertSame('Some other error', $error->getRawMessage()); $error->setStartLine(15); $this->assertSame(15, $error->getStartLine()); $this->assertSame('Some other error on line 15', $error->getMessage()); } public function testUnknownLine(): void { $error = new Error('Some error'); $this->assertSame(-1, $error->getStartLine()); $this->assertSame(-1, $error->getEndLine()); $this->assertSame('Some error on unknown line', $error->getMessage()); } /** @dataProvider provideTestColumnInfo */ public function testColumnInfo($code, $startPos, $endPos, $startColumn, $endColumn): void { $error = new Error('Some error', [ 'startFilePos' => $startPos, 'endFilePos' => $endPos, ]); $this->assertTrue($error->hasColumnInfo()); $this->assertSame($startColumn, $error->getStartColumn($code)); $this->assertSame($endColumn, $error->getEndColumn($code)); } public static function provideTestColumnInfo() { return [ // Error at "bar" ["<?php foo bar baz", 10, 12, 11, 13], ["<?php\nfoo bar baz", 10, 12, 5, 7], ["<?php foo\nbar baz", 10, 12, 1, 3], ["<?php foo bar\nbaz", 10, 12, 11, 13], ["<?php\r\nfoo bar baz", 11, 13, 5, 7], // Error at "baz" ["<?php foo bar baz", 14, 16, 15, 17], ["<?php foo bar\nbaz", 14, 16, 1, 3], // Error at string literal ["<?php foo 'bar\nbaz' xyz", 10, 18, 11, 4], ["<?php\nfoo 'bar\nbaz' xyz", 10, 18, 5, 4], ["<?php foo\n'\nbarbaz\n'\nxyz", 10, 19, 1, 1], // Error over full string ["<?php", 0, 4, 1, 5], ["<?\nphp", 0, 5, 1, 3], ]; } public function testNoColumnInfo(): void { $error = new Error('Some error', ['startLine' => 3]); $this->assertFalse($error->hasColumnInfo()); try { $error->getStartColumn(''); $this->fail('Expected RuntimeException'); } catch (\RuntimeException $e) { $this->assertSame('Error does not have column information', $e->getMessage()); } try { $error->getEndColumn(''); $this->fail('Expected RuntimeException'); } catch (\RuntimeException $e) { $this->assertSame('Error does not have column information', $e->getMessage()); } } public function testInvalidPosInfo(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Invalid position information'); $error = new Error('Some error', [ 'startFilePos' => 10, 'endFilePos' => 11, ]); $error->getStartColumn('code'); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeAbstractTest.php
test/PhpParser/NodeAbstractTest.php
<?php declare(strict_types=1); namespace PhpParser; class DummyNode extends NodeAbstract { public $subNode1; public $subNode2; public $notSubNode; public function __construct($subNode1, $subNode2, $notSubNode, $attributes) { parent::__construct($attributes); $this->subNode1 = $subNode1; $this->subNode2 = $subNode2; $this->notSubNode = $notSubNode; } public function getSubNodeNames(): array { return ['subNode1', 'subNode2']; } // This method is only overwritten because the node is located in an unusual namespace public function getType(): string { return 'Dummy'; } } class NodeAbstractTest extends \PHPUnit\Framework\TestCase { public static function provideNodes() { $attributes = [ 'startLine' => 10, 'endLine' => 11, 'startTokenPos' => 12, 'endTokenPos' => 13, 'startFilePos' => 14, 'endFilePos' => 15, 'comments' => [ new Comment('// Comment 1' . "\n"), new Comment\Doc('/** doc comment */'), new Comment('// Comment 2' . "\n"), ], ]; $node = new DummyNode('value1', 'value2', 'value3', $attributes); return [ [$attributes, $node], ]; } /** * @dataProvider provideNodes */ public function testConstruct(array $attributes, Node $node) { $this->assertSame('Dummy', $node->getType()); $this->assertSame(['subNode1', 'subNode2'], $node->getSubNodeNames()); $this->assertSame(10, $node->getLine()); $this->assertSame(10, $node->getStartLine()); $this->assertSame(11, $node->getEndLine()); $this->assertSame(12, $node->getStartTokenPos()); $this->assertSame(13, $node->getEndTokenPos()); $this->assertSame(14, $node->getStartFilePos()); $this->assertSame(15, $node->getEndFilePos()); $this->assertSame('/** doc comment */', $node->getDocComment()->getText()); $this->assertSame('value1', $node->subNode1); $this->assertSame('value2', $node->subNode2); $this->assertTrue(isset($node->subNode1)); $this->assertTrue(isset($node->subNode2)); $this->assertTrue(!isset($node->subNode3)); $this->assertSame($attributes, $node->getAttributes()); $this->assertSame($attributes['comments'], $node->getComments()); return $node; } /** * @dataProvider provideNodes */ public function testGetDocComment(array $attributes, Node $node): void { $this->assertSame('/** doc comment */', $node->getDocComment()->getText()); $comments = $node->getComments(); array_splice($comments, 1, 1, []); // remove doc comment $node->setAttribute('comments', $comments); $this->assertNull($node->getDocComment()); // Remove all comments. $node->setAttribute('comments', []); $this->assertNull($node->getDocComment()); } public function testSetDocComment(): void { $node = new DummyNode(null, null, null, []); // Add doc comment to node without comments $docComment = new Comment\Doc('/** doc */'); $node->setDocComment($docComment); $this->assertSame($docComment, $node->getDocComment()); // Replace it $docComment = new Comment\Doc('/** doc 2 */'); $node->setDocComment($docComment); $this->assertSame($docComment, $node->getDocComment()); // Add docmment to node with other comments $c1 = new Comment('/* foo */'); $c2 = new Comment('/* bar */'); $docComment = new Comment\Doc('/** baz */'); $node->setAttribute('comments', [$c1, $c2]); $node->setDocComment($docComment); $this->assertSame([$c1, $c2, $docComment], $node->getAttribute('comments')); // Replace doc comment that is not at the end. $newDocComment = new Comment\Doc('/** new baz */'); $node->setAttribute('comments', [$c1, $docComment, $c2]); $node->setDocComment($newDocComment); $this->assertSame([$c1, $newDocComment, $c2], $node->getAttribute('comments')); } /** * @dataProvider provideNodes */ public function testChange(array $attributes, DummyNode $node): void { // direct modification $node->subNode1 = 'newValue'; $this->assertSame('newValue', $node->subNode1); // indirect modification $subNode = &$node->subNode1; $subNode = 'newNewValue'; $this->assertSame('newNewValue', $node->subNode1); // removal unset($node->subNode1); $this->assertFalse(isset($node->subNode1)); } /** * @dataProvider provideNodes */ public function testIteration(array $attributes, Node $node): void { // Iteration is simple object iteration over properties, // not over subnodes $i = 0; foreach ($node as $key => $value) { if ($i === 0) { $this->assertSame('subNode1', $key); $this->assertSame('value1', $value); } elseif ($i === 1) { $this->assertSame('subNode2', $key); $this->assertSame('value2', $value); } elseif ($i === 2) { $this->assertSame('notSubNode', $key); $this->assertSame('value3', $value); } else { throw new \Exception(); } $i++; } $this->assertSame(3, $i); } public function testAttributes(): void { /** @var $node Node */ $node = $this->getMockForAbstractClass(NodeAbstract::class); $this->assertEmpty($node->getAttributes()); $node->setAttribute('key', 'value'); $this->assertTrue($node->hasAttribute('key')); $this->assertSame('value', $node->getAttribute('key')); $this->assertFalse($node->hasAttribute('doesNotExist')); $this->assertNull($node->getAttribute('doesNotExist')); $this->assertSame('default', $node->getAttribute('doesNotExist', 'default')); $node->setAttribute('null', null); $this->assertTrue($node->hasAttribute('null')); $this->assertNull($node->getAttribute('null')); $this->assertNull($node->getAttribute('null', 'default')); $this->assertSame( [ 'key' => 'value', 'null' => null, ], $node->getAttributes() ); $node->setAttributes( [ 'a' => 'b', 'c' => null, ] ); $this->assertSame( [ 'a' => 'b', 'c' => null, ], $node->getAttributes() ); } public function testJsonSerialization(): void { $code = <<<'PHP' <?php // comment /** doc comment */ function functionName(&$a = 0, $b = 1.0) { echo 'Foo'; } PHP; $expected = <<<'JSON' [ { "nodeType": "Stmt_Function", "byRef": false, "name": { "nodeType": "Identifier", "name": "functionName", "attributes": { "startLine": 4, "startTokenPos": 7, "startFilePos": 45, "endLine": 4, "endTokenPos": 7, "endFilePos": 56 } }, "params": [ { "nodeType": "Param", "type": null, "byRef": true, "variadic": false, "var": { "nodeType": "Expr_Variable", "name": "a", "attributes": { "startLine": 4, "startTokenPos": 10, "startFilePos": 59, "endLine": 4, "endTokenPos": 10, "endFilePos": 60 } }, "default": { "nodeType": "Scalar_Int", "value": 0, "attributes": { "startLine": 4, "startTokenPos": 14, "startFilePos": 64, "endLine": 4, "endTokenPos": 14, "endFilePos": 64, "rawValue": "0", "kind": 10 } }, "flags": 0, "attrGroups": [], "hooks": [], "attributes": { "startLine": 4, "startTokenPos": 9, "startFilePos": 58, "endLine": 4, "endTokenPos": 14, "endFilePos": 64 } }, { "nodeType": "Param", "type": null, "byRef": false, "variadic": false, "var": { "nodeType": "Expr_Variable", "name": "b", "attributes": { "startLine": 4, "startTokenPos": 17, "startFilePos": 67, "endLine": 4, "endTokenPos": 17, "endFilePos": 68 } }, "default": { "nodeType": "Scalar_Float", "value": 1, "attributes": { "startLine": 4, "startTokenPos": 21, "startFilePos": 72, "endLine": 4, "endTokenPos": 21, "endFilePos": 74, "rawValue": "1.0" } }, "flags": 0, "attrGroups": [], "hooks": [], "attributes": { "startLine": 4, "startTokenPos": 17, "startFilePos": 67, "endLine": 4, "endTokenPos": 21, "endFilePos": 74 } } ], "returnType": null, "stmts": [ { "nodeType": "Stmt_Echo", "exprs": [ { "nodeType": "Scalar_String", "value": "Foo", "attributes": { "startLine": 5, "startTokenPos": 28, "startFilePos": 88, "endLine": 5, "endTokenPos": 28, "endFilePos": 92, "kind": 1, "rawValue": "'Foo'" } } ], "attributes": { "startLine": 5, "startTokenPos": 26, "startFilePos": 83, "endLine": 5, "endTokenPos": 29, "endFilePos": 93 } } ], "attrGroups": [], "attributes": { "startLine": 4, "startTokenPos": 5, "startFilePos": 36, "endLine": 6, "endTokenPos": 31, "endFilePos": 95, "comments": [ { "nodeType": "Comment", "text": "\/\/ comment", "line": 2, "filePos": 6, "tokenPos": 1, "endLine": 2, "endFilePos": 15, "endTokenPos": 1 }, { "nodeType": "Comment_Doc", "text": "\/** doc comment *\/", "line": 3, "filePos": 17, "tokenPos": 3, "endLine": 3, "endFilePos": 34, "endTokenPos": 3 } ] } } ] JSON; $expected81 = <<<'JSON' [ { "nodeType": "Stmt_Function", "attributes": { "startLine": 4, "startTokenPos": 5, "startFilePos": 36, "endLine": 6, "endTokenPos": 31, "endFilePos": 95, "comments": [ { "nodeType": "Comment", "text": "\/\/ comment", "line": 2, "filePos": 6, "tokenPos": 1, "endLine": 2, "endFilePos": 15, "endTokenPos": 1 }, { "nodeType": "Comment_Doc", "text": "\/** doc comment *\/", "line": 3, "filePos": 17, "tokenPos": 3, "endLine": 3, "endFilePos": 34, "endTokenPos": 3 } ] }, "byRef": false, "name": { "nodeType": "Identifier", "attributes": { "startLine": 4, "startTokenPos": 7, "startFilePos": 45, "endLine": 4, "endTokenPos": 7, "endFilePos": 56 }, "name": "functionName" }, "params": [ { "nodeType": "Param", "attributes": { "startLine": 4, "startTokenPos": 9, "startFilePos": 58, "endLine": 4, "endTokenPos": 14, "endFilePos": 64 }, "type": null, "byRef": true, "variadic": false, "var": { "nodeType": "Expr_Variable", "attributes": { "startLine": 4, "startTokenPos": 10, "startFilePos": 59, "endLine": 4, "endTokenPos": 10, "endFilePos": 60 }, "name": "a" }, "default": { "nodeType": "Scalar_Int", "attributes": { "startLine": 4, "startTokenPos": 14, "startFilePos": 64, "endLine": 4, "endTokenPos": 14, "endFilePos": 64, "rawValue": "0", "kind": 10 }, "value": 0 }, "flags": 0, "attrGroups": [], "hooks": [] }, { "nodeType": "Param", "attributes": { "startLine": 4, "startTokenPos": 17, "startFilePos": 67, "endLine": 4, "endTokenPos": 21, "endFilePos": 74 }, "type": null, "byRef": false, "variadic": false, "var": { "nodeType": "Expr_Variable", "attributes": { "startLine": 4, "startTokenPos": 17, "startFilePos": 67, "endLine": 4, "endTokenPos": 17, "endFilePos": 68 }, "name": "b" }, "default": { "nodeType": "Scalar_Float", "attributes": { "startLine": 4, "startTokenPos": 21, "startFilePos": 72, "endLine": 4, "endTokenPos": 21, "endFilePos": 74, "rawValue": "1.0" }, "value": 1 }, "flags": 0, "attrGroups": [], "hooks": [] } ], "returnType": null, "stmts": [ { "nodeType": "Stmt_Echo", "attributes": { "startLine": 5, "startTokenPos": 26, "startFilePos": 83, "endLine": 5, "endTokenPos": 29, "endFilePos": 93 }, "exprs": [ { "nodeType": "Scalar_String", "attributes": { "startLine": 5, "startTokenPos": 28, "startFilePos": 88, "endLine": 5, "endTokenPos": 28, "endFilePos": 92, "kind": 1, "rawValue": "'Foo'" }, "value": "Foo" } ] } ], "attrGroups": [] } ] JSON; if (version_compare(PHP_VERSION, '8.1', '>=')) { $expected = $expected81; } $parser = new Parser\Php7(new Lexer()); $stmts = $parser->parse(canonicalize($code)); $json = json_encode($stmts, JSON_PRETTY_PRINT); $this->assertEquals(canonicalize($expected), canonicalize($json)); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/BuilderFactoryTest.php
test/PhpParser/BuilderFactoryTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\Expr; use PhpParser\Node\Expr\BinaryOp\Concat; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Scalar\String_; class BuilderFactoryTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideTestFactory */ public function testFactory($methodName, $className): void { $factory = new BuilderFactory(); $this->assertInstanceOf($className, $factory->$methodName('test')); } public static function provideTestFactory() { return [ ['namespace', Builder\Namespace_::class], ['class', Builder\Class_::class], ['interface', Builder\Interface_::class], ['trait', Builder\Trait_::class], ['enum', Builder\Enum_::class], ['method', Builder\Method::class], ['function', Builder\Function_::class], ['property', Builder\Property::class], ['param', Builder\Param::class], ['use', Builder\Use_::class], ['useFunction', Builder\Use_::class], ['useConst', Builder\Use_::class], ['enumCase', Builder\EnumCase::class], ]; } public function testFactoryClassConst(): void { $factory = new BuilderFactory(); $this->assertInstanceOf(Builder\ClassConst::class, $factory->classConst('TEST', 1)); } public function testAttribute(): void { $factory = new BuilderFactory(); $this->assertEquals( new Attribute(new Name('AttributeName'), [new Arg( new String_('bar'), false, false, [], new Identifier('foo') )]), $factory->attribute('AttributeName', ['foo' => 'bar']) ); } public function testVal(): void { // This method is a wrapper around BuilderHelpers::normalizeValue(), // which is already tested elsewhere $factory = new BuilderFactory(); $this->assertEquals( new String_("foo"), $factory->val("foo") ); } public function testConcat(): void { $factory = new BuilderFactory(); $varA = new Expr\Variable('a'); $varB = new Expr\Variable('b'); $varC = new Expr\Variable('c'); $this->assertEquals( new Concat($varA, $varB), $factory->concat($varA, $varB) ); $this->assertEquals( new Concat(new Concat($varA, $varB), $varC), $factory->concat($varA, $varB, $varC) ); $this->assertEquals( new Concat(new Concat(new String_("a"), $varB), new String_("c")), $factory->concat("a", $varB, "c") ); } public function testConcatOneError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected at least two expressions'); (new BuilderFactory())->concat("a"); } public function testConcatInvalidExpr(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected string or Expr'); (new BuilderFactory())->concat("a", 42); } public function testArgs(): void { $factory = new BuilderFactory(); $unpack = new Arg(new Expr\Variable('c'), false, true); $this->assertEquals( [ new Arg(new Expr\Variable('a')), new Arg(new String_('b')), $unpack ], $factory->args([new Expr\Variable('a'), 'b', $unpack]) ); } public function testNamedArgs(): void { $factory = new BuilderFactory(); $this->assertEquals( [ new Arg(new String_('foo')), new Arg(new String_('baz'), false, false, [], new Identifier('bar')), ], $factory->args(['foo', 'bar' => 'baz']) ); } public function testCalls(): void { $factory = new BuilderFactory(); // Simple function call $this->assertEquals( new Expr\FuncCall( new Name('var_dump'), [new Arg(new String_('str'))] ), $factory->funcCall('var_dump', ['str']) ); // Dynamic function call $this->assertEquals( new Expr\FuncCall(new Expr\Variable('fn')), $factory->funcCall(new Expr\Variable('fn')) ); // Simple method call $this->assertEquals( new Expr\MethodCall( new Expr\Variable('obj'), new Identifier('method'), [new Arg(new Int_(42))] ), $factory->methodCall(new Expr\Variable('obj'), 'method', [42]) ); // Explicitly pass Identifier node $this->assertEquals( new Expr\MethodCall( new Expr\Variable('obj'), new Identifier('method') ), $factory->methodCall(new Expr\Variable('obj'), new Identifier('method')) ); // Dynamic method call $this->assertEquals( new Expr\MethodCall( new Expr\Variable('obj'), new Expr\Variable('method') ), $factory->methodCall(new Expr\Variable('obj'), new Expr\Variable('method')) ); // Simple static method call $this->assertEquals( new Expr\StaticCall( new Name\FullyQualified('Foo'), new Identifier('bar'), [new Arg(new Expr\Variable('baz'))] ), $factory->staticCall('\Foo', 'bar', [new Expr\Variable('baz')]) ); // Dynamic static method call $this->assertEquals( new Expr\StaticCall( new Expr\Variable('foo'), new Expr\Variable('bar') ), $factory->staticCall(new Expr\Variable('foo'), new Expr\Variable('bar')) ); // Simple new call $this->assertEquals( new Expr\New_(new Name\FullyQualified('stdClass')), $factory->new('\stdClass') ); // Dynamic new call $this->assertEquals( new Expr\New_( new Expr\Variable('foo'), [new Arg(new String_('bar'))] ), $factory->new(new Expr\Variable('foo'), ['bar']) ); } public function testConstFetches(): void { $factory = new BuilderFactory(); $this->assertEquals( new Expr\ConstFetch(new Name('FOO')), $factory->constFetch('FOO') ); $this->assertEquals( new Expr\ClassConstFetch(new Name('Foo'), new Identifier('BAR')), $factory->classConstFetch('Foo', 'BAR') ); $this->assertEquals( new Expr\ClassConstFetch(new Expr\Variable('foo'), new Identifier('BAR')), $factory->classConstFetch(new Expr\Variable('foo'), 'BAR') ); $this->assertEquals( new Expr\ClassConstFetch(new Name('Foo'), new Expr\Variable('foo')), $factory->classConstFetch('Foo', $factory->var('foo')) ); } public function testVar(): void { $factory = new BuilderFactory(); $this->assertEquals( new Expr\Variable("foo"), $factory->var("foo") ); $this->assertEquals( new Expr\Variable(new Expr\Variable("foo")), $factory->var($factory->var("foo")) ); } public function testPropertyFetch(): void { $f = new BuilderFactory(); $this->assertEquals( new Expr\PropertyFetch(new Expr\Variable('foo'), 'bar'), $f->propertyFetch($f->var('foo'), 'bar') ); $this->assertEquals( new Expr\PropertyFetch(new Expr\Variable('foo'), 'bar'), $f->propertyFetch($f->var('foo'), new Identifier('bar')) ); $this->assertEquals( new Expr\PropertyFetch(new Expr\Variable('foo'), new Expr\Variable('bar')), $f->propertyFetch($f->var('foo'), $f->var('bar')) ); } public function testInvalidIdentifier(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected string or instance of Node\Identifier'); (new BuilderFactory())->classConstFetch('Foo', new Name('foo')); } public function testInvalidIdentifierOrExpr(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected string or instance of Node\Identifier or Node\Expr'); (new BuilderFactory())->staticCall('Foo', new Name('bar')); } public function testInvalidNameOrExpr(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name must be a string or an instance of Node\Name or Node\Expr'); (new BuilderFactory())->funcCall(new Node\Stmt\Return_()); } public function testInvalidVar(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Variable name must be string or Expr'); (new BuilderFactory())->var(new Node\Stmt\Return_()); } public function testIntegration(): void { $factory = new BuilderFactory(); $node = $factory->namespace('Name\Space') ->addStmt($factory->use('Foo\Bar\SomeOtherClass')) ->addStmt($factory->use('Foo\Bar')->as('A')) ->addStmt($factory->useFunction('strlen')) ->addStmt($factory->useConst('PHP_VERSION')) ->addStmt($factory ->class('SomeClass') ->extend('SomeOtherClass') ->implement('A\Few', '\Interfaces') ->addAttribute($factory->attribute('ClassAttribute', ['repository' => 'fqcn'])) ->makeAbstract() ->addStmt($factory->useTrait('FirstTrait')) ->addStmt($factory->useTrait('SecondTrait', 'ThirdTrait') ->and('AnotherTrait') ->with($factory->traitUseAdaptation('foo')->as('bar')) ->with($factory->traitUseAdaptation('AnotherTrait', 'baz')->as('test')) ->with($factory->traitUseAdaptation('AnotherTrait', 'func')->insteadof('SecondTrait'))) ->addStmt($factory->method('firstMethod') ->addAttribute($factory->attribute('Route', ['/index', 'name' => 'homepage'])) ) ->addStmt($factory->method('someMethod') ->makePublic() ->makeAbstract() ->addParam($factory->param('someParam')->setType('SomeClass')) ->setDocComment('/** * This method does something. * * @param SomeClass And takes a parameter */')) ->addStmt($factory->method('anotherMethod') ->makeProtected() ->addParam($factory->param('someParam') ->setDefault('test') ->addAttribute($factory->attribute('TaggedIterator', ['app.handlers'])) ) ->addStmt(new Expr\Print_(new Expr\Variable('someParam')))) ->addStmt($factory->property('someProperty')->makeProtected()) ->addStmt($factory->property('anotherProperty') ->makePrivate() ->setDefault([1, 2, 3])) ->addStmt($factory->property('integerProperty') ->setType('int') ->addAttribute($factory->attribute('Column', ['options' => ['unsigned' => true]])) ->setDefault(1)) ->addStmt($factory->classConst('CONST_WITH_ATTRIBUTE', 1) ->makePublic() ->addAttribute($factory->attribute('ConstAttribute')) ) ->addStmt($factory->classConst("FIRST_CLASS_CONST", 1) ->addConst("SECOND_CLASS_CONST", 2) ->makePrivate())) ->getNode() ; $expected = <<<'EOC' <?php namespace Name\Space; use Foo\Bar\SomeOtherClass; use Foo\Bar as A; use function strlen; use const PHP_VERSION; #[ClassAttribute(repository: 'fqcn')] abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces { use FirstTrait; use SecondTrait, ThirdTrait, AnotherTrait { foo as bar; AnotherTrait::baz as test; AnotherTrait::func insteadof SecondTrait; } #[ConstAttribute] public const CONST_WITH_ATTRIBUTE = 1; private const FIRST_CLASS_CONST = 1, SECOND_CLASS_CONST = 2; protected $someProperty; private $anotherProperty = [1, 2, 3]; #[Column(options: ['unsigned' => true])] public int $integerProperty = 1; #[Route('/index', name: 'homepage')] function firstMethod() { } /** * This method does something. * * @param SomeClass And takes a parameter */ abstract public function someMethod(SomeClass $someParam); protected function anotherMethod( #[TaggedIterator('app.handlers')] $someParam = 'test' ) { print $someParam; } } EOC; $stmts = [$node]; $prettyPrinter = new PrettyPrinter\Standard(); $generated = $prettyPrinter->prettyPrintFile($stmts); $this->assertEquals( str_replace("\r\n", "\n", $expected), str_replace("\r\n", "\n", $generated) ); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/CodeTestAbstract.php
test/PhpParser/CodeTestAbstract.php
<?php declare(strict_types=1); namespace PhpParser; abstract class CodeTestAbstract extends \PHPUnit\Framework\TestCase { protected static function getTests($directory, $fileExtension, $chunksPerTest = 2) { $parser = new CodeTestParser(); $allTests = []; foreach (filesInDir($directory, $fileExtension) as $fileName => $fileContents) { list($name, $tests) = $parser->parseTest($fileContents, $chunksPerTest); // first part is the name $name .= ' (' . $fileName . ')'; $shortName = ltrim(str_replace($directory, '', $fileName), '/\\'); // multiple sections possible with always two forming a pair foreach ($tests as $i => list($mode, $parts)) { $dataSetName = $shortName . (count($parts) > 1 ? '#' . $i : ''); $allTests[$dataSetName] = array_merge([$name], $parts, [$mode]); } } return $allTests; } public function parseModeLine(?string $modeLine): array { if ($modeLine === null) { return []; } $modes = []; foreach (explode(',', $modeLine) as $mode) { $kv = explode('=', $mode, 2); if (isset($kv[1])) { $modes[$kv[0]] = $kv[1]; } else { $modes[$kv[0]] = true; } } return $modes; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/CodeTestParser.php
test/PhpParser/CodeTestParser.php
<?php declare(strict_types=1); namespace PhpParser; class CodeTestParser { public function parseTest($code, $chunksPerTest) { $code = canonicalize($code); // evaluate @@{expr}@@ expressions $code = preg_replace_callback( '/@@\{(.*?)\}@@/', function ($matches) { return eval('return ' . $matches[1] . ';'); }, $code ); // parse sections $parts = preg_split("/\n-----(?:\n|$)/", $code); // first part is the name $name = array_shift($parts); // multiple sections possible with always two forming a pair $chunks = array_chunk($parts, $chunksPerTest); $tests = []; foreach ($chunks as $chunk) { $lastPart = array_pop($chunk); list($lastPart, $mode) = $this->extractMode($lastPart); $tests[] = [$mode, array_merge($chunk, [$lastPart])]; } return [$name, $tests]; } public function reconstructTest($name, array $tests) { $result = $name; foreach ($tests as list($mode, $parts)) { $lastPart = array_pop($parts); foreach ($parts as $part) { $result .= "\n-----\n$part"; } $result .= "\n-----\n"; if (null !== $mode) { $result .= "!!$mode\n"; } $result .= $lastPart; } return $result . "\n"; } private function extractMode(string $expected): array { $firstNewLine = strpos($expected, "\n"); if (false === $firstNewLine) { $firstNewLine = strlen($expected); } $firstLine = substr($expected, 0, $firstNewLine); if (0 !== strpos($firstLine, '!!')) { return [$expected, null]; } $expected = substr($expected, $firstNewLine + 1); return [$expected, substr($firstLine, 2)]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/LexerTest.php
test/PhpParser/LexerTest.php
<?php declare(strict_types=1); namespace PhpParser; require __DIR__ . '/../../lib/PhpParser/compatibility_tokens.php'; class LexerTest extends \PHPUnit\Framework\TestCase { /* To allow overwriting in parent class */ protected function getLexer() { return new Lexer(); } /** * @dataProvider provideTestError */ public function testError($code, $messages): void { if (defined('HHVM_VERSION')) { $this->markTestSkipped('HHVM does not throw warnings from token_get_all()'); } $errorHandler = new ErrorHandler\Collecting(); $lexer = $this->getLexer(); $lexer->tokenize($code, $errorHandler); $errors = $errorHandler->getErrors(); $this->assertCount(count($messages), $errors); for ($i = 0; $i < count($messages); $i++) { $this->assertSame($messages[$i], $errors[$i]->getMessageWithColumnInfo($code)); } } public static function provideTestError() { return [ ["<?php /*", ["Unterminated comment from 1:7 to 1:9"]], ["<?php /*\n", ["Unterminated comment from 1:7 to 2:1"]], ["<?php \1", ["Unexpected character \"\1\" (ASCII 1) from 1:7 to 1:7"]], ["<?php \0", ["Unexpected null byte from 1:7 to 1:7"]], // Error with potentially emulated token ["<?php ?? \0", ["Unexpected null byte from 1:10 to 1:10"]], ["<?php\n\0\1 foo /* bar", [ "Unexpected null byte from 2:1 to 2:1", "Unexpected character \"\1\" (ASCII 1) from 2:2 to 2:2", "Unterminated comment from 2:8 to 2:14" ]], ]; } public function testDefaultErrorHandler(): void { $this->expectException(Error::class); $this->expectExceptionMessage('Unterminated comment on line 1'); $lexer = $this->getLexer(); $lexer->tokenize("<?php readonly /*"); } /** * @dataProvider provideTestLex */ public function testLex($code, $expectedTokens): void { $lexer = $this->getLexer(); $tokens = $lexer->tokenize($code); foreach ($tokens as $token) { if ($token->id === 0 || $token->isIgnorable()) { continue; } $expectedToken = array_shift($expectedTokens); $this->assertSame($expectedToken[0], $token->id); $this->assertSame($expectedToken[1], $token->text); } } public static function provideTestLex() { return [ // tests PHP 8 T_NAME_* emulation [ '<?php Foo\Bar \Foo\Bar namespace\Foo\Bar Foo\Bar\\', [ [\T_NAME_QUALIFIED, 'Foo\Bar'], [\T_NAME_FULLY_QUALIFIED, '\Foo\Bar'], [\T_NAME_RELATIVE, 'namespace\Foo\Bar'], [\T_NAME_QUALIFIED, 'Foo\Bar'], [\T_NS_SEPARATOR, '\\'], ] ], // tests PHP 8 T_NAME_* emulation with reserved keywords [ '<?php fn\use \fn\use namespace\fn\use fn\use\\', [ [\T_NAME_QUALIFIED, 'fn\use'], [\T_NAME_FULLY_QUALIFIED, '\fn\use'], [\T_NAME_RELATIVE, 'namespace\fn\use'], [\T_NAME_QUALIFIED, 'fn\use'], [\T_NS_SEPARATOR, '\\'], ] ], ]; } public function testGetTokens(): void { $code = '<?php "a";' . "\n" . '// foo' . "\n" . '// bar' . "\n\n" . '"b";'; $expectedTokens = [ new Token(T_OPEN_TAG, '<?php ', 1, 0), new Token(T_CONSTANT_ENCAPSED_STRING, '"a"', 1, 6), new Token(\ord(';'), ';', 1, 9), new Token(T_WHITESPACE, "\n", 1, 10), new Token(T_COMMENT, '// foo', 2, 11), new Token(T_WHITESPACE, "\n", 2, 17), new Token(T_COMMENT, '// bar', 3, 18), new Token(T_WHITESPACE, "\n\n", 3, 24), new Token(T_CONSTANT_ENCAPSED_STRING, '"b"', 5, 26), new Token(\ord(';'), ';', 5, 29), new Token(0, "\0", 5, 30), ]; $lexer = $this->getLexer(); $this->assertEquals($expectedTokens, $lexer->tokenize($code)); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/ParserFactoryTest.php
test/PhpParser/ParserFactoryTest.php
<?php declare(strict_types=1); namespace PhpParser; /* This test is very weak, because PHPUnit's assertEquals assertion is way too slow dealing with the * large objects involved here. So we just do some basic instanceof tests instead. */ use PhpParser\Parser\Php7; use PhpParser\Parser\Php8; class ParserFactoryTest extends \PHPUnit\Framework\TestCase { public function testCreate(): void { $factory = new ParserFactory(); $this->assertInstanceOf(Php8::class, $factory->createForNewestSupportedVersion()); $this->assertInstanceOf(Parser::class, $factory->createForHostVersion()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/CodeParsingTest.php
test/PhpParser/CodeParsingTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; use PhpParser\Node\Stmt; class CodeParsingTest extends CodeTestAbstract { /** * @dataProvider provideTestParse */ public function testParse($name, $code, $expected, $modeLine): void { $modes = $this->parseModeLine($modeLine); $parser = $this->createParser($modes['version'] ?? null); list($stmts, $output) = $this->getParseOutput($parser, $code, $modes); $this->assertSame($expected, $output, $name); $this->checkAttributes($stmts); } public function createParser(?string $version): Parser { $factory = new ParserFactory(); $version = $version === null ? PhpVersion::getNewestSupported() : PhpVersion::fromString($version); return $factory->createForVersion($version); } // Must be public for updateTests.php public function getParseOutput(Parser $parser, $code, array $modes) { $dumpPositions = isset($modes['positions']); $dumpOtherAttributes = isset($modes['attributes']); $errors = new ErrorHandler\Collecting(); $stmts = $parser->parse($code, $errors); $output = ''; foreach ($errors->getErrors() as $error) { $output .= $this->formatErrorMessage($error, $code) . "\n"; } if (null !== $stmts) { $dumper = new NodeDumper([ 'dumpComments' => true, 'dumpPositions' => $dumpPositions, 'dumpOtherAttributes' => $dumpOtherAttributes, ]); $output .= $dumper->dump($stmts, $code); } return [$stmts, canonicalize($output)]; } public static function provideTestParse() { return self::getTests(__DIR__ . '/../code/parser', 'test'); } private function formatErrorMessage(Error $e, $code) { if ($e->hasColumnInfo()) { return $e->getMessageWithColumnInfo($code); } return $e->getMessage(); } private function checkAttributes($stmts): void { if ($stmts === null) { return; } $traverser = new NodeTraverser(new class () extends NodeVisitorAbstract { public function enterNode(Node $node): void { $startLine = $node->getStartLine(); $endLine = $node->getEndLine(); $startFilePos = $node->getStartFilePos(); $endFilePos = $node->getEndFilePos(); $startTokenPos = $node->getStartTokenPos(); $endTokenPos = $node->getEndTokenPos(); if ($startLine < 0 || $endLine < 0 || $startFilePos < 0 || $endFilePos < 0 || $startTokenPos < 0 || $endTokenPos < 0 ) { throw new \Exception('Missing location information on ' . $node->getType()); } if ($endLine < $startLine || $endFilePos < $startFilePos || $endTokenPos < $startTokenPos ) { // Nop and Error can have inverted order, if they are empty. // This can also happen for a Param containing an Error. if (!$node instanceof Stmt\Nop && !$node instanceof Expr\Error && !$node instanceof Node\Param ) { throw new \Exception('End < start on ' . $node->getType()); } } } }); $traverser->traverse($stmts); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NameContextTest.php
test/PhpParser/NameContextTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Name; use PhpParser\Node\Stmt\Use_; class NameContextTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideTestGetPossibleNames */ public function testGetPossibleNames($type, $name, $expectedPossibleNames): void { $nameContext = new NameContext(new ErrorHandler\Throwing()); $nameContext->startNamespace(new Name('NS')); $nameContext->addAlias(new Name('Foo'), 'Foo', Use_::TYPE_NORMAL); $nameContext->addAlias(new Name('Foo\Bar'), 'Alias', Use_::TYPE_NORMAL); $nameContext->addAlias(new Name('Foo\fn'), 'fn', Use_::TYPE_FUNCTION); $nameContext->addAlias(new Name('Foo\CN'), 'CN', Use_::TYPE_CONSTANT); $possibleNames = $nameContext->getPossibleNames($name, $type); $possibleNames = array_map(function (Name $name) { return $name->toCodeString(); }, $possibleNames); $this->assertSame($expectedPossibleNames, $possibleNames); // Here the last name is always the shortest one $expectedShortName = $expectedPossibleNames[count($expectedPossibleNames) - 1]; $this->assertSame( $expectedShortName, $nameContext->getShortName($name, $type)->toCodeString() ); } public static function provideTestGetPossibleNames() { return [ [Use_::TYPE_NORMAL, 'Test', ['\Test']], [Use_::TYPE_NORMAL, 'Test\Namespaced', ['\Test\Namespaced']], [Use_::TYPE_NORMAL, 'NS\Test', ['\NS\Test', 'Test']], [Use_::TYPE_NORMAL, 'ns\Test', ['\ns\Test', 'Test']], [Use_::TYPE_NORMAL, 'NS\Foo\Bar', ['\NS\Foo\Bar']], [Use_::TYPE_NORMAL, 'ns\foo\Bar', ['\ns\foo\Bar']], [Use_::TYPE_NORMAL, 'Foo', ['\Foo', 'Foo']], [Use_::TYPE_NORMAL, 'Foo\Bar', ['\Foo\Bar', 'Foo\Bar', 'Alias']], [Use_::TYPE_NORMAL, 'Foo\Bar\Baz', ['\Foo\Bar\Baz', 'Foo\Bar\Baz', 'Alias\Baz']], [Use_::TYPE_NORMAL, 'Foo\fn\Bar', ['\Foo\fn\Bar', 'Foo\fn\Bar']], [Use_::TYPE_FUNCTION, 'Foo\fn\bar', ['\Foo\fn\bar', 'Foo\fn\bar']], [Use_::TYPE_FUNCTION, 'Foo\fn', ['\Foo\fn', 'Foo\fn', 'fn']], [Use_::TYPE_FUNCTION, 'Foo\FN', ['\Foo\FN', 'Foo\FN', 'fn']], [Use_::TYPE_CONSTANT, 'Foo\CN\BAR', ['\Foo\CN\BAR', 'Foo\CN\BAR']], [Use_::TYPE_CONSTANT, 'Foo\CN', ['\Foo\CN', 'Foo\CN', 'CN']], [Use_::TYPE_CONSTANT, 'foo\CN', ['\foo\CN', 'Foo\CN', 'CN']], [Use_::TYPE_CONSTANT, 'foo\cn', ['\foo\cn', 'Foo\cn']], // self/parent/static must not be fully qualified [Use_::TYPE_NORMAL, 'self', ['self']], [Use_::TYPE_NORMAL, 'parent', ['parent']], [Use_::TYPE_NORMAL, 'static', ['static']], // true/false/null do not need to be fully qualified, even in namespaces [Use_::TYPE_CONSTANT, 'true', ['\true', 'true']], [Use_::TYPE_CONSTANT, 'false', ['\false', 'false']], [Use_::TYPE_CONSTANT, 'null', ['\null', 'null']], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/PhpVersionTest.php
test/PhpParser/PhpVersionTest.php
<?php declare(strict_types=1); namespace PhpParser; class PhpVersionTest extends \PHPUnit\Framework\TestCase { public function testConstruction(): void { $version = PhpVersion::fromComponents(8, 2); $this->assertSame(80200, $version->id); $version = PhpVersion::fromString('8.2'); $this->assertSame(80200, $version->id); $version = PhpVersion::fromString('8.2.14'); $this->assertSame(80200, $version->id); $version = PhpVersion::fromString('8.2.14rc1'); $this->assertSame(80200, $version->id); } public function testInvalidVersion(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Invalid PHP version "8"'); PhpVersion::fromString('8'); } public function testEquals(): void { $php74 = PhpVersion::fromComponents(7, 4); $php81 = PhpVersion::fromComponents(8, 1); $php82 = PhpVersion::fromComponents(8, 2); $this->assertTrue($php81->equals($php81)); $this->assertFalse($php81->equals($php82)); $this->assertTrue($php81->older($php82)); $this->assertFalse($php81->older($php81)); $this->assertFalse($php81->older($php74)); $this->assertFalse($php81->newerOrEqual($php82)); $this->assertTrue($php81->newerOrEqual($php81)); $this->assertTrue($php81->newerOrEqual($php74)); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeDumperTest.php
test/PhpParser/NodeDumperTest.php
<?php declare(strict_types=1); namespace PhpParser; class NodeDumperTest extends \PHPUnit\Framework\TestCase { private function canonicalize($string) { return str_replace("\r\n", "\n", $string); } /** * @dataProvider provideTestDump */ public function testDump($node, $dump): void { $dumper = new NodeDumper(); $this->assertSame($this->canonicalize($dump), $this->canonicalize($dumper->dump($node))); } public static function provideTestDump() { return [ [ [], 'array( )' ], [ ['Foo', 'Bar', 'Key' => 'FooBar'], 'array( 0: Foo 1: Bar Key: FooBar )' ], [ new Node\Name(['Hallo', 'World']), 'Name( name: Hallo\World )' ], [ new Node\Expr\Array_([ new Node\ArrayItem(new Node\Scalar\String_('Foo')) ]), 'Expr_Array( items: array( 0: ArrayItem( key: null value: Scalar_String( value: Foo ) byRef: false unpack: false ) ) )' ], ]; } public function testDumpWithPositions(): void { $parser = (new ParserFactory())->createForHostVersion(); $dumper = new NodeDumper(['dumpPositions' => true]); $code = "<?php\n\$a = 1;\necho \$a;"; $expected = <<<'OUT' array( 0: Stmt_Expression[2:1 - 2:7]( expr: Expr_Assign[2:1 - 2:6]( var: Expr_Variable[2:1 - 2:2]( name: a ) expr: Scalar_Int[2:6 - 2:6]( value: 1 ) ) ) 1: Stmt_Echo[3:1 - 3:8]( exprs: array( 0: Expr_Variable[3:6 - 3:7]( name: a ) ) ) ) OUT; $stmts = $parser->parse($code); $dump = $dumper->dump($stmts, $code); $this->assertSame($this->canonicalize($expected), $this->canonicalize($dump)); } public function testError(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Can only dump nodes and arrays.'); $dumper = new NodeDumper(); $dumper->dump(new \stdClass()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeFinderTest.php
test/PhpParser/NodeFinderTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; class NodeFinderTest extends \PHPUnit\Framework\TestCase { private function getStmtsAndVars() { $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\BinaryOp\Concat( new Expr\Variable('b'), new Expr\Variable('c') )); $stmts = [new Node\Stmt\Expression($assign)]; $vars = [$assign->var, $assign->expr->left, $assign->expr->right]; return [$stmts, $vars]; } public function testFind(): void { $finder = new NodeFinder(); list($stmts, $vars) = $this->getStmtsAndVars(); $varFilter = function (Node $node) { return $node instanceof Expr\Variable; }; $this->assertSame($vars, $finder->find($stmts, $varFilter)); $this->assertSame($vars, $finder->find($stmts[0], $varFilter)); $noneFilter = function () { return false; }; $this->assertSame([], $finder->find($stmts, $noneFilter)); } public function testFindInstanceOf(): void { $finder = new NodeFinder(); list($stmts, $vars) = $this->getStmtsAndVars(); $this->assertSame($vars, $finder->findInstanceOf($stmts, Expr\Variable::class)); $this->assertSame($vars, $finder->findInstanceOf($stmts[0], Expr\Variable::class)); $this->assertSame([], $finder->findInstanceOf($stmts, Expr\BinaryOp\Mul::class)); } public function testFindFirst(): void { $finder = new NodeFinder(); list($stmts, $vars) = $this->getStmtsAndVars(); $varFilter = function (Node $node) { return $node instanceof Expr\Variable; }; $this->assertSame($vars[0], $finder->findFirst($stmts, $varFilter)); $this->assertSame($vars[0], $finder->findFirst($stmts[0], $varFilter)); $noneFilter = function () { return false; }; $this->assertNull($finder->findFirst($stmts, $noneFilter)); } public function testFindFirstInstanceOf(): void { $finder = new NodeFinder(); list($stmts, $vars) = $this->getStmtsAndVars(); $this->assertSame($vars[0], $finder->findFirstInstanceOf($stmts, Expr\Variable::class)); $this->assertSame($vars[0], $finder->findFirstInstanceOf($stmts[0], Expr\Variable::class)); $this->assertNull($finder->findFirstInstanceOf($stmts, Expr\BinaryOp\Mul::class)); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/CommentTest.php
test/PhpParser/CommentTest.php
<?php declare(strict_types=1); namespace PhpParser; class CommentTest extends \PHPUnit\Framework\TestCase { public function testGetters(): void { $comment = new Comment('/* Some comment */', 1, 10, 2, 1, 27, 2); $this->assertSame('/* Some comment */', $comment->getText()); $this->assertSame('/* Some comment */', (string) $comment); $this->assertSame(1, $comment->getStartLine()); $this->assertSame(10, $comment->getStartFilePos()); $this->assertSame(2, $comment->getStartTokenPos()); $this->assertSame(1, $comment->getEndLine()); $this->assertSame(27, $comment->getEndFilePos()); $this->assertSame(2, $comment->getEndTokenPos()); } /** * @dataProvider provideTestReformatting */ public function testReformatting($commentText, $reformattedText): void { $comment = new Comment($commentText); $this->assertSame($reformattedText, $comment->getReformattedText()); } public static function provideTestReformatting() { return [ ['// Some text', '// Some text'], ['/* Some text */', '/* Some text */'], [ "/**\n * Some text.\n * Some more text.\n */", "/**\n * Some text.\n * Some more text.\n */" ], [ "/**\r\n * Some text.\r\n * Some more text.\r\n */", "/**\n * Some text.\n * Some more text.\n */" ], [ "/*\n Some text.\n Some more text.\n */", "/*\n Some text.\n Some more text.\n*/" ], [ "/*\r\n Some text.\r\n Some more text.\r\n */", "/*\n Some text.\n Some more text.\n*/" ], [ "/* Some text.\n More text.\n Even more text. */", "/* Some text.\n More text.\n Even more text. */" ], [ "/* Some text.\r\n More text.\r\n Even more text. */", "/* Some text.\n More text.\n Even more text. */" ], [ "/* Some text.\n More text.\n Indented text. */", "/* Some text.\n More text.\n Indented text. */", ], // invalid comment -> no reformatting [ "hello\n world", "hello\n world", ], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/ConstExprEvaluatorTest.php
test/PhpParser/ConstExprEvaluatorTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; use PhpParser\Node\Scalar; class ConstExprEvaluatorTest extends \PHPUnit\Framework\TestCase { /** @dataProvider provideTestEvaluate */ public function testEvaluate($exprString, $expected): void { $parser = (new ParserFactory())->createForNewestSupportedVersion(); $expr = $parser->parse('<?php ' . $exprString . ';')[0]->expr; $evaluator = new ConstExprEvaluator(); $this->assertSame($expected, $evaluator->evaluateDirectly($expr)); } public static function provideTestEvaluate() { return [ ['1', 1], ['1.0', 1.0], ['"foo"', "foo"], ['[0, 1]', [0, 1]], ['["foo" => "bar"]', ["foo" => "bar"]], ['[...["bar"]]', ["bar"]], ['[...["foo" => "bar"]]', ["foo" => "bar"]], ['["a", "b" => "b", ...["b" => "bb", "c"]]', ["a", "b" => "bb", "c"]], ['NULL', null], ['False', false], ['true', true], ['+1', 1], ['-1', -1], ['~0', -1], ['!true', false], ['[0][0]', 0], ['"a"[0]', "a"], ['true ? 1 : (1/0)', 1], ['false ? (1/0) : 1', 1], ['42 ?: (1/0)', 42], ['false ?: 42', 42], ['false ?? 42', false], ['null ?? 42', 42], ['[0][0] ?? 42', 0], ['[][0] ?? 42', 42], ['0b11 & 0b10', 0b10], ['0b11 | 0b10', 0b11], ['0b11 ^ 0b10', 0b01], ['1 << 2', 4], ['4 >> 2', 1], ['"a" . "b"', "ab"], ['4 + 2', 6], ['4 - 2', 2], ['4 * 2', 8], ['4 / 2', 2], ['4 % 2', 0], ['4 ** 2', 16], ['1 == 1.0', true], ['1 != 1.0', false], ['1 < 2.0', true], ['1 <= 2.0', true], ['1 > 2.0', false], ['1 >= 2.0', false], ['1 <=> 2.0', -1], ['1 === 1.0', false], ['1 !== 1.0', true], ['true && true', true], ['true and true', true], ['false && (1/0)', false], ['false and (1/0)', false], ['false || false', false], ['false or false', false], ['true || (1/0)', true], ['true or (1/0)', true], ['true xor false', true], ['"foo" |> "strlen"', 3], ]; } public function testEvaluateFails(): void { $this->expectException(ConstExprEvaluationException::class); $this->expectExceptionMessage('Expression of type Expr_Variable cannot be evaluated'); $evaluator = new ConstExprEvaluator(); $evaluator->evaluateDirectly(new Expr\Variable('a')); } public function testEvaluateFallback(): void { $evaluator = new ConstExprEvaluator(function (Expr $expr) { if ($expr instanceof Scalar\MagicConst\Line) { return 42; } throw new ConstExprEvaluationException(); }); $expr = new Expr\BinaryOp\Plus( new Scalar\Int_(8), new Scalar\MagicConst\Line() ); $this->assertSame(50, $evaluator->evaluateDirectly($expr)); } /** * @dataProvider provideTestEvaluateSilently */ public function testEvaluateSilently($expr, $exception, $msg): void { $evaluator = new ConstExprEvaluator(); try { $evaluator->evaluateSilently($expr); } catch (ConstExprEvaluationException $e) { $this->assertSame( 'An error occurred during constant expression evaluation', $e->getMessage() ); $prev = $e->getPrevious(); $this->assertInstanceOf($exception, $prev); $this->assertSame($msg, $prev->getMessage()); } } public static function provideTestEvaluateSilently() { return [ [ new Expr\BinaryOp\Mod(new Scalar\Int_(42), new Scalar\Int_(0)), \Error::class, 'Modulo by zero' ], [ new Expr\BinaryOp\Plus(new Scalar\Int_(42), new Scalar\String_("1foo")), \ErrorException::class, \PHP_VERSION_ID >= 80000 ? 'A non-numeric value encountered' : 'A non well formed numeric value encountered' ], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/PrettyPrinterTest.php
test/PhpParser/PrettyPrinterTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Float_; use PhpParser\Node\Scalar\InterpolatedString; use PhpParser\Node\InterpolatedStringPart; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; use PhpParser\PrettyPrinter\Standard; class PrettyPrinterTest extends CodeTestAbstract { /** @return array{0: Parser, 1: PrettyPrinter} */ private function createParserAndPrinter(array $options): array { $parserVersion = $options['parserVersion'] ?? $options['version'] ?? null; $printerVersion = $options['version'] ?? null; $indent = isset($options['indent']) ? json_decode($options['indent']) : null; $factory = new ParserFactory(); $parser = $factory->createForVersion($parserVersion !== null ? PhpVersion::fromString($parserVersion) : PhpVersion::getNewestSupported()); $prettyPrinter = new Standard([ 'phpVersion' => $printerVersion !== null ? PhpVersion::fromString($printerVersion) : null, 'indent' => $indent, ]); return [$parser, $prettyPrinter]; } protected function doTestPrettyPrintMethod($method, $name, $code, $expected, $modeLine) { [$parser, $prettyPrinter] = $this->createParserAndPrinter($this->parseModeLine($modeLine)); $output = canonicalize($prettyPrinter->$method($parser->parse($code))); $this->assertSame($expected, $output, $name); } /** * @dataProvider provideTestPrettyPrint */ public function testPrettyPrint($name, $code, $expected, $mode): void { $this->doTestPrettyPrintMethod('prettyPrint', $name, $code, $expected, $mode); } /** * @dataProvider provideTestPrettyPrintFile */ public function testPrettyPrintFile($name, $code, $expected, $mode): void { $this->doTestPrettyPrintMethod('prettyPrintFile', $name, $code, $expected, $mode); } public static function provideTestPrettyPrint() { return self::getTests(__DIR__ . '/../code/prettyPrinter', 'test'); } public static function provideTestPrettyPrintFile() { return self::getTests(__DIR__ . '/../code/prettyPrinter', 'file-test'); } public function testPrettyPrintExpr(): void { $prettyPrinter = new Standard(); $expr = new Expr\BinaryOp\Mul( new Expr\BinaryOp\Plus(new Expr\Variable('a'), new Expr\Variable('b')), new Expr\Variable('c') ); $this->assertEquals('($a + $b) * $c', $prettyPrinter->prettyPrintExpr($expr)); $expr = new Expr\Closure([ 'stmts' => [new Stmt\Return_(new String_("a\nb"))] ]); $this->assertEquals("function () {\n return 'a\nb';\n}", $prettyPrinter->prettyPrintExpr($expr)); } public function testCommentBeforeInlineHTML(): void { $prettyPrinter = new PrettyPrinter\Standard(); $comment = new Comment\Doc("/**\n * This is a comment\n */"); $stmts = [new Stmt\InlineHTML('Hello World!', ['comments' => [$comment]])]; $expected = "<?php\n\n/**\n * This is a comment\n */\n?>\nHello World!"; $this->assertSame($expected, $prettyPrinter->prettyPrintFile($stmts)); } public function testArraySyntaxDefault(): void { $prettyPrinter = new Standard(['shortArraySyntax' => true]); $expr = new Expr\Array_([ new Node\ArrayItem(new String_('val'), new String_('key')) ]); $expected = "['key' => 'val']"; $this->assertSame($expected, $prettyPrinter->prettyPrintExpr($expr)); } /** * @dataProvider provideTestKindAttributes */ public function testKindAttributes($node, $expected): void { $prttyPrinter = new PrettyPrinter\Standard(); $result = $prttyPrinter->prettyPrintExpr($node); $this->assertSame($expected, $result); } public static function provideTestKindAttributes() { $nowdoc = ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR']; $heredoc = ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR']; return [ // Defaults to single quoted [new String_('foo'), "'foo'"], // Explicit single/double quoted [new String_('foo', ['kind' => String_::KIND_SINGLE_QUOTED]), "'foo'"], [new String_('foo', ['kind' => String_::KIND_DOUBLE_QUOTED]), '"foo"'], // Fallback from doc string if no label [new String_('foo', ['kind' => String_::KIND_NOWDOC]), "'foo'"], [new String_('foo', ['kind' => String_::KIND_HEREDOC]), '"foo"'], // Fallback if string contains label [new String_("A\nB\nC", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'A']), "'A\nB\nC'"], [new String_("A\nB\nC", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'B']), "'A\nB\nC'"], [new String_("A\nB\nC", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'C']), "'A\nB\nC'"], [new String_("STR;", $nowdoc), "'STR;'"], [new String_("STR,", $nowdoc), "'STR,'"], [new String_(" STR", $nowdoc), "' STR'"], [new String_("\tSTR", $nowdoc), "'\tSTR'"], [new String_("STR\x80", $heredoc), '"STR\x80"'], // Doc string if label not contained (or not in ending position) [new String_("foo", $nowdoc), "<<<'STR'\nfoo\nSTR"], [new String_("foo", $heredoc), "<<<STR\nfoo\nSTR"], [new String_("STRx", $nowdoc), "<<<'STR'\nSTRx\nSTR"], [new String_("xSTR", $nowdoc), "<<<'STR'\nxSTR\nSTR"], [new String_("STRä", $nowdoc), "<<<'STR'\nSTRä\nSTR"], [new String_("STR\x80", $nowdoc), "<<<'STR'\nSTR\x80\nSTR"], // Empty doc string variations (encapsed variant does not occur naturally) [new String_("", $nowdoc), "<<<'STR'\nSTR"], [new String_("", $heredoc), "<<<STR\nSTR"], [new InterpolatedString([new InterpolatedStringPart('')], $heredoc), "<<<STR\nSTR"], // Isolated \r in doc string [new String_("\r", $heredoc), "<<<STR\n\\r\nSTR"], [new String_("\r", $nowdoc), "'\r'"], [new String_("\rx", $nowdoc), "<<<'STR'\n\rx\nSTR"], // Encapsed doc string variations [new InterpolatedString([new InterpolatedStringPart('foo')], $heredoc), "<<<STR\nfoo\nSTR"], [new InterpolatedString([new InterpolatedStringPart('foo'), new Expr\Variable('y')], $heredoc), "<<<STR\nfoo{\$y}\nSTR"], [new InterpolatedString([new Expr\Variable('y'), new InterpolatedStringPart("STR\n")], $heredoc), "<<<STR\n{\$y}STR\n\nSTR"], // Encapsed doc string fallback [new InterpolatedString([new Expr\Variable('y'), new InterpolatedStringPart("\nSTR")], $heredoc), '"{$y}\\nSTR"'], [new InterpolatedString([new InterpolatedStringPart("STR\n"), new Expr\Variable('y')], $heredoc), '"STR\\n{$y}"'], [new InterpolatedString([new InterpolatedStringPart("STR")], $heredoc), '"STR"'], [new InterpolatedString([new InterpolatedStringPart("\nSTR"), new Expr\Variable('y')], $heredoc), '"\nSTR{$y}"'], [new InterpolatedString([new InterpolatedStringPart("STR\x80"), new Expr\Variable('y')], $heredoc), '"STR\x80{$y}"'], ]; } /** @dataProvider provideTestUnnaturalLiterals */ public function testUnnaturalLiterals($node, $expected): void { $prttyPrinter = new PrettyPrinter\Standard(); $result = $prttyPrinter->prettyPrintExpr($node); $this->assertSame($expected, $result); } public static function provideTestUnnaturalLiterals() { return [ [new Int_(-1), '-1'], [new Int_(-PHP_INT_MAX - 1), '(-' . PHP_INT_MAX . '-1)'], [new Int_(-1, ['kind' => Int_::KIND_BIN]), '-0b1'], [new Int_(-1, ['kind' => Int_::KIND_OCT]), '-01'], [new Int_(-1, ['kind' => Int_::KIND_HEX]), '-0x1'], [new Float_(\INF), '1.0E+1000'], [new Float_(-\INF), '-1.0E+1000'], [new Float_(-\NAN), '\NAN'], ]; } /** @dataProvider provideTestCustomRawValue */ public function printCustomRawValue($node, $expected): void { $prettyPrinter = new PrettyPrinter\Standard(); $result = $prettyPrinter->prettyPrintExpr($node); $this->assertSame($expected, $result); } public static function provideTestCustomRawValue() { return [ // Decimal with separator [new Int_(1000, ['rawValue' => '10_00', 'shouldPrintRawValue' => true]), '10_00'], // Hexadecimal with separator [new Int_(0xDEADBEEF, ['kind' => Int_::KIND_HEX, 'rawValue' => '0xDEAD_BEEF', 'shouldPrintRawValue' => true]), '0xDEAD_BEEF'], // Binary with separator [new Int_(0b11110000, ['kind' => Int_::KIND_BIN, 'rawValue' => '0b1111_0000', 'shouldPrintRawValue' => true]), '0b1111_0000'], // Octal with separator [new Int_(0755, ['kind' => Int_::KIND_OCT, 'rawValue' => '0755_000', 'shouldPrintRawValue' => true]), '0755_000'], // Without flag set, should use default formatting [new Int_(1000, ['rawValue' => '10_00', 'shouldPrintRawValue' => false]), '1000'], ]; } public function testPrettyPrintWithError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot pretty-print AST with Error nodes'); $stmts = [new Stmt\Expression( new Expr\PropertyFetch(new Expr\Variable('a'), new Expr\Error()) )]; $prettyPrinter = new PrettyPrinter\Standard(); $prettyPrinter->prettyPrint($stmts); } public function testPrettyPrintWithErrorInClassConstFetch(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot pretty-print AST with Error nodes'); $stmts = [new Stmt\Expression( new Expr\ClassConstFetch(new Name('Foo'), new Expr\Error()) )]; $prettyPrinter = new PrettyPrinter\Standard(); $prettyPrinter->prettyPrint($stmts); } /** * @dataProvider provideTestFormatPreservingPrint */ public function testFormatPreservingPrint($name, $code, $modification, $expected, $modeLine): void { [$parser, $printer] = $this->createParserAndPrinter($this->parseModeLine($modeLine)); $traverser = new NodeTraverser(new NodeVisitor\CloningVisitor()); $oldStmts = $parser->parse($code); $oldTokens = $parser->getTokens(); $newStmts = $traverser->traverse($oldStmts); /** @var callable $fn */ eval(<<<CODE use PhpParser\Comment; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Scalar; use PhpParser\Node\Stmt; use PhpParser\Modifiers; \$fn = function(&\$stmts) { $modification }; CODE ); $fn($newStmts); $newCode = $printer->printFormatPreserving($newStmts, $oldStmts, $oldTokens); $this->assertSame(canonicalize($expected), canonicalize($newCode), $name); } public static function provideTestFormatPreservingPrint() { return self::getTests(__DIR__ . '/../code/formatPreservation', 'test', 3); } /** * @dataProvider provideTestRoundTripPrint */ public function testRoundTripPrint($name, $code, $expected, $modeLine): void { /** * This test makes sure that the format-preserving pretty printer round-trips for all * the pretty printer tests (i.e. returns the input if no changes occurred). */ [$parser, $printer] = $this->createParserAndPrinter($this->parseModeLine($modeLine)); $traverser = new NodeTraverser(new NodeVisitor\CloningVisitor()); try { $oldStmts = $parser->parse($code); } catch (Error $e) { // Can't do a format-preserving print on a file with errors return; } $oldTokens = $parser->getTokens(); $newStmts = $traverser->traverse($oldStmts); $newCode = $printer->printFormatPreserving($newStmts, $oldStmts, $oldTokens); $this->assertSame(canonicalize($code), canonicalize($newCode), $name); } public static function provideTestRoundTripPrint() { return array_merge( self::getTests(__DIR__ . '/../code/prettyPrinter', 'test'), self::getTests(__DIR__ . '/../code/parser', 'test') ); } public function testWindowsNewline(): void { $prettyPrinter = new Standard([ 'newline' => "\r\n", 'phpVersion' => PhpVersion::fromComponents(7, 2), ]); $stmts = [ new Stmt\If_(new Int_(1), [ 'stmts' => [ new Stmt\Echo_([new String_('Hello')]), new Stmt\Echo_([new String_('World')]), ], ]), ]; $code = $prettyPrinter->prettyPrint($stmts); $this->assertSame("if (1) {\r\n echo 'Hello';\r\n echo 'World';\r\n}", $code); $code = $prettyPrinter->prettyPrintFile($stmts); $this->assertSame("<?php\r\n\r\nif (1) {\r\n echo 'Hello';\r\n echo 'World';\r\n}", $code); $stmts = [new Stmt\InlineHTML('Hello world')]; $code = $prettyPrinter->prettyPrintFile($stmts); $this->assertSame("Hello world", $code); $stmts = [ new Stmt\Expression(new String_('Test', [ 'kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR' ])), new Stmt\Expression(new String_('Test 2', [ 'kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR' ])), new Stmt\Expression(new InterpolatedString([new InterpolatedStringPart('Test 3')], [ 'kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR' ])), ]; $code = $prettyPrinter->prettyPrint($stmts); $this->assertSame( "<<<'STR'\r\nTest\r\nSTR;\r\n<<<STR\r\nTest 2\r\nSTR;\r\n<<<STR\r\nTest 3\r\nSTR\r\n;", $code); } public function testInvalidNewline(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Option "newline" must be one of "\n" or "\r\n"'); new PrettyPrinter\Standard(['newline' => 'foo']); } public function testInvalidIndent(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Option "indent" must either be all spaces or a single tab'); new PrettyPrinter\Standard(['indent' => "\t "]); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/BuilderHelpersTest.php
test/PhpParser/BuilderHelpersTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Builder\Class_; use PhpParser\Node\Identifier; use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Scalar; use PhpParser\Node\Stmt; use PhpParser\Node\Expr; class BuilderHelpersTest extends \PHPUnit\Framework\TestCase { public function testNormalizeNode(): void { $builder = new Class_('SomeClass'); $this->assertEquals($builder->getNode(), BuilderHelpers::normalizeNode($builder)); $attribute = new Node\Attribute(new Node\Name('Test')); $this->assertSame($attribute, BuilderHelpers::normalizeNode($attribute)); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected node or builder object'); BuilderHelpers::normalizeNode('test'); } public function testNormalizeStmt(): void { $stmt = new Node\Stmt\Class_('Class'); $this->assertSame($stmt, BuilderHelpers::normalizeStmt($stmt)); $expr = new Expr\Variable('fn'); $normalizedExpr = BuilderHelpers::normalizeStmt($expr); $this->assertEquals(new Stmt\Expression($expr), $normalizedExpr); $this->assertSame($expr, $normalizedExpr->expr); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected statement or expression node'); BuilderHelpers::normalizeStmt(new Node\Attribute(new Node\Name('Test'))); } public function testNormalizeStmtInvalidType(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected node or builder object'); BuilderHelpers::normalizeStmt('test'); } public function testNormalizeIdentifier(): void { $identifier = new Node\Identifier('fn'); $this->assertSame($identifier, BuilderHelpers::normalizeIdentifier($identifier)); $this->assertEquals($identifier, BuilderHelpers::normalizeIdentifier('fn')); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected string or instance of Node\Identifier'); BuilderHelpers::normalizeIdentifier(1); } public function testNormalizeIdentifierOrExpr(): void { $identifier = new Node\Identifier('fn'); $this->assertSame($identifier, BuilderHelpers::normalizeIdentifierOrExpr($identifier)); $expr = new Expr\Variable('fn'); $this->assertSame($expr, BuilderHelpers::normalizeIdentifierOrExpr($expr)); $this->assertEquals($identifier, BuilderHelpers::normalizeIdentifierOrExpr('fn')); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected string or instance of Node\Identifier'); BuilderHelpers::normalizeIdentifierOrExpr(1); } public function testNormalizeName(): void { $name = new Node\Name('test'); $this->assertSame($name, BuilderHelpers::normalizeName($name)); $this->assertEquals( new Node\Name\FullyQualified(['Namespace', 'Test']), BuilderHelpers::normalizeName('\\Namespace\\Test') ); $this->assertEquals( new Node\Name\Relative(['Test']), BuilderHelpers::normalizeName('namespace\\Test') ); $this->assertEquals($name, BuilderHelpers::normalizeName('test')); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name cannot be empty'); BuilderHelpers::normalizeName(''); } public function testNormalizeNameInvalidType(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name must be a string or an instance of Node\Name'); BuilderHelpers::normalizeName(1); } public function testNormalizeNameOrExpr(): void { $expr = new Expr\Variable('fn'); $this->assertSame($expr, BuilderHelpers::normalizeNameOrExpr($expr)); $name = new Node\Name('test'); $this->assertSame($name, BuilderHelpers::normalizeNameOrExpr($name)); $this->assertEquals( new Node\Name\FullyQualified(['Namespace', 'Test']), BuilderHelpers::normalizeNameOrExpr('\\Namespace\\Test') ); $this->assertEquals( new Node\Name\Relative(['Test']), BuilderHelpers::normalizeNameOrExpr('namespace\\Test') ); $this->assertEquals($name, BuilderHelpers::normalizeNameOrExpr('test')); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name cannot be empty'); BuilderHelpers::normalizeNameOrExpr(''); } public function testNormalizeNameOrExpInvalidType(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name must be a string or an instance of Node\Name or Node\Expr'); BuilderHelpers::normalizeNameOrExpr(1); } public function testNormalizeType(): void { $this->assertEquals(new Node\Identifier('array'), BuilderHelpers::normalizeType('array')); $this->assertEquals(new Node\Identifier('callable'), BuilderHelpers::normalizeType('callable')); $this->assertEquals(new Node\Identifier('string'), BuilderHelpers::normalizeType('string')); $this->assertEquals(new Node\Identifier('int'), BuilderHelpers::normalizeType('int')); $this->assertEquals(new Node\Identifier('float'), BuilderHelpers::normalizeType('float')); $this->assertEquals(new Node\Identifier('bool'), BuilderHelpers::normalizeType('bool')); $this->assertEquals(new Node\Identifier('iterable'), BuilderHelpers::normalizeType('iterable')); $this->assertEquals(new Node\Identifier('void'), BuilderHelpers::normalizeType('void')); $this->assertEquals(new Node\Identifier('object'), BuilderHelpers::normalizeType('object')); $this->assertEquals(new Node\Identifier('null'), BuilderHelpers::normalizeType('null')); $this->assertEquals(new Node\Identifier('false'), BuilderHelpers::normalizeType('false')); $this->assertEquals(new Node\Identifier('mixed'), BuilderHelpers::normalizeType('mixed')); $this->assertEquals(new Node\Identifier('never'), BuilderHelpers::normalizeType('never')); $this->assertEquals(new Node\Identifier('true'), BuilderHelpers::normalizeType('true')); $intIdentifier = new Node\Identifier('int'); $this->assertSame($intIdentifier, BuilderHelpers::normalizeType($intIdentifier)); $intName = new Node\Name('int'); $this->assertSame($intName, BuilderHelpers::normalizeType($intName)); $intNullable = new Node\NullableType(new Identifier('int')); $this->assertSame($intNullable, BuilderHelpers::normalizeType($intNullable)); $unionType = new Node\UnionType([new Node\Identifier('int'), new Node\Identifier('string')]); $this->assertSame($unionType, BuilderHelpers::normalizeType($unionType)); $intersectionType = new Node\IntersectionType([new Node\Name('A'), new Node\Name('B')]); $this->assertSame($intersectionType, BuilderHelpers::normalizeType($intersectionType)); $expectedNullable = new Node\NullableType($intIdentifier); $nullable = BuilderHelpers::normalizeType('?int'); $this->assertEquals($expectedNullable, $nullable); $this->assertEquals($intIdentifier, $nullable->type); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Type must be a string, or an instance of Name, Identifier or ComplexType'); BuilderHelpers::normalizeType(1); } public function testNormalizeTypeNullableVoid(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('void type cannot be nullable'); BuilderHelpers::normalizeType('?void'); } public function testNormalizeTypeNullableMixed(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('mixed type cannot be nullable'); BuilderHelpers::normalizeType('?mixed'); } public function testNormalizeTypeNullableNever(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('never type cannot be nullable'); BuilderHelpers::normalizeType('?never'); } public function testNormalizeValue(): void { $expression = new Scalar\Int_(1); $this->assertSame($expression, BuilderHelpers::normalizeValue($expression)); $this->assertEquals(new Expr\ConstFetch(new Node\Name('null')), BuilderHelpers::normalizeValue(null)); $this->assertEquals(new Expr\ConstFetch(new Node\Name('true')), BuilderHelpers::normalizeValue(true)); $this->assertEquals(new Expr\ConstFetch(new Node\Name('false')), BuilderHelpers::normalizeValue(false)); $this->assertEquals(new Scalar\Int_(2), BuilderHelpers::normalizeValue(2)); $this->assertEquals(new Scalar\Float_(2.5), BuilderHelpers::normalizeValue(2.5)); $this->assertEquals(new Scalar\String_('text'), BuilderHelpers::normalizeValue('text')); $this->assertEquals( new Expr\Array_([ new Node\ArrayItem(new Scalar\Int_(0)), new Node\ArrayItem(new Scalar\Int_(1), new Scalar\String_('test')), ]), BuilderHelpers::normalizeValue([ 0, 'test' => 1, ]) ); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Invalid value'); BuilderHelpers::normalizeValue(new \stdClass()); } public function testNormalizeDocComment(): void { $docComment = new Comment\Doc('Some doc comment'); $this->assertSame($docComment, BuilderHelpers::normalizeDocComment($docComment)); $this->assertEquals($docComment, BuilderHelpers::normalizeDocComment('Some doc comment')); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Doc comment must be a string or an instance of PhpParser\Comment\Doc'); BuilderHelpers::normalizeDocComment(1); } public function testNormalizeAttribute(): void { $attribute = new Node\Attribute(new Node\Name('Test')); $attributeGroup = new Node\AttributeGroup([$attribute]); $this->assertEquals($attributeGroup, BuilderHelpers::normalizeAttribute($attribute)); $this->assertSame($attributeGroup, BuilderHelpers::normalizeAttribute($attributeGroup)); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Attribute must be an instance of PhpParser\Node\Attribute or PhpParser\Node\AttributeGroup'); BuilderHelpers::normalizeAttribute('test'); } public function testNormalizeValueEnum() { if (\PHP_VERSION_ID <= 80100) { $this->markTestSkipped('Enums are supported since PHP 8.1'); } include __DIR__ . '/../fixtures/Suit.php'; $this->assertEquals(new Expr\ClassConstFetch(new FullyQualified(\Suit::class), new Identifier('Hearts')), BuilderHelpers::normalizeValue(\Suit::Hearts)); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/TokenTest.php
test/PhpParser/TokenTest.php
<?php declare(strict_types=1); namespace PhpParser; class TokenTest extends \PHPUnit\Framework\TestCase { public function testGetTokenName(): void { $token = new Token(\ord(','), ','); $this->assertSame(',', $token->getTokenName()); $token = new Token(\T_WHITESPACE, ' '); $this->assertSame('T_WHITESPACE', $token->getTokenName()); } public function testIs(): void { $token = new Token(\ord(','), ','); $this->assertTrue($token->is(\ord(','))); $this->assertFalse($token->is(\ord(';'))); $this->assertTrue($token->is(',')); $this->assertFalse($token->is(';')); $this->assertTrue($token->is([\ord(','), \ord(';')])); $this->assertFalse($token->is([\ord('!'), \ord(';')])); $this->assertTrue($token->is([',', ';'])); $this->assertFalse($token->is(['!', ';'])); } /** @dataProvider provideTestIsIgnorable */ public function testIsIgnorable(int $id, string $text, bool $isIgnorable): void { $token = new Token($id, $text); $this->assertSame($isIgnorable, $token->isIgnorable()); } public static function provideTestIsIgnorable() { return [ [\T_STRING, 'foo', false], [\T_WHITESPACE, ' ', true], [\T_COMMENT, '// foo', true], [\T_DOC_COMMENT, '/** foo */', true], [\T_OPEN_TAG, '<?php ', true], ]; } public function testToString(): void { $token = new Token(\ord(','), ','); $this->assertSame(',', (string) $token); $token = new Token(\T_STRING, 'foo'); $this->assertSame('foo', (string) $token); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/JsonDecoderTest.php
test/PhpParser/JsonDecoderTest.php
<?php declare(strict_types=1); namespace PhpParser; class JsonDecoderTest extends \PHPUnit\Framework\TestCase { public function testRoundTrip(): void { $code = <<<'PHP' <?php // comment /** doc comment */ function functionName(&$a = 0, $b = 1.0) { echo 'Foo'; } PHP; $parser = new Parser\Php7(new Lexer()); $stmts = $parser->parse($code); $json = json_encode($stmts); $jsonDecoder = new JsonDecoder(); $decodedStmts = $jsonDecoder->decode($json); $this->assertEquals($stmts, $decodedStmts); } /** @dataProvider provideTestDecodingError */ public function testDecodingError($json, $expectedMessage): void { $jsonDecoder = new JsonDecoder(); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage($expectedMessage); $jsonDecoder->decode($json); } public static function provideTestDecodingError() { return [ ['???', 'JSON decoding error: Syntax error'], ['{"nodeType":123}', 'Node type must be a string'], ['{"nodeType":"Name","attributes":123}', 'Attributes must be an array'], ['{"nodeType":"Comment"}', 'Comment must have text'], ['{"nodeType":"xxx"}', 'Unknown node type "xxx"'], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/ParserTestAbstract.php
test/PhpParser/ParserTestAbstract.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; use PhpParser\Node\Scalar; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; abstract class ParserTestAbstract extends \PHPUnit\Framework\TestCase { /** @returns Parser */ abstract protected function getParser(Lexer $lexer); public function testParserThrowsSyntaxError(): void { $this->expectException(Error::class); $this->expectExceptionMessage('Syntax error, unexpected EOF on line 1'); $parser = $this->getParser(new Lexer()); $parser->parse('<?php foo'); } public function testParserThrowsSpecialError(): void { $this->expectException(Error::class); $this->expectExceptionMessage('Cannot use foo as self because \'self\' is a special class name on line 1'); $parser = $this->getParser(new Lexer()); $parser->parse('<?php use foo as self;'); } public function testParserThrowsLexerError(): void { $this->expectException(Error::class); $this->expectExceptionMessage('Unterminated comment on line 1'); $parser = $this->getParser(new Lexer()); $parser->parse('<?php /*'); } public function testAttributeAssignment(): void { $lexer = new Lexer(); $code = <<<'EOC' <?php /** Doc comment */ function test($a) { // Line // Comments echo $a; } EOC; $code = canonicalize($code); $parser = $this->getParser($lexer); $stmts = $parser->parse($code); /** @var Stmt\Function_ $fn */ $fn = $stmts[0]; $this->assertInstanceOf(Stmt\Function_::class, $fn); $this->assertEquals([ 'comments' => [ new Comment\Doc('/** Doc comment */', 2, 6, 1, 2, 23, 1), ], 'startLine' => 3, 'endLine' => 7, 'startTokenPos' => 3, 'endTokenPos' => 21, 'startFilePos' => 25, 'endFilePos' => 86, ], $fn->getAttributes()); $param = $fn->params[0]; $this->assertInstanceOf(Node\Param::class, $param); $this->assertEquals([ 'startLine' => 3, 'endLine' => 3, 'startTokenPos' => 7, 'endTokenPos' => 7, 'startFilePos' => 39, 'endFilePos' => 40, ], $param->getAttributes()); /** @var Stmt\Echo_ $echo */ $echo = $fn->stmts[0]; $this->assertInstanceOf(Stmt\Echo_::class, $echo); $this->assertEquals([ 'comments' => [ new Comment("// Line", 4, 49, 12, 4, 55, 12), new Comment("// Comments", 5, 61, 14, 5, 71, 14), ], 'startLine' => 6, 'endLine' => 6, 'startTokenPos' => 16, 'endTokenPos' => 19, 'startFilePos' => 77, 'endFilePos' => 84, ], $echo->getAttributes()); /** @var \PhpParser\Node\Expr\Variable $var */ $var = $echo->exprs[0]; $this->assertInstanceOf(Expr\Variable::class, $var); $this->assertEquals([ 'startLine' => 6, 'endLine' => 6, 'startTokenPos' => 18, 'endTokenPos' => 18, 'startFilePos' => 82, 'endFilePos' => 83, ], $var->getAttributes()); } public function testInvalidToken(): void { $this->expectException(\RangeException::class); $this->expectExceptionMessage('The lexer returned an invalid token (id=999, value=foobar)'); $lexer = new InvalidTokenLexer(); $parser = $this->getParser($lexer); $parser->parse('dummy'); } /** * @dataProvider provideTestExtraAttributes */ public function testExtraAttributes($code, $expectedAttributes): void { $parser = $this->getParser(new Lexer\Emulative()); $stmts = $parser->parse("<?php $code;"); $node = $stmts[0] instanceof Stmt\Expression ? $stmts[0]->expr : $stmts[0]; $attributes = $node->getAttributes(); foreach ($expectedAttributes as $name => $value) { $this->assertSame($value, $attributes[$name]); } } public static function provideTestExtraAttributes() { return [ ['0', ['kind' => Scalar\Int_::KIND_DEC]], ['9', ['kind' => Scalar\Int_::KIND_DEC]], ['07', ['kind' => Scalar\Int_::KIND_OCT]], ['0xf', ['kind' => Scalar\Int_::KIND_HEX]], ['0XF', ['kind' => Scalar\Int_::KIND_HEX]], ['0b1', ['kind' => Scalar\Int_::KIND_BIN]], ['0B1', ['kind' => Scalar\Int_::KIND_BIN]], ['0o7', ['kind' => Scalar\Int_::KIND_OCT]], ['0O7', ['kind' => Scalar\Int_::KIND_OCT]], ['[]', ['kind' => Expr\Array_::KIND_SHORT]], ['array()', ['kind' => Expr\Array_::KIND_LONG]], ["'foo'", ['kind' => String_::KIND_SINGLE_QUOTED]], ["b'foo'", ['kind' => String_::KIND_SINGLE_QUOTED]], ["B'foo'", ['kind' => String_::KIND_SINGLE_QUOTED]], ['"foo"', ['kind' => String_::KIND_DOUBLE_QUOTED]], ['b"foo"', ['kind' => String_::KIND_DOUBLE_QUOTED]], ['B"foo"', ['kind' => String_::KIND_DOUBLE_QUOTED]], ['"foo$bar"', ['kind' => String_::KIND_DOUBLE_QUOTED]], ['b"foo$bar"', ['kind' => String_::KIND_DOUBLE_QUOTED]], ['B"foo$bar"', ['kind' => String_::KIND_DOUBLE_QUOTED]], ["<<<'STR'\nSTR\n", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["<<<STR\nSTR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["<<<\"STR\"\nSTR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["b<<<'STR'\nSTR\n", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["B<<<'STR'\nSTR\n", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["<<< \t 'STR'\nSTR\n", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["<<<'\xff'\n\xff\n", ['kind' => String_::KIND_NOWDOC, 'docLabel' => "\xff", 'docIndentation' => '']], ["<<<\"STR\"\n\$a\nSTR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["b<<<\"STR\"\n\$a\nSTR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["B<<<\"STR\"\n\$a\nSTR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["<<< \t \"STR\"\n\$a\nSTR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => '']], ["<<<STR\n STR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => ' ']], ["<<<STR\n\tSTR\n", ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR', 'docIndentation' => "\t"]], ["<<<'STR'\n Foo\n STR\n", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR', 'docIndentation' => ' ']], ["die", ['kind' => Expr\Exit_::KIND_DIE]], ["die('done')", ['kind' => Expr\Exit_::KIND_DIE]], ["exit", ['kind' => Expr\Exit_::KIND_EXIT]], ["exit(1)", ['kind' => Expr\Exit_::KIND_EXIT]], ["?>Foo", ['hasLeadingNewline' => false]], ["?>\nFoo", ['hasLeadingNewline' => true]], ["namespace Foo;", ['kind' => Stmt\Namespace_::KIND_SEMICOLON]], ["namespace Foo {}", ['kind' => Stmt\Namespace_::KIND_BRACED]], ["namespace {}", ['kind' => Stmt\Namespace_::KIND_BRACED]], ["(float) 5.0", ['kind' => Expr\Cast\Double::KIND_FLOAT]], ["(double) 5.0", ['kind' => Expr\Cast\Double::KIND_DOUBLE]], ["(real) 5.0", ['kind' => Expr\Cast\Double::KIND_REAL]], [" ( REAL ) 5.0", ['kind' => Expr\Cast\Double::KIND_REAL]], ]; } public function testListKindAttribute(): void { $parser = $this->getParser(new Lexer\Emulative()); $stmts = $parser->parse('<?php list(list($x)) = $y; [[$x]] = $y;'); $this->assertSame($stmts[0]->expr->var->getAttribute('kind'), Expr\List_::KIND_LIST); $this->assertSame($stmts[0]->expr->var->items[0]->value->getAttribute('kind'), Expr\List_::KIND_LIST); $this->assertSame($stmts[1]->expr->var->getAttribute('kind'), Expr\List_::KIND_ARRAY); $this->assertSame($stmts[1]->expr->var->items[0]->value->getAttribute('kind'), Expr\List_::KIND_ARRAY); } public function testGetTokens(): void { $lexer = new Lexer(); $parser = $this->getParser($lexer); $parser->parse('<?php echo "Foo";'); $this->assertEquals([ new Token(\T_OPEN_TAG, '<?php ', 1, 0), new Token(\T_ECHO, 'echo', 1, 6), new Token(\T_WHITESPACE, ' ', 1, 10), new Token(\T_CONSTANT_ENCAPSED_STRING, '"Foo"', 1, 11), new Token(ord(';'), ';', 1, 16), new Token(0, "\0", 1, 17), ], $parser->getTokens()); } } class InvalidTokenLexer extends Lexer { public function tokenize(string $code, ?ErrorHandler $errorHandler = null): array { return [ new Token(999, 'foobar', 42), ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeTraverserTest.php
test/PhpParser/NodeTraverserTest.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt\Else_; use PhpParser\Node\Stmt\If_; class NodeTraverserTest extends \PHPUnit\Framework\TestCase { public function testNonModifying(): void { $str1Node = new String_('Foo'); $str2Node = new String_('Bar'); $echoNode = new Node\Stmt\Echo_([$str1Node, $str2Node]); $stmts = [$echoNode]; $visitor = new NodeVisitorForTesting(); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $this->assertEquals($stmts, $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $echoNode], ['enterNode', $str1Node], ['leaveNode', $str1Node], ['enterNode', $str2Node], ['leaveNode', $str2Node], ['leaveNode', $echoNode], ['afterTraverse', $stmts], ], $visitor->trace); } public function testModifying(): void { $str1Node = new String_('Foo'); $str2Node = new String_('Bar'); $printNode = new Expr\Print_($str1Node); // Visitor 2 performs changes, visitors 1 and 3 observe the changes. $visitor1 = new NodeVisitorForTesting(); $visitor2 = new NodeVisitorForTesting([ ['beforeTraverse', [], [$str1Node]], ['enterNode', $str1Node, $printNode], ['enterNode', $str1Node, $str2Node], ['leaveNode', $str2Node, $str1Node], ['leaveNode', $printNode, $str1Node], ['afterTraverse', [$str1Node], []], ]); $visitor3 = new NodeVisitorForTesting(); $traverser = new NodeTraverser($visitor1, $visitor2, $visitor3); // as all operations are reversed we end where we start $this->assertEquals([], $traverser->traverse([])); $this->assertEquals([ // Sees nodes before changes on entry. ['beforeTraverse', []], ['enterNode', $str1Node], ['enterNode', $str1Node], // Sees nodes after changes on leave. ['leaveNode', $str1Node], ['leaveNode', $str1Node], ['afterTraverse', []], ], $visitor1->trace); $this->assertEquals([ // Sees nodes after changes on entry. ['beforeTraverse', [$str1Node]], ['enterNode', $printNode], ['enterNode', $str2Node], // Sees nodes before changes on leave. ['leaveNode', $str2Node], ['leaveNode', $printNode], ['afterTraverse', [$str1Node]], ], $visitor3->trace); } public function testRemoveFromLeave(): void { $str1Node = new String_('Foo'); $str2Node = new String_('Bar'); $visitor = new NodeVisitorForTesting([ ['leaveNode', $str1Node, NodeVisitor::REMOVE_NODE], ]); $visitor2 = new NodeVisitorForTesting(); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor2); $traverser->addVisitor($visitor); $stmts = [$str1Node, $str2Node]; $this->assertEquals([$str2Node], $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $str1Node], ['enterNode', $str2Node], ['leaveNode', $str2Node], ['afterTraverse', [$str2Node]], ], $visitor2->trace); } public function testRemoveFromEnter(): void { $str1Node = new String_('Foo'); $str2Node = new String_('Bar'); $visitor = new NodeVisitorForTesting([ ['enterNode', $str1Node, NodeVisitor::REMOVE_NODE], ]); $visitor2 = new NodeVisitorForTesting(); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $traverser->addVisitor($visitor2); $stmts = [$str1Node, $str2Node]; $this->assertEquals([$str2Node], $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $str2Node], ['leaveNode', $str2Node], ['afterTraverse', [$str2Node]], ], $visitor2->trace); } public function testReturnArrayFromEnter(): void { $str1Node = new String_('Str1'); $str2Node = new String_('Str2'); $str3Node = new String_('Str3'); $str4Node = new String_('Str4'); $visitor = new NodeVisitorForTesting([ ['enterNode', $str1Node, [$str3Node, $str4Node]], ]); $visitor2 = new NodeVisitorForTesting(); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $traverser->addVisitor($visitor2); $stmts = [$str1Node, $str2Node]; $this->assertEquals([$str3Node, $str4Node, $str2Node], $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $str2Node], ['leaveNode', $str2Node], ['afterTraverse', [$str3Node, $str4Node, $str2Node]], ], $visitor2->trace); } public function testMerge(): void { $strStart = new String_('Start'); $strMiddle = new String_('End'); $strEnd = new String_('Middle'); $strR1 = new String_('Replacement 1'); $strR2 = new String_('Replacement 2'); $visitor = new NodeVisitorForTesting([ ['leaveNode', $strMiddle, [$strR1, $strR2]], ]); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $this->assertEquals( [$strStart, $strR1, $strR2, $strEnd], $traverser->traverse([$strStart, $strMiddle, $strEnd]) ); } public function testInvalidDeepArray(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Invalid node structure: Contains nested arrays'); $strNode = new String_('Foo'); $stmts = [[[$strNode]]]; $traverser = new NodeTraverser(); $this->assertEquals($stmts, $traverser->traverse($stmts)); } public function testDontTraverseChildren(): void { $strNode = new String_('str'); $printNode = new Expr\Print_($strNode); $varNode = new Expr\Variable('foo'); $mulNode = new Expr\BinaryOp\Mul($varNode, $varNode); $negNode = new Expr\UnaryMinus($mulNode); $stmts = [$printNode, $negNode]; $visitor1 = new NodeVisitorForTesting([ ['enterNode', $printNode, NodeVisitor::DONT_TRAVERSE_CHILDREN], ]); $visitor2 = new NodeVisitorForTesting([ ['enterNode', $mulNode, NodeVisitor::DONT_TRAVERSE_CHILDREN], ]); $expectedTrace = [ ['beforeTraverse', $stmts], ['enterNode', $printNode], ['leaveNode', $printNode], ['enterNode', $negNode], ['enterNode', $mulNode], ['leaveNode', $mulNode], ['leaveNode', $negNode], ['afterTraverse', $stmts], ]; $traverser = new NodeTraverser(); $traverser->addVisitor($visitor1); $traverser->addVisitor($visitor2); $this->assertEquals($stmts, $traverser->traverse($stmts)); $this->assertEquals($expectedTrace, $visitor1->trace); $this->assertEquals($expectedTrace, $visitor2->trace); } public function testDontTraverseCurrentAndChildren(): void { // print 'str'; -($foo * $foo); $strNode = new String_('str'); $printNode = new Expr\Print_($strNode); $varNode = new Expr\Variable('foo'); $mulNode = new Expr\BinaryOp\Mul($varNode, $varNode); $divNode = new Expr\BinaryOp\Div($varNode, $varNode); $negNode = new Expr\UnaryMinus($mulNode); $stmts = [$printNode, $negNode]; $visitor1 = new NodeVisitorForTesting([ ['enterNode', $printNode, NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN], ['enterNode', $mulNode, NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN], ['leaveNode', $mulNode, $divNode], ]); $visitor2 = new NodeVisitorForTesting(); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor1); $traverser->addVisitor($visitor2); $resultStmts = $traverser->traverse($stmts); $this->assertInstanceOf(Expr\BinaryOp\Div::class, $resultStmts[1]->expr); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $printNode], ['leaveNode', $printNode], ['enterNode', $negNode], ['enterNode', $mulNode], ['leaveNode', $mulNode], ['leaveNode', $negNode], ['afterTraverse', $resultStmts], ], $visitor1->trace); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $negNode], ['leaveNode', $negNode], ['afterTraverse', $resultStmts], ], $visitor2->trace); } public function testStopTraversal(): void { $varNode1 = new Expr\Variable('a'); $varNode2 = new Expr\Variable('b'); $varNode3 = new Expr\Variable('c'); $mulNode = new Expr\BinaryOp\Mul($varNode1, $varNode2); $printNode = new Expr\Print_($varNode3); $stmts = [$mulNode, $printNode]; // From enterNode() with array parent $visitor = new NodeVisitorForTesting([ ['enterNode', $mulNode, NodeVisitor::STOP_TRAVERSAL], ]); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $this->assertEquals($stmts, $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $mulNode], ['afterTraverse', $stmts], ], $visitor->trace); // From enterNode with Node parent $visitor = new NodeVisitorForTesting([ ['enterNode', $varNode1, NodeVisitor::STOP_TRAVERSAL], ]); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $this->assertEquals($stmts, $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $mulNode], ['enterNode', $varNode1], ['afterTraverse', $stmts], ], $visitor->trace); // From leaveNode with Node parent $visitor = new NodeVisitorForTesting([ ['leaveNode', $varNode1, NodeVisitor::STOP_TRAVERSAL], ]); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $this->assertEquals($stmts, $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $mulNode], ['enterNode', $varNode1], ['leaveNode', $varNode1], ['afterTraverse', $stmts], ], $visitor->trace); // From leaveNode with array parent $visitor = new NodeVisitorForTesting([ ['leaveNode', $mulNode, NodeVisitor::STOP_TRAVERSAL], ]); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $this->assertEquals($stmts, $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $mulNode], ['enterNode', $varNode1], ['leaveNode', $varNode1], ['enterNode', $varNode2], ['leaveNode', $varNode2], ['leaveNode', $mulNode], ['afterTraverse', $stmts], ], $visitor->trace); // Check that pending array modifications are still carried out $visitor = new NodeVisitorForTesting([ ['leaveNode', $mulNode, NodeVisitor::REMOVE_NODE], ['enterNode', $printNode, NodeVisitor::STOP_TRAVERSAL], ]); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $this->assertEquals([$printNode], $traverser->traverse($stmts)); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $mulNode], ['enterNode', $varNode1], ['leaveNode', $varNode1], ['enterNode', $varNode2], ['leaveNode', $varNode2], ['leaveNode', $mulNode], ['enterNode', $printNode], ['afterTraverse', [$printNode]], ], $visitor->trace); } public function testReplaceWithNull(): void { $one = new Int_(1); $else1 = new Else_(); $else2 = new Else_(); $if1 = new If_($one, ['else' => $else1]); $if2 = new If_($one, ['else' => $else2]); $stmts = [$if1, $if2]; $visitor1 = new NodeVisitorForTesting([ ['enterNode', $else1, NodeVisitor::REPLACE_WITH_NULL], ['leaveNode', $else2, NodeVisitor::REPLACE_WITH_NULL], ]); $visitor2 = new NodeVisitorForTesting(); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor1); $traverser->addVisitor($visitor2); $newStmts = $traverser->traverse($stmts); $this->assertEquals([ new If_($one), new If_($one), ], $newStmts); $this->assertEquals([ ['beforeTraverse', $stmts], ['enterNode', $if1], ['enterNode', $one], // We never see the if1 Else node. ['leaveNode', $one], ['leaveNode', $if1], ['enterNode', $if2], ['enterNode', $one], ['leaveNode', $one], // We do see the if2 Else node, as it will only be replaced afterwards. ['enterNode', $else2], ['leaveNode', $else2], ['leaveNode', $if2], ['afterTraverse', $stmts], ], $visitor2->trace); } public function testRemovingVisitor(): void { $visitor1 = new class () extends NodeVisitorAbstract {}; $visitor2 = new class () extends NodeVisitorAbstract {}; $visitor3 = new class () extends NodeVisitorAbstract {}; $traverser = new NodeTraverser(); $traverser->addVisitor($visitor1); $traverser->addVisitor($visitor2); $traverser->addVisitor($visitor3); $getVisitors = (function () { return $this->visitors; })->bindTo($traverser, NodeTraverser::class); $preExpected = [$visitor1, $visitor2, $visitor3]; $this->assertSame($preExpected, $getVisitors()); $traverser->removeVisitor($visitor2); $postExpected = [$visitor1, $visitor3]; $this->assertSame($postExpected, $getVisitors()); } public function testNoCloneNodes(): void { $stmts = [new Node\Stmt\Echo_([new String_('Foo'), new String_('Bar')])]; $traverser = new NodeTraverser(); $this->assertSame($stmts, $traverser->traverse($stmts)); } /** * @dataProvider provideTestInvalidReturn */ public function testInvalidReturn($stmts, $visitor, $message): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage($message); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $traverser->traverse($stmts); } public static function provideTestInvalidReturn() { $num = new Node\Scalar\Int_(42); $expr = new Node\Stmt\Expression($num); $stmts = [$expr]; $visitor1 = new NodeVisitorForTesting([ ['enterNode', $expr, 'foobar'], ]); $visitor2 = new NodeVisitorForTesting([ ['enterNode', $num, 'foobar'], ]); $visitor3 = new NodeVisitorForTesting([ ['leaveNode', $num, 'foobar'], ]); $visitor4 = new NodeVisitorForTesting([ ['leaveNode', $expr, 'foobar'], ]); $visitor5 = new NodeVisitorForTesting([ ['leaveNode', $num, [new Node\Scalar\Float_(42.0)]], ]); $visitor6 = new NodeVisitorForTesting([ ['leaveNode', $expr, false], ]); $visitor7 = new NodeVisitorForTesting([ ['enterNode', $expr, new Node\Scalar\Int_(42)], ]); $visitor8 = new NodeVisitorForTesting([ ['enterNode', $num, new Node\Stmt\Return_()], ]); $visitor9 = new NodeVisitorForTesting([ ['enterNode', $expr, NodeVisitor::REPLACE_WITH_NULL], ]); $visitor10 = new NodeVisitorForTesting([ ['leaveNode', $expr, NodeVisitor::REPLACE_WITH_NULL], ]); return [ [$stmts, $visitor1, 'enterNode() returned invalid value of type string'], [$stmts, $visitor2, 'enterNode() returned invalid value of type string'], [$stmts, $visitor3, 'leaveNode() returned invalid value of type string'], [$stmts, $visitor4, 'leaveNode() returned invalid value of type string'], [$stmts, $visitor5, 'leaveNode() may only return an array if the parent structure is an array'], [$stmts, $visitor6, 'leaveNode() returned invalid value of type bool'], [$stmts, $visitor7, 'Trying to replace statement (Stmt_Expression) with expression (Scalar_Int). Are you missing a Stmt_Expression wrapper?'], [$stmts, $visitor8, 'Trying to replace expression (Scalar_Int) with statement (Stmt_Return)'], [$stmts, $visitor9, 'REPLACE_WITH_NULL can not be used if the parent structure is an array'], [$stmts, $visitor10, 'REPLACE_WITH_NULL can not be used if the parent structure is an array'], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/ModifiersTest.php
test/PhpParser/ModifiersTest.php
<?php declare(strict_types=1); namespace PhpParser; use InvalidArgumentException; use PHPUnit\Framework\TestCase; class ModifiersTest extends TestCase { public function testToString() { $this->assertSame('public', Modifiers::toString(Modifiers::PUBLIC)); } public function testToStringInvalid() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unknown modifier 3'); Modifiers::toString(Modifiers::PUBLIC | Modifiers::PROTECTED); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeVisitorForTesting.php
test/PhpParser/NodeVisitorForTesting.php
<?php declare(strict_types=1); namespace PhpParser; class NodeVisitorForTesting implements NodeVisitor { public $trace = []; private $returns; private $returnsPos; public function __construct(array $returns = []) { $this->returns = $returns; $this->returnsPos = 0; } public function beforeTraverse(array $nodes): ?array { return $this->traceEvent('beforeTraverse', $nodes); } public function enterNode(Node $node) { return $this->traceEvent('enterNode', $node); } public function leaveNode(Node $node) { return $this->traceEvent('leaveNode', $node); } public function afterTraverse(array $nodes): ?array { return $this->traceEvent('afterTraverse', $nodes); } private function traceEvent(string $method, $param) { $this->trace[] = [$method, $param]; if ($this->returnsPos < count($this->returns)) { $currentReturn = $this->returns[$this->returnsPos]; if ($currentReturn[0] === $method && $currentReturn[1] === $param) { $this->returnsPos++; return $currentReturn[2]; } } return null; } public function __destruct() { if ($this->returnsPos !== count($this->returns)) { throw new \Exception("Expected event did not occur"); } } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/MethodTest.php
test/PhpParser/Builder/MethodTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Modifiers; use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Expr\Print_; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; class MethodTest extends \PHPUnit\Framework\TestCase { public function createMethodBuilder($name) { return new Method($name); } public function testModifiers(): void { $node = $this->createMethodBuilder('test') ->makePublic() ->makeAbstract() ->makeStatic() ->getNode() ; $this->assertEquals( new Stmt\ClassMethod('test', [ 'flags' => Modifiers::PUBLIC | Modifiers::ABSTRACT | Modifiers::STATIC, 'stmts' => null, ]), $node ); $node = $this->createMethodBuilder('test') ->makeProtected() ->makeFinal() ->getNode() ; $this->assertEquals( new Stmt\ClassMethod('test', [ 'flags' => Modifiers::PROTECTED | Modifiers::FINAL ]), $node ); $node = $this->createMethodBuilder('test') ->makePrivate() ->getNode() ; $this->assertEquals( new Stmt\ClassMethod('test', [ 'type' => Modifiers::PRIVATE ]), $node ); } public function testReturnByRef(): void { $node = $this->createMethodBuilder('test') ->makeReturnByRef() ->getNode() ; $this->assertEquals( new Stmt\ClassMethod('test', [ 'byRef' => true ]), $node ); } public function testParams(): void { $param1 = new Node\Param(new Variable('test1')); $param2 = new Node\Param(new Variable('test2')); $param3 = new Node\Param(new Variable('test3')); $node = $this->createMethodBuilder('test') ->addParam($param1) ->addParams([$param2, $param3]) ->getNode() ; $this->assertEquals( new Stmt\ClassMethod('test', [ 'params' => [$param1, $param2, $param3] ]), $node ); } public function testStmts(): void { $stmt1 = new Print_(new String_('test1')); $stmt2 = new Print_(new String_('test2')); $stmt3 = new Print_(new String_('test3')); $node = $this->createMethodBuilder('test') ->addStmt($stmt1) ->addStmts([$stmt2, $stmt3]) ->getNode() ; $this->assertEquals( new Stmt\ClassMethod('test', [ 'stmts' => [ new Stmt\Expression($stmt1), new Stmt\Expression($stmt2), new Stmt\Expression($stmt3), ] ]), $node ); } public function testDocComment(): void { $node = $this->createMethodBuilder('test') ->setDocComment('/** Test */') ->getNode(); $this->assertEquals(new Stmt\ClassMethod('test', [], [ 'comments' => [new Comment\Doc('/** Test */')] ]), $node); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createMethodBuilder('attributeGroup') ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals(new Stmt\ClassMethod('attributeGroup', [ 'attrGroups' => [$attributeGroup], ], []), $node); } public function testReturnType(): void { $node = $this->createMethodBuilder('test') ->setReturnType('bool') ->getNode(); $this->assertEquals(new Stmt\ClassMethod('test', [ 'returnType' => new Identifier('bool'), ], []), $node); } public function testAddStmtToAbstractMethodError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot add statements to an abstract method'); $this->createMethodBuilder('test') ->makeAbstract() ->addStmt(new Print_(new String_('test'))) ; } public function testMakeMethodWithStmtsAbstractError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot make method with statements abstract'); $this->createMethodBuilder('test') ->addStmt(new Print_(new String_('test'))) ->makeAbstract() ; } public function testInvalidParamError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected parameter node, got "Name"'); $this->createMethodBuilder('test') ->addParam(new Node\Name('foo')) ; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/EnumTest.php
test/PhpParser/Builder/EnumTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt; class EnumTest extends \PHPUnit\Framework\TestCase { protected function createEnumBuilder($class) { return new Enum_($class); } public function testImplements(): void { $node = $this->createEnumBuilder('SomeEnum') ->implement('Namespaced\SomeInterface', new Name('OtherInterface')) ->getNode() ; $this->assertEquals( new Stmt\Enum_('SomeEnum', [ 'implements' => [ new Name('Namespaced\SomeInterface'), new Name('OtherInterface'), ], ]), $node ); } public function testSetScalarType(): void { $node = $this->createEnumBuilder('Test') ->setScalarType('int') ->getNode() ; $this->assertEquals( new Stmt\Enum_('Test', [ 'scalarType' => new Identifier('int'), ]), $node ); } public function testStatementOrder(): void { $method = new Stmt\ClassMethod('testMethod'); $enumCase = new Stmt\EnumCase( 'TEST_ENUM_CASE' ); $const = new Stmt\ClassConst([ new Node\Const_('TEST_CONST', new Node\Scalar\String_('ABC')) ]); $use = new Stmt\TraitUse([new Name('SomeTrait')]); $node = $this->createEnumBuilder('Test') ->addStmt($method) ->addStmt($enumCase) ->addStmts([$const, $use]) ->getNode() ; $this->assertEquals( new Stmt\Enum_('Test', [ 'stmts' => [$use, $enumCase, $const, $method] ]), $node ); } public function testDocComment(): void { $docComment = <<<'DOC' /** * Test */ DOC; $enum = $this->createEnumBuilder('Test') ->setDocComment($docComment) ->getNode(); $this->assertEquals( new Stmt\Enum_('Test', [], [ 'comments' => [ new Comment\Doc($docComment) ] ]), $enum ); $enum = $this->createEnumBuilder('Test') ->setDocComment(new Comment\Doc($docComment)) ->getNode(); $this->assertEquals( new Stmt\Enum_('Test', [], [ 'comments' => [ new Comment\Doc($docComment) ] ]), $enum ); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $enum = $this->createEnumBuilder('ATTR_GROUP') ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals( new Stmt\Enum_('ATTR_GROUP', [ 'attrGroups' => [ $attributeGroup, ] ], []), $enum ); } public function testInvalidStmtError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Unexpected node of type "PropertyItem"'); $this->createEnumBuilder('Test') ->addStmt(new Node\PropertyItem('property')) ; } public function testInvalidDocComment(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Doc comment must be a string or an instance of PhpParser\Comment\Doc'); $this->createEnumBuilder('Test') ->setDocComment(new Comment('Test')); } public function testEmptyName(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name cannot be empty'); $this->createEnumBuilder('Test') ->implement(''); } public function testInvalidName(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name must be a string or an instance of Node\Name'); $this->createEnumBuilder('Test') ->implement(['Foo']); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/ParamTest.php
test/PhpParser/Builder/ParamTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Modifiers; use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Expr; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar; use PhpParser\Node\Scalar\Int_; class ParamTest extends \PHPUnit\Framework\TestCase { public function createParamBuilder($name) { return new Param($name); } /** * @dataProvider provideTestDefaultValues */ public function testDefaultValues($value, $expectedValueNode): void { $node = $this->createParamBuilder('test') ->setDefault($value) ->getNode() ; $this->assertEquals($expectedValueNode, $node->default); } public static function provideTestDefaultValues() { return [ [ null, new Expr\ConstFetch(new Node\Name('null')) ], [ true, new Expr\ConstFetch(new Node\Name('true')) ], [ false, new Expr\ConstFetch(new Node\Name('false')) ], [ 31415, new Scalar\Int_(31415) ], [ 3.1415, new Scalar\Float_(3.1415) ], [ 'Hallo World', new Scalar\String_('Hallo World') ], [ [1, 2, 3], new Expr\Array_([ new Node\ArrayItem(new Scalar\Int_(1)), new Node\ArrayItem(new Scalar\Int_(2)), new Node\ArrayItem(new Scalar\Int_(3)), ]) ], [ ['foo' => 'bar', 'bar' => 'foo'], new Expr\Array_([ new Node\ArrayItem( new Scalar\String_('bar'), new Scalar\String_('foo') ), new Node\ArrayItem( new Scalar\String_('foo'), new Scalar\String_('bar') ), ]) ], [ new Scalar\MagicConst\Dir(), new Scalar\MagicConst\Dir() ] ]; } /** * @dataProvider provideTestTypes * @dataProvider provideTestNullableTypes * @dataProvider provideTestUnionTypes */ public function testTypes($typeHint, $expectedType): void { $node = $this->createParamBuilder('test') ->setType($typeHint) ->getNode() ; $type = $node->type; /* Manually implement comparison to avoid __toString stupidity */ if ($expectedType instanceof Node\NullableType) { $this->assertInstanceOf(get_class($expectedType), $type); $expectedType = $expectedType->type; $type = $type->type; } $this->assertInstanceOf(get_class($expectedType), $type); $this->assertEquals($expectedType, $type); } public static function provideTestTypes() { return [ ['array', new Node\Identifier('array')], ['callable', new Node\Identifier('callable')], ['bool', new Node\Identifier('bool')], ['int', new Node\Identifier('int')], ['float', new Node\Identifier('float')], ['string', new Node\Identifier('string')], ['iterable', new Node\Identifier('iterable')], ['object', new Node\Identifier('object')], ['Array', new Node\Identifier('array')], ['CALLABLE', new Node\Identifier('callable')], ['mixed', new Node\Identifier('mixed')], ['Some\Class', new Node\Name('Some\Class')], ['\Foo', new Node\Name\FullyQualified('Foo')], ['self', new Node\Name('self')], [new Node\Name('Some\Class'), new Node\Name('Some\Class')], ]; } public static function provideTestNullableTypes() { return [ ['?array', new Node\NullableType(new Node\Identifier('array'))], ['?Some\Class', new Node\NullableType(new Node\Name('Some\Class'))], [ new Node\NullableType(new Node\Identifier('int')), new Node\NullableType(new Node\Identifier('int')) ], [ new Node\NullableType(new Node\Name('Some\Class')), new Node\NullableType(new Node\Name('Some\Class')) ], ]; } public static function provideTestUnionTypes() { return [ [ new Node\UnionType([ new Node\Name('Some\Class'), new Node\Identifier('array'), ]), new Node\UnionType([ new Node\Name('Some\Class'), new Node\Identifier('array'), ]), ], [ new Node\UnionType([ new Node\Identifier('self'), new Node\Identifier('array'), new Node\Name\FullyQualified('Foo') ]), new Node\UnionType([ new Node\Identifier('self'), new Node\Identifier('array'), new Node\Name\FullyQualified('Foo') ]), ], ]; } public function testVoidTypeError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Parameter type cannot be void'); $this->createParamBuilder('test')->setType('void'); } public function testInvalidTypeError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Type must be a string, or an instance of Name, Identifier or ComplexType'); $this->createParamBuilder('test')->setType(new \stdClass()); } public function testByRef(): void { $node = $this->createParamBuilder('test') ->makeByRef() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, true), $node ); } public function testVariadic(): void { $node = $this->createParamBuilder('test') ->makeVariadic() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, false, true), $node ); } public function testMakePublic(): void { $node = $this->createParamBuilder('test') ->makePublic() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, false, false, [], Modifiers::PUBLIC), $node ); } public function testMakeProtected(): void { $node = $this->createParamBuilder('test') ->makeProtected() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, false, false, [], Modifiers::PROTECTED), $node ); $node = $this->createParamBuilder('test') ->makeProtectedSet() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, false, false, [], Modifiers::PROTECTED_SET), $node ); } public function testMakePrivate(): void { $node = $this->createParamBuilder('test') ->makePrivate() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, false, false, [], Modifiers::PRIVATE), $node ); $node = $this->createParamBuilder('test') ->makePrivateSet() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, false, false, [], Modifiers::PRIVATE_SET), $node ); } public function testMakeReadonly(): void { $node = $this->createParamBuilder('test') ->makeReadonly() ->getNode() ; $this->assertEquals( new Node\Param(new Expr\Variable('test'), null, null, false, false, [], Modifiers::READONLY), $node ); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createParamBuilder('attributeGroup') ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals( new Node\Param(new Expr\Variable('attributeGroup'), null, null, false, false, [], 0, [$attributeGroup]), $node ); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/PropertyTest.php
test/PhpParser/Builder/PropertyTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Error; use PhpParser\Modifiers; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Expr; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\PropertyHook; use PhpParser\Node\PropertyItem; use PhpParser\Node\Scalar; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt; class PropertyTest extends \PHPUnit\Framework\TestCase { public function createPropertyBuilder($name) { return new Property($name); } public function testModifiers(): void { $node = $this->createPropertyBuilder('test') ->makePrivate() ->makeStatic() ->getNode() ; $this->assertEquals( new Stmt\Property( Modifiers::PRIVATE | Modifiers::STATIC, [new PropertyItem('test')] ), $node ); $node = $this->createPropertyBuilder('test') ->makeProtected() ->getNode() ; $this->assertEquals( new Stmt\Property( Modifiers::PROTECTED, [new PropertyItem('test')] ), $node ); $node = $this->createPropertyBuilder('test') ->makePublic() ->getNode() ; $this->assertEquals( new Stmt\Property( Modifiers::PUBLIC, [new PropertyItem('test')] ), $node ); $node = $this->createPropertyBuilder('test') ->makeReadonly() ->getNode() ; $this->assertEquals( new Stmt\Property( Modifiers::READONLY, [new PropertyItem('test')] ), $node ); $node = $this->createPropertyBuilder('test') ->makeFinal() ->getNode(); $this->assertEquals( new Stmt\Property(Modifiers::FINAL, [new PropertyItem('test')]), $node); $node = $this->createPropertyBuilder('test') ->makePrivateSet() ->getNode(); $this->assertEquals( new Stmt\Property(Modifiers::PRIVATE_SET, [new PropertyItem('test')]), $node); $node = $this->createPropertyBuilder('test') ->makeProtectedSet() ->getNode(); $this->assertEquals( new Stmt\Property(Modifiers::PROTECTED_SET, [new PropertyItem('test')]), $node); } public function testAbstractWithoutHook() { $this->expectException(Error::class); $this->expectExceptionMessage('Only hooked properties may be declared abstract'); $this->createPropertyBuilder('test')->makeAbstract()->getNode(); } public function testDocComment(): void { $node = $this->createPropertyBuilder('test') ->setDocComment('/** Test */') ->getNode(); $this->assertEquals(new Stmt\Property( Modifiers::PUBLIC, [ new \PhpParser\Node\PropertyItem('test') ], [ 'comments' => [new Comment\Doc('/** Test */')] ] ), $node); } /** * @dataProvider provideTestDefaultValues */ public function testDefaultValues($value, $expectedValueNode): void { $node = $this->createPropertyBuilder('test') ->setDefault($value) ->getNode() ; $this->assertEquals($expectedValueNode, $node->props[0]->default); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createPropertyBuilder('test') ->addAttribute($attributeGroup) ->getNode() ; $this->assertEquals( new Stmt\Property( Modifiers::PUBLIC, [ new \PhpParser\Node\PropertyItem('test') ], [], null, [$attributeGroup] ), $node ); } public function testAddHook(): void { $get = new PropertyHook('get', null); $set = new PropertyHook('set', null); $node = $this->createPropertyBuilder('test') ->addHook($get) ->addHook($set) ->makeAbstract() ->getNode(); $this->assertEquals( new Stmt\Property( Modifiers::ABSTRACT, [new PropertyItem('test')], [], null, [], [$get, $set]), $node); } public static function provideTestDefaultValues() { return [ [ null, new Expr\ConstFetch(new Name('null')) ], [ true, new Expr\ConstFetch(new Name('true')) ], [ false, new Expr\ConstFetch(new Name('false')) ], [ 31415, new Scalar\Int_(31415) ], [ 3.1415, new Scalar\Float_(3.1415) ], [ 'Hallo World', new Scalar\String_('Hallo World') ], [ [1, 2, 3], new Expr\Array_([ new \PhpParser\Node\ArrayItem(new Scalar\Int_(1)), new \PhpParser\Node\ArrayItem(new Scalar\Int_(2)), new \PhpParser\Node\ArrayItem(new Scalar\Int_(3)), ]) ], [ ['foo' => 'bar', 'bar' => 'foo'], new Expr\Array_([ new \PhpParser\Node\ArrayItem( new Scalar\String_('bar'), new Scalar\String_('foo') ), new \PhpParser\Node\ArrayItem( new Scalar\String_('foo'), new Scalar\String_('bar') ), ]) ], [ new Scalar\MagicConst\Dir(), new Scalar\MagicConst\Dir() ] ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/EnumCaseTest.php
test/PhpParser/Builder/EnumCaseTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt; class EnumCaseTest extends \PHPUnit\Framework\TestCase { public function createEnumCaseBuilder($name) { return new EnumCase($name); } public function testDocComment(): void { $node = $this->createEnumCaseBuilder('TEST') ->setDocComment('/** Test */') ->getNode(); $this->assertEquals( new Stmt\EnumCase( "TEST", null, [], [ 'comments' => [new Comment\Doc('/** Test */')] ] ), $node ); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createEnumCaseBuilder('ATTR_GROUP') ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals( new Stmt\EnumCase( "ATTR_GROUP", null, [$attributeGroup] ), $node ); } /** * @dataProvider provideTestDefaultValues */ public function testValues($value, $expectedValueNode): void { $node = $this->createEnumCaseBuilder('TEST') ->setValue($value) ->getNode() ; $this->assertEquals($expectedValueNode, $node->expr); } public static function provideTestDefaultValues() { return [ [ 31415, new Scalar\Int_(31415) ], [ 'Hallo World', new Scalar\String_('Hallo World') ], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/ClassTest.php
test/PhpParser/Builder/ClassTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Modifiers; use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt; class ClassTest extends \PHPUnit\Framework\TestCase { protected function createClassBuilder($class) { return new Class_($class); } public function testExtendsImplements(): void { $node = $this->createClassBuilder('SomeLogger') ->extend('BaseLogger') ->implement('Namespaced\Logger', new Name('SomeInterface')) ->implement('\Fully\Qualified', 'namespace\NamespaceRelative') ->getNode() ; $this->assertEquals( new Stmt\Class_('SomeLogger', [ 'extends' => new Name('BaseLogger'), 'implements' => [ new Name('Namespaced\Logger'), new Name('SomeInterface'), new Name\FullyQualified('Fully\Qualified'), new Name\Relative('NamespaceRelative'), ], ]), $node ); } public function testAbstract(): void { $node = $this->createClassBuilder('Test') ->makeAbstract() ->getNode() ; $this->assertEquals( new Stmt\Class_('Test', [ 'flags' => Modifiers::ABSTRACT ]), $node ); } public function testFinal(): void { $node = $this->createClassBuilder('Test') ->makeFinal() ->getNode() ; $this->assertEquals( new Stmt\Class_('Test', [ 'flags' => Modifiers::FINAL ]), $node ); } public function testReadonly(): void { $node = $this->createClassBuilder('Test') ->makeReadonly() ->getNode() ; $this->assertEquals( new Stmt\Class_('Test', [ 'flags' => Modifiers::READONLY ]), $node ); } public function testStatementOrder(): void { $method = new Stmt\ClassMethod('testMethod'); $property = new Stmt\Property( Modifiers::PUBLIC, [new Node\PropertyItem('testProperty')] ); $const = new Stmt\ClassConst([ new Node\Const_('TEST_CONST', new Node\Scalar\String_('ABC')) ]); $use = new Stmt\TraitUse([new Name('SomeTrait')]); $node = $this->createClassBuilder('Test') ->addStmt($method) ->addStmt($property) ->addStmts([$const, $use]) ->getNode() ; $this->assertEquals( new Stmt\Class_('Test', [ 'stmts' => [$use, $const, $property, $method] ]), $node ); } public function testDocComment(): void { $docComment = <<<'DOC' /** * Test */ DOC; $class = $this->createClassBuilder('Test') ->setDocComment($docComment) ->getNode(); $this->assertEquals( new Stmt\Class_('Test', [], [ 'comments' => [ new Comment\Doc($docComment) ] ]), $class ); $class = $this->createClassBuilder('Test') ->setDocComment(new Comment\Doc($docComment)) ->getNode(); $this->assertEquals( new Stmt\Class_('Test', [], [ 'comments' => [ new Comment\Doc($docComment) ] ]), $class ); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $class = $this->createClassBuilder('ATTR_GROUP') ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals( new Stmt\Class_('ATTR_GROUP', [ 'attrGroups' => [ $attributeGroup, ] ], []), $class ); } public function testInvalidStmtError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Unexpected node of type "Stmt_Echo"'); $this->createClassBuilder('Test') ->addStmt(new Stmt\Echo_([])) ; } public function testInvalidDocComment(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Doc comment must be a string or an instance of PhpParser\Comment\Doc'); $this->createClassBuilder('Test') ->setDocComment(new Comment('Test')); } public function testEmptyName(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name cannot be empty'); $this->createClassBuilder('Test') ->extend(''); } public function testInvalidName(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Name must be a string or an instance of Node\Name'); $this->createClassBuilder('Test') ->extend(['Foo']); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/TraitUseAdaptationTest.php
test/PhpParser/Builder/TraitUseAdaptationTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Modifiers; use PhpParser\Node\Name; use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\Class_; class TraitUseAdaptationTest extends \PHPUnit\Framework\TestCase { protected function createTraitUseAdaptationBuilder($trait, $method) { return new TraitUseAdaptation($trait, $method); } public function testAsMake(): void { $builder = $this->createTraitUseAdaptationBuilder(null, 'foo'); $this->assertEquals( new Stmt\TraitUseAdaptation\Alias(null, 'foo', null, 'bar'), (clone $builder)->as('bar')->getNode() ); $this->assertEquals( new Stmt\TraitUseAdaptation\Alias(null, 'foo', Modifiers::PUBLIC, null), (clone $builder)->makePublic()->getNode() ); $this->assertEquals( new Stmt\TraitUseAdaptation\Alias(null, 'foo', Modifiers::PROTECTED, null), (clone $builder)->makeProtected()->getNode() ); $this->assertEquals( new Stmt\TraitUseAdaptation\Alias(null, 'foo', Modifiers::PRIVATE, null), (clone $builder)->makePrivate()->getNode() ); } public function testInsteadof(): void { $node = $this->createTraitUseAdaptationBuilder('SomeTrait', 'foo') ->insteadof('AnotherTrait') ->getNode() ; $this->assertEquals( new Stmt\TraitUseAdaptation\Precedence( new Name('SomeTrait'), 'foo', [new Name('AnotherTrait')] ), $node ); } public function testAsOnNotAlias(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot set alias for not alias adaptation buider'); $this->createTraitUseAdaptationBuilder('Test', 'foo') ->insteadof('AnotherTrait') ->as('bar') ; } public function testInsteadofOnNotPrecedence(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot add overwritten traits for not precedence adaptation buider'); $this->createTraitUseAdaptationBuilder('Test', 'foo') ->as('bar') ->insteadof('AnotherTrait') ; } public function testInsteadofWithoutTrait(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Precedence adaptation must have trait'); $this->createTraitUseAdaptationBuilder(null, 'foo') ->insteadof('AnotherTrait') ; } public function testMakeOnNotAlias(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot set access modifier for not alias adaptation buider'); $this->createTraitUseAdaptationBuilder('Test', 'foo') ->insteadof('AnotherTrait') ->makePublic() ; } public function testMultipleMake(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Multiple access type modifiers are not allowed'); $this->createTraitUseAdaptationBuilder(null, 'foo') ->makePrivate() ->makePublic() ; } public function testUndefinedType(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Type of adaptation is not defined'); $this->createTraitUseAdaptationBuilder(null, 'foo') ->getNode() ; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/ClassConstTest.php
test/PhpParser/Builder/ClassConstTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Modifiers; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Const_; use PhpParser\Node\Expr; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt; class ClassConstTest extends \PHPUnit\Framework\TestCase { public function createClassConstBuilder($name, $value) { return new ClassConst($name, $value); } public function testModifiers(): void { $node = $this->createClassConstBuilder("TEST", 1) ->makePrivate() ->getNode() ; $this->assertEquals( new Stmt\ClassConst( [ new Const_("TEST", new Int_(1)) ], Modifiers::PRIVATE ), $node ); $node = $this->createClassConstBuilder("TEST", 1) ->makeProtected() ->getNode() ; $this->assertEquals( new Stmt\ClassConst( [ new Const_("TEST", new Int_(1)) ], Modifiers::PROTECTED ), $node ); $node = $this->createClassConstBuilder("TEST", 1) ->makePublic() ->getNode() ; $this->assertEquals( new Stmt\ClassConst( [ new Const_("TEST", new Int_(1)) ], Modifiers::PUBLIC ), $node ); $node = $this->createClassConstBuilder("TEST", 1) ->makeFinal() ->getNode() ; $this->assertEquals( new Stmt\ClassConst( [ new Const_("TEST", new Int_(1)) ], Modifiers::FINAL ), $node ); } public function testDocComment(): void { $node = $this->createClassConstBuilder('TEST', 1) ->setDocComment('/** Test */') ->makePublic() ->getNode(); $this->assertEquals( new Stmt\ClassConst( [ new Const_("TEST", new Int_(1)) ], Modifiers::PUBLIC, [ 'comments' => [new Comment\Doc('/** Test */')] ] ), $node ); } public function testAddConst(): void { $node = $this->createClassConstBuilder('FIRST_TEST', 1) ->addConst("SECOND_TEST", 2) ->getNode(); $this->assertEquals( new Stmt\ClassConst( [ new Const_("FIRST_TEST", new Int_(1)), new Const_("SECOND_TEST", new Int_(2)) ] ), $node ); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createClassConstBuilder('ATTR_GROUP', 1) ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals( new Stmt\ClassConst( [ new Const_("ATTR_GROUP", new Int_(1)) ], 0, [], [$attributeGroup] ), $node ); } public function testType(): void { $node = $this->createClassConstBuilder('TYPE', 1) ->setType('int') ->getNode(); $this->assertEquals( new Stmt\ClassConst( [new Const_('TYPE', new Int_(1))], 0, [], [], new Identifier('int')), $node ); } /** * @dataProvider provideTestDefaultValues */ public function testValues($value, $expectedValueNode): void { $node = $this->createClassConstBuilder('TEST', $value) ->getNode() ; $this->assertEquals($expectedValueNode, $node->consts[0]->value); } public static function provideTestDefaultValues() { return [ [ null, new Expr\ConstFetch(new Name('null')) ], [ true, new Expr\ConstFetch(new Name('true')) ], [ false, new Expr\ConstFetch(new Name('false')) ], [ 31415, new Scalar\Int_(31415) ], [ 3.1415, new Scalar\Float_(3.1415) ], [ 'Hallo World', new Scalar\String_('Hallo World') ], [ [1, 2, 3], new Expr\Array_([ new \PhpParser\Node\ArrayItem(new Scalar\Int_(1)), new \PhpParser\Node\ArrayItem(new Scalar\Int_(2)), new \PhpParser\Node\ArrayItem(new Scalar\Int_(3)), ]) ], [ ['foo' => 'bar', 'bar' => 'foo'], new Expr\Array_([ new \PhpParser\Node\ArrayItem( new Scalar\String_('bar'), new Scalar\String_('foo') ), new \PhpParser\Node\ArrayItem( new Scalar\String_('foo'), new Scalar\String_('bar') ), ]) ], [ new Scalar\MagicConst\Dir(), new Scalar\MagicConst\Dir() ] ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/TraitUseTest.php
test/PhpParser/Builder/TraitUseTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Node\Name; use PhpParser\Node\Stmt; class TraitUseTest extends \PHPUnit\Framework\TestCase { protected function createTraitUseBuilder(...$traits) { return new TraitUse(...$traits); } public function testAnd(): void { $node = $this->createTraitUseBuilder('SomeTrait') ->and('AnotherTrait') ->getNode() ; $this->assertEquals( new Stmt\TraitUse([ new Name('SomeTrait'), new Name('AnotherTrait') ]), $node ); } public function testWith(): void { $node = $this->createTraitUseBuilder('SomeTrait') ->with(new Stmt\TraitUseAdaptation\Alias(null, 'foo', null, 'bar')) ->with((new TraitUseAdaptation(null, 'test'))->as('baz')) ->getNode() ; $this->assertEquals( new Stmt\TraitUse([new Name('SomeTrait')], [ new Stmt\TraitUseAdaptation\Alias(null, 'foo', null, 'bar'), new Stmt\TraitUseAdaptation\Alias(null, 'test', null, 'baz') ]), $node ); } public function testInvalidAdaptationNode(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Adaptation must have type TraitUseAdaptation'); $this->createTraitUseBuilder('Test') ->with(new Stmt\Echo_([])) ; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/NamespaceTest.php
test/PhpParser/Builder/NamespaceTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment\Doc; use PhpParser\Node; use PhpParser\Node\Stmt; class NamespaceTest extends \PHPUnit\Framework\TestCase { protected function createNamespaceBuilder($fqn) { return new Namespace_($fqn); } public function testCreation(): void { $stmt1 = new Stmt\Class_('SomeClass'); $stmt2 = new Stmt\Interface_('SomeInterface'); $stmt3 = new Stmt\Function_('someFunction'); $docComment = new Doc('/** Test */'); $expected = new Stmt\Namespace_( new Node\Name('Name\Space'), [$stmt1, $stmt2, $stmt3], ['comments' => [$docComment]] ); $node = $this->createNamespaceBuilder('Name\Space') ->addStmt($stmt1) ->addStmts([$stmt2, $stmt3]) ->setDocComment($docComment) ->getNode() ; $this->assertEquals($expected, $node); $node = $this->createNamespaceBuilder(new Node\Name(['Name', 'Space'])) ->setDocComment($docComment) ->addStmts([$stmt1, $stmt2]) ->addStmt($stmt3) ->getNode() ; $this->assertEquals($expected, $node); $node = $this->createNamespaceBuilder(null)->getNode(); $this->assertNull($node->name); $this->assertEmpty($node->stmts); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/FunctionTest.php
test/PhpParser/Builder/FunctionTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Expr\Print_; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; class FunctionTest extends \PHPUnit\Framework\TestCase { public function createFunctionBuilder($name) { return new Function_($name); } public function testReturnByRef(): void { $node = $this->createFunctionBuilder('test') ->makeReturnByRef() ->getNode() ; $this->assertEquals( new Stmt\Function_('test', [ 'byRef' => true ]), $node ); } public function testParams(): void { $param1 = new Node\Param(new Variable('test1')); $param2 = new Node\Param(new Variable('test2')); $param3 = new Node\Param(new Variable('test3')); $node = $this->createFunctionBuilder('test') ->addParam($param1) ->addParams([$param2, $param3]) ->getNode() ; $this->assertEquals( new Stmt\Function_('test', [ 'params' => [$param1, $param2, $param3] ]), $node ); } public function testStmts(): void { $stmt1 = new Print_(new String_('test1')); $stmt2 = new Print_(new String_('test2')); $stmt3 = new Print_(new String_('test3')); $node = $this->createFunctionBuilder('test') ->addStmt($stmt1) ->addStmts([$stmt2, $stmt3]) ->getNode() ; $this->assertEquals( new Stmt\Function_('test', [ 'stmts' => [ new Stmt\Expression($stmt1), new Stmt\Expression($stmt2), new Stmt\Expression($stmt3), ] ]), $node ); } public function testDocComment(): void { $node = $this->createFunctionBuilder('test') ->setDocComment('/** Test */') ->getNode(); $this->assertEquals(new Stmt\Function_('test', [], [ 'comments' => [new Comment\Doc('/** Test */')] ]), $node); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createFunctionBuilder('attrGroup') ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals(new Stmt\Function_('attrGroup', [ 'attrGroups' => [$attributeGroup], ], []), $node); } public function testReturnType(): void { $node = $this->createFunctionBuilder('test') ->setReturnType('void') ->getNode(); $this->assertEquals(new Stmt\Function_('test', [ 'returnType' => new Identifier('void'), ], []), $node); } public function testInvalidNullableVoidType(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('void type cannot be nullable'); $this->createFunctionBuilder('test')->setReturnType('?void'); } public function testInvalidParamError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected parameter node, got "Name"'); $this->createFunctionBuilder('test') ->addParam(new Node\Name('foo')) ; } public function testAddNonStmt(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected statement or expression node'); $this->createFunctionBuilder('test') ->addStmt(new Node\Name('Test')); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/UseTest.php
test/PhpParser/Builder/UseTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Builder; use PhpParser\Node\Name; use PhpParser\Node\Stmt; class UseTest extends \PHPUnit\Framework\TestCase { protected function createUseBuilder($name, $type = Stmt\Use_::TYPE_NORMAL) { return new Builder\Use_($name, $type); } public function testCreation(): void { $node = $this->createUseBuilder('Foo\Bar')->getNode(); $this->assertEquals(new Stmt\Use_([ new \PhpParser\Node\UseItem(new Name('Foo\Bar'), null) ]), $node); $node = $this->createUseBuilder(new Name('Foo\Bar'))->as('XYZ')->getNode(); $this->assertEquals(new Stmt\Use_([ new \PhpParser\Node\UseItem(new Name('Foo\Bar'), 'XYZ') ]), $node); $node = $this->createUseBuilder('foo\bar', Stmt\Use_::TYPE_FUNCTION)->as('foo')->getNode(); $this->assertEquals(new Stmt\Use_([ new \PhpParser\Node\UseItem(new Name('foo\bar'), 'foo') ], Stmt\Use_::TYPE_FUNCTION), $node); $node = $this->createUseBuilder('foo\BAR', Stmt\Use_::TYPE_CONSTANT)->as('FOO')->getNode(); $this->assertEquals(new Stmt\Use_([ new \PhpParser\Node\UseItem(new Name('foo\BAR'), 'FOO') ], Stmt\Use_::TYPE_CONSTANT), $node); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/InterfaceTest.php
test/PhpParser/Builder/InterfaceTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Float_; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt; class InterfaceTest extends \PHPUnit\Framework\TestCase { protected function createInterfaceBuilder() { return new Interface_('Contract'); } private function dump($node) { $pp = new \PhpParser\PrettyPrinter\Standard(); return $pp->prettyPrint([$node]); } public function testEmpty(): void { $contract = $this->createInterfaceBuilder()->getNode(); $this->assertInstanceOf(Stmt\Interface_::class, $contract); $this->assertEquals(new Node\Identifier('Contract'), $contract->name); } public function testExtending(): void { $contract = $this->createInterfaceBuilder() ->extend('Space\Root1', 'Root2')->getNode(); $this->assertEquals( new Stmt\Interface_('Contract', [ 'extends' => [ new Node\Name('Space\Root1'), new Node\Name('Root2') ], ]), $contract ); } public function testAddMethod(): void { $method = new Stmt\ClassMethod('doSomething'); $contract = $this->createInterfaceBuilder()->addStmt($method)->getNode(); $this->assertSame([$method], $contract->stmts); } public function testAddConst(): void { $const = new Stmt\ClassConst([ new Node\Const_('SPEED_OF_LIGHT', new Float_(299792458.0)) ]); $contract = $this->createInterfaceBuilder()->addStmt($const)->getNode(); $this->assertSame(299792458.0, $contract->stmts[0]->consts[0]->value->value); } public function testOrder(): void { $const = new Stmt\ClassConst([ new Node\Const_('SPEED_OF_LIGHT', new Float_(299792458)) ]); $method = new Stmt\ClassMethod('doSomething'); $contract = $this->createInterfaceBuilder() ->addStmt($method) ->addStmt($const) ->getNode() ; $this->assertInstanceOf(Stmt\ClassConst::class, $contract->stmts[0]); $this->assertInstanceOf(Stmt\ClassMethod::class, $contract->stmts[1]); } public function testDocComment(): void { $node = $this->createInterfaceBuilder() ->setDocComment('/** Test */') ->getNode(); $this->assertEquals(new Stmt\Interface_('Contract', [], [ 'comments' => [new Comment\Doc('/** Test */')] ]), $node); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createInterfaceBuilder() ->addAttribute($attributeGroup) ->getNode(); $this->assertEquals(new Stmt\Interface_('Contract', [ 'attrGroups' => [$attributeGroup], ], []), $node); } public function testInvalidStmtError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Unexpected node of type "PropertyItem"'); $this->createInterfaceBuilder()->addStmt(new Node\PropertyItem('invalid')); } public function testFullFunctional(): void { $const = new Stmt\ClassConst([ new Node\Const_('SPEED_OF_LIGHT', new Float_(299792458)) ]); $method = new Stmt\ClassMethod('doSomething'); $contract = $this->createInterfaceBuilder() ->addStmt($method) ->addStmt($const) ->getNode() ; eval($this->dump($contract)); $this->assertTrue(interface_exists('Contract', false)); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Builder/TraitTest.php
test/PhpParser/Builder/TraitTest.php
<?php declare(strict_types=1); namespace PhpParser\Builder; use PhpParser\Comment; use PhpParser\Modifiers; use PhpParser\Node\Arg; use PhpParser\Node\Attribute; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Const_; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\ClassConst; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Property; use PhpParser\Node\PropertyItem; use PhpParser\Node\Stmt\TraitUse; class TraitTest extends \PHPUnit\Framework\TestCase { protected function createTraitBuilder($class) { return new Trait_($class); } public function testStmtAddition(): void { $method1 = new Stmt\ClassMethod('test1'); $method2 = new Stmt\ClassMethod('test2'); $method3 = new Stmt\ClassMethod('test3'); $prop = new Stmt\Property(Modifiers::PUBLIC, [ new PropertyItem('test') ]); $const = new ClassConst([new Const_('FOO', new Int_(0))]); $use = new Stmt\TraitUse([new Name('OtherTrait')]); $trait = $this->createTraitBuilder('TestTrait') ->setDocComment('/** Nice trait */') ->addStmt($method1) ->addStmts([$method2, $method3]) ->addStmt($prop) ->addStmt($use) ->addStmt($const) ->getNode(); $this->assertEquals(new Stmt\Trait_('TestTrait', [ 'stmts' => [$use, $const, $prop, $method1, $method2, $method3] ], [ 'comments' => [ new Comment\Doc('/** Nice trait */') ] ]), $trait); } public function testInvalidStmtError(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Unexpected node of type "Stmt_Echo"'); $this->createTraitBuilder('Test') ->addStmt(new Stmt\Echo_([])) ; } public function testGetMethods(): void { $methods = [ new ClassMethod('foo'), new ClassMethod('bar'), new ClassMethod('fooBar'), ]; $trait = new Stmt\Trait_('Foo', [ 'stmts' => [ new TraitUse([]), $methods[0], new ClassConst([]), $methods[1], new Property(0, []), $methods[2], ] ]); $this->assertSame($methods, $trait->getMethods()); } public function testGetProperties(): void { $properties = [ new Property(Modifiers::PUBLIC, [new PropertyItem('foo')]), new Property(Modifiers::PUBLIC, [new PropertyItem('bar')]), ]; $trait = new Stmt\Trait_('Foo', [ 'stmts' => [ new TraitUse([]), $properties[0], new ClassConst([]), $properties[1], new ClassMethod('fooBar'), ] ]); $this->assertSame($properties, $trait->getProperties()); } public function testAddAttribute(): void { $attribute = new Attribute( new Name('Attr'), [new Arg(new Int_(1), false, false, [], new Identifier('name'))] ); $attributeGroup = new AttributeGroup([$attribute]); $node = $this->createTraitBuilder('AttributeGroup') ->addAttribute($attributeGroup) ->getNode() ; $this->assertEquals( new Stmt\Trait_( 'AttributeGroup', [ 'attrGroups' => [$attributeGroup], ] ), $node ); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Lexer/EmulativeTest.php
test/PhpParser/Lexer/EmulativeTest.php
<?php declare(strict_types=1); namespace PhpParser\Lexer; use PhpParser\ErrorHandler; use PhpParser\Lexer; use PhpParser\LexerTest; use PhpParser\Parser\Php7; use PhpParser\PhpVersion; use PhpParser\Token; require __DIR__ . '/../../../lib/PhpParser/compatibility_tokens.php'; class EmulativeTest extends LexerTest { protected function getLexer() { return new Emulative(); } /** * @dataProvider provideTestReplaceKeywords */ public function testReplaceKeywords(string $keyword, int $expectedToken): void { $lexer = $this->getLexer(); $code = '<?php ' . $keyword; $this->assertEquals([ new Token(\T_OPEN_TAG, '<?php ', 1, 0), new Token($expectedToken, $keyword, 1, 6), new Token(0, "\0", 1, \strlen($code)), ], $lexer->tokenize($code)); } /** * @dataProvider provideTestReplaceKeywords */ public function testReplaceKeywordsUppercase(string $keyword, int $expectedToken): void { $lexer = $this->getLexer(); $code = '<?php ' . strtoupper($keyword); $this->assertEquals([ new Token(\T_OPEN_TAG, '<?php ', 1, 0), new Token($expectedToken, \strtoupper($keyword), 1, 6), new Token(0, "\0", 1, \strlen($code)), ], $lexer->tokenize($code)); } /** * @dataProvider provideTestReplaceKeywords */ public function testNoReplaceKeywordsAfterObjectOperator(string $keyword): void { $lexer = $this->getLexer(); $code = '<?php ->' . $keyword; $this->assertEquals([ new Token(\T_OPEN_TAG, '<?php ', 1, 0), new Token(\T_OBJECT_OPERATOR, '->', 1, 6), new Token(\T_STRING, $keyword, 1, 8), new Token(0, "\0", 1, \strlen($code)), ], $lexer->tokenize($code)); } /** * @dataProvider provideTestReplaceKeywords */ public function testNoReplaceKeywordsAfterObjectOperatorWithSpaces(string $keyword): void { $lexer = $this->getLexer(); $code = '<?php -> ' . $keyword; $this->assertEquals([ new Token(\T_OPEN_TAG, '<?php ', 1, 0), new Token(\T_OBJECT_OPERATOR, '->', 1, 6), new Token(\T_WHITESPACE, ' ', 1, 8), new Token(\T_STRING, $keyword, 1, 12), new Token(0, "\0", 1, \strlen($code)), ], $lexer->tokenize($code)); } /** * @dataProvider provideTestReplaceKeywords */ public function testNoReplaceKeywordsAfterNullsafeObjectOperator(string $keyword): void { $lexer = $this->getLexer(); $code = '<?php ?->' . $keyword; $this->assertEquals([ new Token(\T_OPEN_TAG, '<?php ', 1, 0), new Token(\T_NULLSAFE_OBJECT_OPERATOR, '?->', 1, 6), new Token(\T_STRING, $keyword, 1, 9), new Token(0, "\0", 1, \strlen($code)), ], $lexer->tokenize($code)); } public static function provideTestReplaceKeywords() { return [ // PHP 8.4 ['__PROPERTY__', \T_PROPERTY_C], // PHP 8.0 ['match', \T_MATCH], // PHP 7.4 ['fn', \T_FN], // PHP 5.5 ['finally', \T_FINALLY], ['yield', \T_YIELD], // PHP 5.4 ['callable', \T_CALLABLE], ['insteadof', \T_INSTEADOF], ['trait', \T_TRAIT], ['__TRAIT__', \T_TRAIT_C], // PHP 5.3 ['__DIR__', \T_DIR], ['goto', \T_GOTO], ['namespace', \T_NAMESPACE], ['__NAMESPACE__', \T_NS_C], ]; } private function assertSameTokens(array $expectedTokens, array $tokens): void { $reducedTokens = []; foreach ($tokens as $token) { if ($token->id === 0 || $token->isIgnorable()) { continue; } $reducedTokens[] = [$token->id, $token->text]; } $this->assertSame($expectedTokens, $reducedTokens); } /** * @dataProvider provideTestLexNewFeatures */ public function testLexNewFeatures(string $code, array $expectedTokens): void { $lexer = $this->getLexer(); $this->assertSameTokens($expectedTokens, $lexer->tokenize('<?php ' . $code)); } /** * @dataProvider provideTestLexNewFeatures */ public function testLeaveStuffAloneInStrings(string $code): void { $stringifiedToken = '"' . addcslashes($code, '"\\') . '"'; $lexer = $this->getLexer(); $fullCode = '<?php ' . $stringifiedToken; $this->assertEquals([ new Token(\T_OPEN_TAG, '<?php ', 1, 0), new Token(\T_CONSTANT_ENCAPSED_STRING, $stringifiedToken, 1, 6), new Token(0, "\0", \substr_count($fullCode, "\n") + 1, \strlen($fullCode)), ], $lexer->tokenize($fullCode)); } /** * @dataProvider provideTestLexNewFeatures */ public function testErrorAfterEmulation($code): void { $errorHandler = new ErrorHandler\Collecting(); $lexer = $this->getLexer(); $lexer->tokenize('<?php ' . $code . "\0", $errorHandler); $errors = $errorHandler->getErrors(); $this->assertCount(1, $errors); $error = $errors[0]; $this->assertSame('Unexpected null byte', $error->getRawMessage()); $attrs = $error->getAttributes(); $expPos = strlen('<?php ' . $code); $expLine = 1 + substr_count('<?php ' . $code, "\n"); $this->assertSame($expPos, $attrs['startFilePos']); $this->assertSame($expPos, $attrs['endFilePos']); $this->assertSame($expLine, $attrs['startLine']); $this->assertSame($expLine, $attrs['endLine']); } public static function provideTestLexNewFeatures() { return [ ['yield from', [ [\T_YIELD_FROM, 'yield from'], ]], ["yield\r\nfrom", [ [\T_YIELD_FROM, "yield\r\nfrom"], ]], ['...', [ [\T_ELLIPSIS, '...'], ]], ['**', [ [\T_POW, '**'], ]], ['**=', [ [\T_POW_EQUAL, '**='], ]], ['??', [ [\T_COALESCE, '??'], ]], ['<=>', [ [\T_SPACESHIP, '<=>'], ]], ['0b1010110', [ [\T_LNUMBER, '0b1010110'], ]], ['0b1011010101001010110101010010101011010101010101101011001110111100', [ [\T_DNUMBER, '0b1011010101001010110101010010101011010101010101101011001110111100'], ]], ['\\', [ [\T_NS_SEPARATOR, '\\'], ]], ["<<<'NOWDOC'\nNOWDOC;\n", [ [\T_START_HEREDOC, "<<<'NOWDOC'\n"], [\T_END_HEREDOC, 'NOWDOC'], [ord(';'), ';'], ]], ["<<<'NOWDOC'\nFoobar\nNOWDOC;\n", [ [\T_START_HEREDOC, "<<<'NOWDOC'\n"], [\T_ENCAPSED_AND_WHITESPACE, "Foobar\n"], [\T_END_HEREDOC, 'NOWDOC'], [ord(';'), ';'], ]], // PHP 7.3: Flexible heredoc/nowdoc ["<<<LABEL\nLABEL,", [ [\T_START_HEREDOC, "<<<LABEL\n"], [\T_END_HEREDOC, "LABEL"], [ord(','), ','], ]], ["<<<LABEL\n LABEL,", [ [\T_START_HEREDOC, "<<<LABEL\n"], [\T_END_HEREDOC, " LABEL"], [ord(','), ','], ]], ["<<<LABEL\n Foo\n LABEL;", [ [\T_START_HEREDOC, "<<<LABEL\n"], [\T_ENCAPSED_AND_WHITESPACE, " Foo\n"], [\T_END_HEREDOC, " LABEL"], [ord(';'), ';'], ]], ["<<<A\n A,<<<A\n A,", [ [\T_START_HEREDOC, "<<<A\n"], [\T_END_HEREDOC, " A"], [ord(','), ','], [\T_START_HEREDOC, "<<<A\n"], [\T_END_HEREDOC, " A"], [ord(','), ','], ]], ["<<<LABEL\nLABELNOPE\nLABEL\n", [ [\T_START_HEREDOC, "<<<LABEL\n"], [\T_ENCAPSED_AND_WHITESPACE, "LABELNOPE\n"], [\T_END_HEREDOC, "LABEL"], ]], // Interpretation changed ["<<<LABEL\n LABEL\nLABEL\n", [ [\T_START_HEREDOC, "<<<LABEL\n"], [\T_END_HEREDOC, " LABEL"], [\T_STRING, "LABEL"], ]], // PHP 7.4: Null coalesce equal ['??=', [ [\T_COALESCE_EQUAL, '??='], ]], // PHP 7.4: Number literal separator ['1_000', [ [\T_LNUMBER, '1_000'], ]], ['0x7AFE_F00D', [ [\T_LNUMBER, '0x7AFE_F00D'], ]], ['0b0101_1111', [ [\T_LNUMBER, '0b0101_1111'], ]], ['0137_041', [ [\T_LNUMBER, '0137_041'], ]], ['1_000.0', [ [\T_DNUMBER, '1_000.0'], ]], ['1_0.0', [ [\T_DNUMBER, '1_0.0'] ]], ['1_000_000_000.0', [ [\T_DNUMBER, '1_000_000_000.0'] ]], ['0e1_0', [ [\T_DNUMBER, '0e1_0'] ]], ['1_0e+10', [ [\T_DNUMBER, '1_0e+10'] ]], ['1_0e-10', [ [\T_DNUMBER, '1_0e-10'] ]], ['0b1011010101001010_110101010010_10101101010101_0101101011001_110111100', [ [\T_DNUMBER, '0b1011010101001010_110101010010_10101101010101_0101101011001_110111100'], ]], ['0xFFFF_FFFF_FFFF_FFFF', [ [\T_DNUMBER, '0xFFFF_FFFF_FFFF_FFFF'], ]], ['1_000+1', [ [\T_LNUMBER, '1_000'], [ord('+'), '+'], [\T_LNUMBER, '1'], ]], ['1_0abc', [ [\T_LNUMBER, '1_0'], [\T_STRING, 'abc'], ]], ['?->', [ [\T_NULLSAFE_OBJECT_OPERATOR, '?->'], ]], ['#[Attr]', [ [\T_ATTRIBUTE, '#['], [\T_STRING, 'Attr'], [ord(']'), ']'], ]], ["#[\nAttr\n]", [ [\T_ATTRIBUTE, '#['], [\T_STRING, 'Attr'], [ord(']'), ']'], ]], // Test interaction of two patch-based emulators ["<<<LABEL\n LABEL, #[Attr]", [ [\T_START_HEREDOC, "<<<LABEL\n"], [\T_END_HEREDOC, " LABEL"], [ord(','), ','], [\T_ATTRIBUTE, '#['], [\T_STRING, 'Attr'], [ord(']'), ']'], ]], ["#[Attr] <<<LABEL\n LABEL,", [ [\T_ATTRIBUTE, '#['], [\T_STRING, 'Attr'], [ord(']'), ']'], [\T_START_HEREDOC, "<<<LABEL\n"], [\T_END_HEREDOC, " LABEL"], [ord(','), ','], ]], // Enums use a contextual keyword ['enum Foo {}', [ [\T_ENUM, 'enum'], [\T_STRING, 'Foo'], [ord('{'), '{'], [ord('}'), '}'], ]], ['class Enum {}', [ [\T_CLASS, 'class'], [\T_STRING, 'Enum'], [ord('{'), '{'], [ord('}'), '}'], ]], ['class Enum extends X {}', [ [\T_CLASS, 'class'], [\T_STRING, 'Enum'], [\T_EXTENDS, 'extends'], [\T_STRING, 'X'], [ord('{'), '{'], [ord('}'), '}'], ]], ['class Enum implements X {}', [ [\T_CLASS, 'class'], [\T_STRING, 'Enum'], [\T_IMPLEMENTS, 'implements'], [\T_STRING, 'X'], [ord('{'), '{'], [ord('}'), '}'], ]], ['0o123', [ [\T_LNUMBER, '0o123'], ]], ['0O123', [ [\T_LNUMBER, '0O123'], ]], ['0o1_2_3', [ [\T_LNUMBER, '0o1_2_3'], ]], ['0o1000000000000000000000', [ [\T_DNUMBER, '0o1000000000000000000000'], ]], ['readonly class', [ [\T_READONLY, 'readonly'], [\T_CLASS, 'class'], ]], ['function readonly(', [ [\T_FUNCTION, 'function'], [\T_READONLY, 'readonly'], [ord('('), '('], ]], ['function readonly (', [ [\T_FUNCTION, 'function'], [\T_READONLY, 'readonly'], [ord('('), '('], ]], // PHP 8.4: Asymmetric visibility modifiers ['private(set)', [ [\T_PRIVATE_SET, 'private(set)'] ]], ['PROTECTED(SET)', [ [\T_PROTECTED_SET, 'PROTECTED(SET)'] ]], ['Public(Set)', [ [\T_PUBLIC_SET, 'Public(Set)'] ]], ['public (set)', [ [\T_PUBLIC, 'public'], [\ord('('), '('], [\T_STRING, 'set'], [\ord(')'), ')'], ]], ['->public(set)', [ [\T_OBJECT_OPERATOR, '->'], [\T_STRING, 'public'], [\ord('('), '('], [\T_STRING, 'set'], [\ord(')'), ')'], ]], ['?-> public(set)', [ [\T_NULLSAFE_OBJECT_OPERATOR, '?->'], [\T_STRING, 'public'], [\ord('('), '('], [\T_STRING, 'set'], [\ord(')'), ')'], ]], // PHP 8.5: Pipe operator ['|>', [ [\T_PIPE, '|>'] ]], // PHP 8.5: Void cast ['(void)', [ [\T_VOID_CAST, '(void)'], ]], ["( \tvoid \t)", [ [\T_VOID_CAST, "( \tvoid \t)"], ]], ['( vOiD)', [ [\T_VOID_CAST, '( vOiD)'], ]], ["(void\n)", [ [\ord('('), '('], [\T_STRING, 'void'], [\ord(')'), ')'], ]], ]; } /** * @dataProvider provideTestTargetVersion */ public function testTargetVersion(string $phpVersion, string $code, array $expectedTokens): void { $lexer = new Emulative(PhpVersion::fromString($phpVersion)); $this->assertSameTokens($expectedTokens, $lexer->tokenize('<?php ' . $code)); } public static function provideTestTargetVersion() { return [ ['8.0', 'match', [[\T_MATCH, 'match']]], ['7.4', 'match', [[\T_STRING, 'match']]], // Keywords are not case-sensitive. ['8.0', 'MATCH', [[\T_MATCH, 'MATCH']]], ['7.4', 'MATCH', [[\T_STRING, 'MATCH']]], // Tested here to skip testLeaveStuffAloneInStrings. ['8.0', '"$foo?->bar"', [ [ord('"'), '"'], [\T_VARIABLE, '$foo'], [\T_NULLSAFE_OBJECT_OPERATOR, '?->'], [\T_STRING, 'bar'], [ord('"'), '"'], ]], ['8.0', '"$foo?->bar baz"', [ [ord('"'), '"'], [\T_VARIABLE, '$foo'], [\T_NULLSAFE_OBJECT_OPERATOR, '?->'], [\T_STRING, 'bar'], [\T_ENCAPSED_AND_WHITESPACE, ' baz'], [ord('"'), '"'], ]], ['8.4', '__PROPERTY__', [[\T_PROPERTY_C, '__PROPERTY__']]], ['8.3', '__PROPERTY__', [[\T_STRING, '__PROPERTY__']]], ['8.4', '__property__', [[\T_PROPERTY_C, '__property__']]], ['8.3', '__property__', [[\T_STRING, '__property__']]], ['8.4', 'public(set)', [ [\T_PUBLIC_SET, 'public(set)'], ]], ['8.3', 'public(set)', [ [\T_PUBLIC, 'public'], [\ord('('), '('], [\T_STRING, 'set'], [\ord(')'), ')'] ]], ['8.5', '|>', [ [\T_PIPE, '|>'] ]], ['8.4', '|>', [ [\ord('|'), '|'], [\ord('>'), '>'], ]], ['8.5', '(void)', [ [\T_VOID_CAST, '(void)'], ]], ['8.5', "( \tvoid \t)", [ [\T_VOID_CAST, "( \tvoid \t)"], ]], ['8.4', '(void)', [ [\ord('('), '('], [\T_STRING, 'void'], [\ord(')'), ')'], ]], ['8.4', "( \tVOID \t)", [ [\ord('('), '('], [\T_STRING, 'VOID'], [\ord(')'), ')'], ]], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeVisitor/FindingVisitorTest.php
test/PhpParser/NodeVisitor/FindingVisitorTest.php
<?php declare(strict_types=1); namespace PhpParser\NodeVisitor; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\NodeTraverser; class FindingVisitorTest extends \PHPUnit\Framework\TestCase { public function testFindVariables(): void { $traverser = new NodeTraverser(); $visitor = new FindingVisitor(function (Node $node) { return $node instanceof Node\Expr\Variable; }); $traverser->addVisitor($visitor); $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\BinaryOp\Concat( new Expr\Variable('b'), new Expr\Variable('c') )); $stmts = [new Node\Stmt\Expression($assign)]; $traverser->traverse($stmts); $this->assertSame([ $assign->var, $assign->expr->left, $assign->expr->right, ], $visitor->getFoundNodes()); } public function testFindAll(): void { $traverser = new NodeTraverser(); $visitor = new FindingVisitor(function (Node $node) { return true; // All nodes }); $traverser->addVisitor($visitor); $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\BinaryOp\Concat( new Expr\Variable('b'), new Expr\Variable('c') )); $stmts = [new Node\Stmt\Expression($assign)]; $traverser->traverse($stmts); $this->assertSame([ $stmts[0], $assign, $assign->var, $assign->expr, $assign->expr->left, $assign->expr->right, ], $visitor->getFoundNodes()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeVisitor/FirstFindingVisitorTest.php
test/PhpParser/NodeVisitor/FirstFindingVisitorTest.php
<?php declare(strict_types=1); namespace PhpParser\NodeVisitor; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\NodeTraverser; class FirstFindingVisitorTest extends \PHPUnit\Framework\TestCase { public function testFindFirstVariable(): void { $traverser = new NodeTraverser(); $visitor = new FirstFindingVisitor(function (Node $node) { return $node instanceof Node\Expr\Variable; }); $traverser->addVisitor($visitor); $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\Variable('b')); $stmts = [new Node\Stmt\Expression($assign)]; $traverser->traverse($stmts); $this->assertSame($assign->var, $visitor->getFoundNode()); } public function testFindNone(): void { $traverser = new NodeTraverser(); $visitor = new FirstFindingVisitor(function (Node $node) { return $node instanceof Node\Expr\BinaryOp; }); $traverser->addVisitor($visitor); $assign = new Expr\Assign(new Expr\Variable('a'), new Expr\Variable('b')); $stmts = [new Node\Stmt\Expression($assign)]; $traverser->traverse($stmts); $this->assertNull($visitor->getFoundNode()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeVisitor/NodeConnectingVisitorTest.php
test/PhpParser/NodeVisitor/NodeConnectingVisitorTest.php
<?php declare(strict_types=1); namespace PhpParser\NodeVisitor; use PhpParser\Node\Expr\ConstFetch; use PhpParser\Node\Stmt\Else_; use PhpParser\Node\Stmt\If_; use PhpParser\NodeFinder; use PhpParser\NodeTraverser; use PhpParser\ParserFactory; final class NodeConnectingVisitorTest extends \PHPUnit\Framework\TestCase { public function testConnectsNodeToItsParentNodeAndItsSiblingNodes(): void { $ast = (new ParserFactory())->createForNewestSupportedVersion()->parse( '<?php if (true) {} else {}' ); $traverser = new NodeTraverser(); $traverser->addVisitor(new NodeConnectingVisitor()); $ast = $traverser->traverse($ast); $node = (new NodeFinder())->findFirstInstanceof($ast, Else_::class); $this->assertSame(If_::class, get_class($node->getAttribute('parent'))); $this->assertSame(ConstFetch::class, get_class($node->getAttribute('previous'))); $node = (new NodeFinder())->findFirstInstanceof($ast, ConstFetch::class); $this->assertSame(Else_::class, get_class($node->getAttribute('next'))); } public function testWeakReferences(): void { $ast = (new ParserFactory())->createForNewestSupportedVersion()->parse( '<?php if (true) {} else {}' ); $traverser = new NodeTraverser(); $traverser->addVisitor(new NodeConnectingVisitor(true)); $ast = $traverser->traverse($ast); $node = (new NodeFinder())->findFirstInstanceof($ast, Else_::class); $this->assertInstanceOf(\WeakReference::class, $node->getAttribute('weak_parent')); $this->assertSame(If_::class, get_class($node->getAttribute('weak_parent')->get())); $this->assertInstanceOf(\WeakReference::class, $node->getAttribute('weak_previous')); $this->assertSame(ConstFetch::class, get_class($node->getAttribute('weak_previous')->get())); $node = (new NodeFinder())->findFirstInstanceof($ast, ConstFetch::class); $this->assertInstanceOf(\WeakReference::class, $node->getAttribute('weak_next')); $this->assertSame(Else_::class, get_class($node->getAttribute('weak_next')->get())); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeVisitor/ParentConnectingVisitorTest.php
test/PhpParser/NodeVisitor/ParentConnectingVisitorTest.php
<?php declare(strict_types=1); namespace PhpParser\NodeVisitor; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\NodeFinder; use PhpParser\NodeTraverser; use PhpParser\ParserFactory; final class ParentConnectingVisitorTest extends \PHPUnit\Framework\TestCase { public function testConnectsChildNodeToParentNode(): void { $ast = (new ParserFactory())->createForNewestSupportedVersion()->parse( '<?php class C { public function m() {} }' ); $traverser = new NodeTraverser(); $traverser->addVisitor(new ParentConnectingVisitor()); $ast = $traverser->traverse($ast); $node = (new NodeFinder())->findFirstInstanceof($ast, ClassMethod::class); $this->assertSame('C', $node->getAttribute('parent')->name->toString()); } public function testWeakReferences(): void { $ast = (new ParserFactory())->createForNewestSupportedVersion()->parse( '<?php class C { public function m() {} }' ); $traverser = new NodeTraverser(); $traverser->addVisitor(new ParentConnectingVisitor(true)); $ast = $traverser->traverse($ast); $node = (new NodeFinder())->findFirstInstanceof($ast, ClassMethod::class); $weakReference = $node->getAttribute('weak_parent'); $this->assertInstanceOf(\WeakReference::class, $weakReference); $this->assertSame('C', $weakReference->get()->name->toString()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/NodeVisitor/NameResolverTest.php
test/PhpParser/NodeVisitor/NameResolverTest.php
<?php declare(strict_types=1); namespace PhpParser\NodeVisitor; use PhpParser; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Name; use PhpParser\Node\Stmt; class NameResolverTest extends \PHPUnit\Framework\TestCase { private function canonicalize($string) { return str_replace("\r\n", "\n", $string); } /** * @covers \PhpParser\NodeVisitor\NameResolver */ public function testResolveNames(): void { $code = <<<'EOC' <?php namespace Foo { use Hallo as Hi; new Bar(); new Hi(); new Hi\Bar(); new \Bar(); new namespace\Bar(); bar(); hi(); Hi\bar(); foo\bar(); \bar(); namespace\bar(); } namespace { use Hallo as Hi; new Bar(); new Hi(); new Hi\Bar(); new \Bar(); new namespace\Bar(); bar(); hi(); Hi\bar(); foo\bar(); \bar(); namespace\bar(); } namespace Bar { use function foo\bar as baz; use const foo\BAR as BAZ; use foo as bar; bar(); baz(); bar\foo(); baz\foo(); BAR(); BAZ(); BAR\FOO(); BAZ\FOO(); bar; baz; bar\foo; baz\foo; BAR; BAZ; BAR\FOO; BAZ\FOO; } namespace Baz { use A\T\{B\C, D\E}; use function X\T\{b\c, d\e}; use const Y\T\{B\C, D\E}; use Z\T\{G, function f, const K}; new C; new E; new C\D; new E\F; new G; c(); e(); f(); C; E; K; } EOC; $expectedCode = <<<'EOC' namespace Foo { use Hallo as Hi; new \Foo\Bar(); new \Hallo(); new \Hallo\Bar(); new \Bar(); new \Foo\Bar(); bar(); hi(); \Hallo\bar(); \Foo\foo\bar(); \bar(); \Foo\bar(); } namespace { use Hallo as Hi; new \Bar(); new \Hallo(); new \Hallo\Bar(); new \Bar(); new \Bar(); \bar(); \hi(); \Hallo\bar(); \foo\bar(); \bar(); \bar(); } namespace Bar { use function foo\bar as baz; use const foo\BAR as BAZ; use foo as bar; bar(); \foo\bar(); \foo\foo(); \Bar\baz\foo(); BAR(); \foo\bar(); \foo\FOO(); \Bar\BAZ\FOO(); bar; baz; \foo\foo; \Bar\baz\foo; BAR; \foo\BAR; \foo\FOO; \Bar\BAZ\FOO; } namespace Baz { use A\T\{B\C, D\E}; use function X\T\{b\c, d\e}; use const Y\T\{B\C, D\E}; use Z\T\{G, function f, const K}; new \A\T\B\C(); new \A\T\D\E(); new \A\T\B\C\D(); new \A\T\D\E\F(); new \Z\T\G(); \X\T\b\c(); \X\T\d\e(); \Z\T\f(); \Y\T\B\C; \Y\T\D\E; \Z\T\K; } EOC; $prettyPrinter = new PhpParser\PrettyPrinter\Standard(); $stmts = $this->parseAndResolve($code); $this->assertSame( $this->canonicalize($expectedCode), $prettyPrinter->prettyPrint($stmts) ); } /** * @covers \PhpParser\NodeVisitor\NameResolver */ public function testResolveLocations(): void { $code = <<<'EOC' <?php namespace NS; #[X] class A extends B implements C, D { use E, F, G { f as private g; E::h as i; E::j insteadof F, G; } #[X] public float $php = 7.4; public ?Foo $person; protected static ?bool $probability; public A|B|int $prop; #[X] const C = 1; public const X A = X::Bar; public const X\Foo B = X\Foo::Bar; public const \X\Foo C = \X\Foo::Bar; public Foo $foo { #[X] set(#[X] Bar $v) {} } public function __construct( public Foo $bar { #[X] set(#[X] Bar $v) {} } ) {} } #[X] interface A extends C, D { public function a(A $a) : A; public function b(A|B|int $a): A|B|int; public function c(A&B $a): A&B; } #[X] enum E: int { #[X] case A = 1; } #[X] trait A {} #[X] function f(#[X] A $a) : A {} function f2(array $a) : array {} function fn3(?A $a) : ?A {} function fn4(?array $a) : ?array {} #[X] function(A $a) : A {}; #[X] fn(array $a): array => $a; fn(A $a): A => $a; fn(?A $a): ?A => $a; #[X] const EXAMPLE = true; A::b(); A::$b; A::B; new A; $a instanceof A; namespace\a(); namespace\A; try { $someThing; } catch (A $a) { $someThingElse; } EOC; $expectedCode = <<<'EOC' namespace NS; #[\NS\X] class A extends \NS\B implements \NS\C, \NS\D { use \NS\E, \NS\F, \NS\G { f as private g; \NS\E::h as i; \NS\E::j insteadof \NS\F, \NS\G; } #[\NS\X] public float $php = 7.4; public ?\NS\Foo $person; protected static ?bool $probability; public \NS\A|\NS\B|int $prop; #[\NS\X] const C = 1; public const \NS\X A = \NS\X::Bar; public const \NS\X\Foo B = \NS\X\Foo::Bar; public const \X\Foo C = \X\Foo::Bar; public \NS\Foo $foo { #[\NS\X] set( #[\NS\X] \NS\Bar $v ) { } } public function __construct(public \NS\Foo $bar { #[\NS\X] set( #[\NS\X] \NS\Bar $v ) { } }) { } } #[\NS\X] interface A extends \NS\C, \NS\D { public function a(\NS\A $a): \NS\A; public function b(\NS\A|\NS\B|int $a): \NS\A|\NS\B|int; public function c(\NS\A&\NS\B $a): \NS\A&\NS\B; } #[\NS\X] enum E : int { #[\NS\X] case A = 1; } #[\NS\X] trait A { } #[\NS\X] function f( #[\NS\X] \NS\A $a ): \NS\A { } function f2(array $a): array { } function fn3(?\NS\A $a): ?\NS\A { } function fn4(?array $a): ?array { } #[\NS\X] function (\NS\A $a): \NS\A { }; #[\NS\X] fn(array $a): array => $a; fn(\NS\A $a): \NS\A => $a; fn(?\NS\A $a): ?\NS\A => $a; #[\NS\X] const EXAMPLE = true; \NS\A::b(); \NS\A::$b; \NS\A::B; new \NS\A(); $a instanceof \NS\A; \NS\a(); \NS\A; try { $someThing; } catch (\NS\A $a) { $someThingElse; } EOC; $prettyPrinter = new PhpParser\PrettyPrinter\Standard(); $stmts = $this->parseAndResolve($code); $this->assertSame( $this->canonicalize($expectedCode), $prettyPrinter->prettyPrint($stmts) ); } public function testNoResolveSpecialName(): void { $stmts = [new Node\Expr\New_(new Name('self'))]; $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver()); $this->assertEquals($stmts, $traverser->traverse($stmts)); } public function testAddDeclarationNamespacedName(): void { $nsStmts = [ new Stmt\Class_('A'), new Stmt\Interface_('B'), new Stmt\Function_('C'), new Stmt\Const_([ new Node\Const_('D', new Node\Scalar\Int_(42)) ]), new Stmt\Trait_('E'), new Expr\New_(new Stmt\Class_(null)), new Stmt\Enum_('F'), ]; $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver()); $stmts = $traverser->traverse([new Stmt\Namespace_(new Name('NS'), $nsStmts)]); $this->assertSame('NS\\A', (string) $stmts[0]->stmts[0]->namespacedName); $this->assertSame('NS\\B', (string) $stmts[0]->stmts[1]->namespacedName); $this->assertSame('NS\\C', (string) $stmts[0]->stmts[2]->namespacedName); $this->assertSame('NS\\D', (string) $stmts[0]->stmts[3]->consts[0]->namespacedName); $this->assertSame('NS\\E', (string) $stmts[0]->stmts[4]->namespacedName); $this->assertNull($stmts[0]->stmts[5]->class->namespacedName); $this->assertSame('NS\\F', (string) $stmts[0]->stmts[6]->namespacedName); $stmts = $traverser->traverse([new Stmt\Namespace_(null, $nsStmts)]); $this->assertSame('A', (string) $stmts[0]->stmts[0]->namespacedName); $this->assertSame('B', (string) $stmts[0]->stmts[1]->namespacedName); $this->assertSame('C', (string) $stmts[0]->stmts[2]->namespacedName); $this->assertSame('D', (string) $stmts[0]->stmts[3]->consts[0]->namespacedName); $this->assertSame('E', (string) $stmts[0]->stmts[4]->namespacedName); $this->assertNull($stmts[0]->stmts[5]->class->namespacedName); $this->assertSame('F', (string) $stmts[0]->stmts[6]->namespacedName); } public function testAddRuntimeResolvedNamespacedName(): void { $stmts = [ new Stmt\Namespace_(new Name('NS'), [ new Expr\FuncCall(new Name('foo')), new Expr\ConstFetch(new Name('FOO')), ]), new Stmt\Namespace_(null, [ new Expr\FuncCall(new Name('foo')), new Expr\ConstFetch(new Name('FOO')), ]), ]; $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver()); $stmts = $traverser->traverse($stmts); $this->assertSame('NS\\foo', (string) $stmts[0]->stmts[0]->name->getAttribute('namespacedName')); $this->assertSame('NS\\FOO', (string) $stmts[0]->stmts[1]->name->getAttribute('namespacedName')); $this->assertFalse($stmts[1]->stmts[0]->name->hasAttribute('namespacedName')); $this->assertFalse($stmts[1]->stmts[1]->name->hasAttribute('namespacedName')); } /** * @dataProvider provideTestError */ public function testError(Node $stmt, $errorMsg): void { $this->expectException(\PhpParser\Error::class); $this->expectExceptionMessage($errorMsg); $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver()); $traverser->traverse([$stmt]); } public static function provideTestError() { return [ [ new Stmt\Use_([ new Node\UseItem(new Name('A\B'), 'B', 0, ['startLine' => 1]), new Node\UseItem(new Name('C\D'), 'B', 0, ['startLine' => 2]), ], Stmt\Use_::TYPE_NORMAL), 'Cannot use C\D as B because the name is already in use on line 2' ], [ new Stmt\Use_([ new Node\UseItem(new Name('a\b'), 'b', 0, ['startLine' => 1]), new Node\UseItem(new Name('c\d'), 'B', 0, ['startLine' => 2]), ], Stmt\Use_::TYPE_FUNCTION), 'Cannot use function c\d as B because the name is already in use on line 2' ], [ new Stmt\Use_([ new Node\UseItem(new Name('A\B'), 'B', 0, ['startLine' => 1]), new Node\UseItem(new Name('C\D'), 'B', 0, ['startLine' => 2]), ], Stmt\Use_::TYPE_CONSTANT), 'Cannot use const C\D as B because the name is already in use on line 2' ], [ new Expr\New_(new Name\FullyQualified('self', ['startLine' => 3])), "'\\self' is an invalid class name on line 3" ], [ new Expr\New_(new Name\Relative('self', ['startLine' => 3])), "'\\self' is an invalid class name on line 3" ], [ new Expr\New_(new Name\FullyQualified('PARENT', ['startLine' => 3])), "'\\PARENT' is an invalid class name on line 3" ], [ new Expr\New_(new Name\Relative('STATIC', ['startLine' => 3])), "'\\STATIC' is an invalid class name on line 3" ], ]; } public function testClassNameIsCaseInsensitive(): void { $source = <<<'EOC' <?php namespace Foo; use Bar\Baz; $test = new baz(); EOC; $parser = new PhpParser\Parser\Php7(new PhpParser\Lexer\Emulative()); $stmts = $parser->parse($source); $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver()); $stmts = $traverser->traverse($stmts); $stmt = $stmts[0]; $assign = $stmt->stmts[1]->expr; $this->assertSame('Bar\\Baz', $assign->expr->class->name); } public function testSpecialClassNamesAreCaseInsensitive(): void { $source = <<<'EOC' <?php namespace Foo; class Bar { public static function method() { SELF::method(); PARENT::method(); STATIC::method(); } } EOC; $parser = new PhpParser\Parser\Php7(new PhpParser\Lexer\Emulative()); $stmts = $parser->parse($source); $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver()); $stmts = $traverser->traverse($stmts); $classStmt = $stmts[0]; $methodStmt = $classStmt->stmts[0]->stmts[0]; $this->assertSame('SELF', (string) $methodStmt->stmts[0]->expr->class); $this->assertSame('PARENT', (string) $methodStmt->stmts[1]->expr->class); $this->assertSame('STATIC', (string) $methodStmt->stmts[2]->expr->class); } public function testAddOriginalNames(): void { $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver(null, ['preserveOriginalNames' => true])); $n1 = new Name('Bar'); $n2 = new Name('bar'); $origStmts = [ new Stmt\Namespace_(new Name('Foo'), [ new Expr\ClassConstFetch($n1, 'FOO'), new Expr\FuncCall($n2), ]) ]; $stmts = $traverser->traverse($origStmts); $this->assertSame($n1, $stmts[0]->stmts[0]->class->getAttribute('originalName')); $this->assertSame($n2, $stmts[0]->stmts[1]->name->getAttribute('originalName')); } public function testAttributeOnlyMode(): void { $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver(null, ['replaceNodes' => false])); $n1 = new Name('Bar'); $n2 = new Name('bar'); $origStmts = [ new Stmt\Namespace_(new Name('Foo'), [ new Expr\ClassConstFetch($n1, 'FOO'), new Expr\FuncCall($n2), ]) ]; $traverser->traverse($origStmts); $this->assertEquals( new Name\FullyQualified('Foo\Bar'), $n1->getAttribute('resolvedName')); $this->assertFalse($n2->hasAttribute('resolvedName')); $this->assertEquals( new Name\FullyQualified('Foo\bar'), $n2->getAttribute('namespacedName')); } private function parseAndResolve(string $code): array { $parser = new PhpParser\Parser\Php8(new PhpParser\Lexer\Emulative()); $traverser = new PhpParser\NodeTraverser(); $traverser->addVisitor(new NameResolver()); $stmts = $parser->parse($code); return $traverser->traverse($stmts); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/ParamTest.php
test/PhpParser/Node/ParamTest.php
<?php declare(strict_types=1); namespace PhpParser\Node; use PhpParser\Modifiers; use PhpParser\Node\Expr\Variable; class ParamTest extends \PHPUnit\Framework\TestCase { public function testNoModifiers(): void { $node = new Param(new Variable('foo')); $this->assertFalse($node->isPromoted()); $this->assertFalse($node->isPrivate()); $this->assertFalse($node->isProtected()); $this->assertFalse($node->isPrivate()); $this->assertFalse($node->isReadonly()); $this->assertFalse($node->isPublicSet()); $this->assertFalse($node->isProtectedSet()); $this->assertFalse($node->isPrivateSet()); } /** * @dataProvider provideModifiers */ public function testModifiers(string $modifier): void { $node = new Param(new Variable('foo')); $node->flags = constant(Modifiers::class . '::' . strtoupper($modifier)); $this->assertTrue($node->isPromoted()); $this->assertTrue($node->{'is' . $modifier}()); } public static function provideModifiers() { return [ ['public'], ['protected'], ['private'], ['readonly'], ['final'], ]; } public function testSetVisibility() { $node = new Param(new Variable('foo')); $node->flags = Modifiers::PRIVATE_SET; $this->assertTrue($node->isPrivateSet()); $this->assertTrue($node->isPublic()); $node->flags = Modifiers::PROTECTED_SET; $this->assertTrue($node->isProtectedSet()); $this->assertTrue($node->isPublic()); $node->flags = Modifiers::PUBLIC_SET; $this->assertTrue($node->isPublicSet()); $this->assertTrue($node->isPublic()); } public function testPromotedPropertyWithoutVisibilityModifier(): void { $node = new Param(new Variable('foo')); $get = new PropertyHook('get', null); $node->hooks[] = $get; $this->assertTrue($node->isPromoted()); $this->assertTrue($node->isPublic()); } public function testNonPromotedPropertyIsNotPublic(): void { $node = new Param(new Variable('foo')); $this->assertFalse($node->isPublic()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/PropertyHookTest.php
test/PhpParser/Node/PropertyHookTest.php
<?php declare(strict_types=1); namespace PhpParser\Node; use PhpParser\Modifiers; use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\PropertyFetch; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Stmt\Expression; use PhpParser\Node\Stmt\Return_; use PhpParser\ParserFactory; use PhpParser\PrettyPrinter\Standard; class PropertyHookTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideModifiers */ public function testModifiers($modifier): void { $node = new PropertyHook( 'get', null, [ 'flags' => constant(Modifiers::class . '::' . strtoupper($modifier)), ] ); $this->assertTrue($node->{'is' . $modifier}()); } public function testNoModifiers(): void { $node = new PropertyHook('get', null); $this->assertFalse($node->isFinal()); } public static function provideModifiers() { return [ ['final'], ]; } public function testGetStmts(): void { $expr = new Variable('test'); $get = new PropertyHook('get', $expr); $this->assertEquals([new Return_($expr)], $get->getStmts()); $set = new PropertyHook('set', $expr, [], ['propertyName' => 'abc']); $this->assertEquals([ new Expression(new Assign(new PropertyFetch(new Variable('this'), 'abc'), $expr)) ], $set->getStmts()); } public function testGetStmtsSetHookFromParser(): void { $parser = (new ParserFactory())->createForNewestSupportedVersion(); $prettyPrinter = new Standard(); $stmts = $parser->parse(<<<'CODE' <?php class Test { public $prop1 { set => 123; } public function __construct(public $prop2 { set => 456; }) {} } CODE); $hook1 = $stmts[0]->stmts[0]->hooks[0]; $this->assertEquals('$this->prop1 = 123;', $prettyPrinter->prettyPrint($hook1->getStmts())); $hook2 = $stmts[0]->stmts[1]->params[0]->hooks[0]; $this->assertEquals('$this->prop2 = 456;', $prettyPrinter->prettyPrint($hook2->getStmts())); } public function testGetStmtsUnknownHook(): void { $expr = new Variable('test'); $hook = new PropertyHook('foobar', $expr); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Unknown property hook "foobar"'); $hook->getStmts(); } public function testGetStmtsSetHookWithoutPropertyName(): void { $expr = new Variable('test'); $set = new PropertyHook('set', $expr); $this->expectException(\LogicException::class); $this->expectExceptionMessage('Can only use getStmts() on a "set" hook if the "propertyName" attribute is set'); $set->getStmts(); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/NameTest.php
test/PhpParser/Node/NameTest.php
<?php declare(strict_types=1); namespace PhpParser\Node; class NameTest extends \PHPUnit\Framework\TestCase { public function testConstruct(): void { $name = new Name(['foo', 'bar']); $this->assertSame('foo\bar', $name->name); $name = new Name('foo\bar'); $this->assertSame('foo\bar', $name->name); $name = new Name($name); $this->assertSame('foo\bar', $name->name); } public function testGet(): void { $name = new Name('foo'); $this->assertSame('foo', $name->getFirst()); $this->assertSame('foo', $name->getLast()); $this->assertSame(['foo'], $name->getParts()); $name = new Name('foo\bar'); $this->assertSame('foo', $name->getFirst()); $this->assertSame('bar', $name->getLast()); $this->assertSame(['foo', 'bar'], $name->getParts()); } public function testToString(): void { $name = new Name('Foo\Bar'); $this->assertSame('Foo\Bar', (string) $name); $this->assertSame('Foo\Bar', $name->toString()); $this->assertSame('foo\bar', $name->toLowerString()); } public function testSlice(): void { $name = new Name('foo\bar\baz'); $this->assertEquals(new Name('foo\bar\baz'), $name->slice(0)); $this->assertEquals(new Name('bar\baz'), $name->slice(1)); $this->assertNull($name->slice(3)); $this->assertEquals(new Name('foo\bar\baz'), $name->slice(-3)); $this->assertEquals(new Name('bar\baz'), $name->slice(-2)); $this->assertEquals(new Name('foo\bar'), $name->slice(0, -1)); $this->assertNull($name->slice(0, -3)); $this->assertEquals(new Name('bar'), $name->slice(1, -1)); $this->assertNull($name->slice(1, -2)); $this->assertEquals(new Name('bar'), $name->slice(-2, 1)); $this->assertEquals(new Name('bar'), $name->slice(-2, -1)); $this->assertNull($name->slice(-2, -2)); } public function testSliceOffsetTooLarge(): void { $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Offset 4 is out of bounds'); (new Name('foo\bar\baz'))->slice(4); } public function testSliceOffsetTooSmall(): void { $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Offset -4 is out of bounds'); (new Name('foo\bar\baz'))->slice(-4); } public function testSliceLengthTooLarge(): void { $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Length 4 is out of bounds'); (new Name('foo\bar\baz'))->slice(0, 4); } public function testSliceLengthTooSmall(): void { $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Length -4 is out of bounds'); (new Name('foo\bar\baz'))->slice(0, -4); } public function testSliceLengthTooLargeWithOffset(): void { $this->expectException(\OutOfBoundsException::class); $this->expectExceptionMessage('Length 3 is out of bounds'); (new Name('foo\bar\baz'))->slice(1, 3); } public function testConcat(): void { $this->assertEquals(new Name('foo\bar\baz'), Name::concat('foo', 'bar\baz')); $this->assertEquals( new Name\FullyQualified('foo\bar'), Name\FullyQualified::concat(['foo'], new Name('bar')) ); $attributes = ['foo' => 'bar']; $this->assertEquals( new Name\Relative('foo\bar\baz', $attributes), Name\Relative::concat(new Name\FullyQualified('foo\bar'), 'baz', $attributes) ); $this->assertEquals(new Name('foo'), Name::concat(null, 'foo')); $this->assertEquals(new Name('foo'), Name::concat('foo', null)); $this->assertNull(Name::concat(null, null)); } public function testNameTypes(): void { $name = new Name('foo'); $this->assertTrue($name->isUnqualified()); $this->assertFalse($name->isQualified()); $this->assertFalse($name->isFullyQualified()); $this->assertFalse($name->isRelative()); $this->assertSame('foo', $name->toCodeString()); $name = new Name('foo\bar'); $this->assertFalse($name->isUnqualified()); $this->assertTrue($name->isQualified()); $this->assertFalse($name->isFullyQualified()); $this->assertFalse($name->isRelative()); $this->assertSame('foo\bar', $name->toCodeString()); $name = new Name\FullyQualified('foo'); $this->assertFalse($name->isUnqualified()); $this->assertFalse($name->isQualified()); $this->assertTrue($name->isFullyQualified()); $this->assertFalse($name->isRelative()); $this->assertSame('\foo', $name->toCodeString()); $name = new Name\Relative('foo'); $this->assertFalse($name->isUnqualified()); $this->assertFalse($name->isQualified()); $this->assertFalse($name->isFullyQualified()); $this->assertTrue($name->isRelative()); $this->assertSame('namespace\foo', $name->toCodeString()); } public function testInvalidArg(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Expected string, array of parts or Name instance'); Name::concat('foo', new \stdClass()); } public function testInvalidEmptyString(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Name cannot be empty'); new Name(''); } public function testInvalidEmptyArray(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Name cannot be empty'); new Name([]); } /** @dataProvider provideTestIsSpecialClassName */ public function testIsSpecialClassName($name, $expected): void { $name = new Name($name); $this->assertSame($expected, $name->isSpecialClassName()); } public static function provideTestIsSpecialClassName() { return [ ['self', true], ['PARENT', true], ['Static', true], ['self\not', false], ['not\self', false], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/IdentifierTest.php
test/PhpParser/Node/IdentifierTest.php
<?php declare(strict_types=1); namespace PhpParser\Node; class IdentifierTest extends \PHPUnit\Framework\TestCase { public function testConstructorThrows(): void { self::expectException(\InvalidArgumentException::class); new Identifier(''); } public function testToString(): void { $identifier = new Identifier('Foo'); $this->assertSame('Foo', (string) $identifier); $this->assertSame('Foo', $identifier->toString()); $this->assertSame('foo', $identifier->toLowerString()); } /** @dataProvider provideTestIsSpecialClassName */ public function testIsSpecialClassName($identifier, $expected): void { $identifier = new Identifier($identifier); $this->assertSame($expected, $identifier->isSpecialClassName()); } public static function provideTestIsSpecialClassName() { return [ ['self', true], ['PARENT', true], ['Static', true], ['other', false], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Stmt/PropertyTest.php
test/PhpParser/Node/Stmt/PropertyTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Stmt; use PhpParser\Modifiers; class PropertyTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideModifiers */ public function testModifiers($modifier): void { $node = new Property( constant(Modifiers::class . '::' . strtoupper($modifier)), [] // invalid ); $this->assertTrue($node->{'is' . $modifier}()); } public function testNoModifiers(): void { $node = new Property(0, []); $this->assertTrue($node->isPublic()); $this->assertFalse($node->isProtected()); $this->assertFalse($node->isPrivate()); $this->assertFalse($node->isStatic()); $this->assertFalse($node->isReadonly()); $this->assertFalse($node->isPublicSet()); $this->assertFalse($node->isProtectedSet()); $this->assertFalse($node->isPrivateSet()); } public function testStaticImplicitlyPublic(): void { $node = new Property(Modifiers::STATIC, []); $this->assertTrue($node->isPublic()); $this->assertFalse($node->isProtected()); $this->assertFalse($node->isPrivate()); $this->assertTrue($node->isStatic()); $this->assertFalse($node->isReadonly()); } public static function provideModifiers() { return [ ['public'], ['protected'], ['private'], ['static'], ['readonly'], ]; } public function testSetVisibility() { $node = new Property(Modifiers::PRIVATE_SET, []); $this->assertTrue($node->isPrivateSet()); $node = new Property(Modifiers::PROTECTED_SET, []); $this->assertTrue($node->isProtectedSet()); $node = new Property(Modifiers::PUBLIC_SET, []); $this->assertTrue($node->isPublicSet()); } public function testIsFinal() { $node = new Property(Modifiers::FINAL, []); $this->assertTrue($node->isFinal()); } public function testIsAbstract() { $node = new Property(Modifiers::ABSTRACT, []); $this->assertTrue($node->isAbstract()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Stmt/ClassTest.php
test/PhpParser/Node/Stmt/ClassTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Stmt; use PhpParser\Modifiers; use PhpParser\Node\PropertyItem; use PhpParser\Node\Scalar\String_; class ClassTest extends \PHPUnit\Framework\TestCase { public function testIsAbstract(): void { $class = new Class_('Foo', ['type' => Modifiers::ABSTRACT]); $this->assertTrue($class->isAbstract()); $class = new Class_('Foo'); $this->assertFalse($class->isAbstract()); } public function testIsFinal(): void { $class = new Class_('Foo', ['type' => Modifiers::FINAL]); $this->assertTrue($class->isFinal()); $class = new Class_('Foo'); $this->assertFalse($class->isFinal()); } public function testGetTraitUses(): void { $traitUses = [ new TraitUse([new Trait_('foo')]), new TraitUse([new Trait_('bar')]), ]; $class = new Class_('Foo', [ 'stmts' => [ $traitUses[0], new ClassMethod('fooBar'), $traitUses[1], ] ]); $this->assertSame($traitUses, $class->getTraitUses()); } public function testGetMethods(): void { $methods = [ new ClassMethod('foo'), new ClassMethod('bar'), new ClassMethod('fooBar'), ]; $class = new Class_('Foo', [ 'stmts' => [ new TraitUse([]), $methods[0], new ClassConst([]), $methods[1], new Property(0, []), $methods[2], ] ]); $this->assertSame($methods, $class->getMethods()); } public function testGetConstants(): void { $constants = [ new ClassConst([new \PhpParser\Node\Const_('foo', new String_('foo_value'))]), new ClassConst([new \PhpParser\Node\Const_('bar', new String_('bar_value'))]), ]; $class = new Class_('Foo', [ 'stmts' => [ new TraitUse([]), $constants[0], new ClassMethod('fooBar'), $constants[1], ] ]); $this->assertSame($constants, $class->getConstants()); } public function testGetProperties(): void { $properties = [ new Property(Modifiers::PUBLIC, [new PropertyItem('foo')]), new Property(Modifiers::PUBLIC, [new PropertyItem('bar')]), ]; $class = new Class_('Foo', [ 'stmts' => [ new TraitUse([]), $properties[0], new ClassConst([]), $properties[1], new ClassMethod('fooBar'), ] ]); $this->assertSame($properties, $class->getProperties()); } public function testGetProperty(): void { $properties = [ $fooProp = new Property(Modifiers::PUBLIC, [new PropertyItem('foo1')]), $barProp = new Property(Modifiers::PUBLIC, [new PropertyItem('BAR1')]), $fooBarProp = new Property(Modifiers::PUBLIC, [new PropertyItem('foo2'), new PropertyItem('bar2')]), ]; $class = new Class_('Foo', [ 'stmts' => [ new TraitUse([]), $properties[0], new ClassConst([]), $properties[1], new ClassMethod('fooBar'), $properties[2], ] ]); $this->assertSame($fooProp, $class->getProperty('foo1')); $this->assertSame($barProp, $class->getProperty('BAR1')); $this->assertSame($fooBarProp, $class->getProperty('foo2')); $this->assertSame($fooBarProp, $class->getProperty('bar2')); $this->assertNull($class->getProperty('bar1')); $this->assertNull($class->getProperty('nonExisting')); } public function testGetMethod(): void { $methodConstruct = new ClassMethod('__CONSTRUCT'); $methodTest = new ClassMethod('test'); $class = new Class_('Foo', [ 'stmts' => [ new ClassConst([]), $methodConstruct, new Property(0, []), $methodTest, ] ]); $this->assertSame($methodConstruct, $class->getMethod('__construct')); $this->assertSame($methodTest, $class->getMethod('test')); $this->assertNull($class->getMethod('nonExisting')); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Stmt/ClassMethodTest.php
test/PhpParser/Node/Stmt/ClassMethodTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Stmt; use PhpParser\Modifiers; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; use PhpParser\Node\Param; class ClassMethodTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideModifiers */ public function testModifiers($modifier): void { $node = new ClassMethod('foo', [ 'type' => constant(Modifiers::class . '::' . strtoupper($modifier)) ]); $this->assertTrue($node->{'is' . $modifier}()); } public function testNoModifiers(): void { $node = new ClassMethod('foo', ['type' => 0]); $this->assertTrue($node->isPublic()); $this->assertFalse($node->isProtected()); $this->assertFalse($node->isPrivate()); $this->assertFalse($node->isAbstract()); $this->assertFalse($node->isFinal()); $this->assertFalse($node->isStatic()); $this->assertFalse($node->isMagic()); } public static function provideModifiers() { return [ ['public'], ['protected'], ['private'], ['abstract'], ['final'], ['static'], ]; } /** * Checks that implicit public modifier detection for method is working * * @dataProvider implicitPublicModifiers * * @param string $modifier Node type modifier */ public function testImplicitPublic(string $modifier): void { $node = new ClassMethod('foo', [ 'type' => constant(Modifiers::class . '::' . strtoupper($modifier)) ]); $this->assertTrue($node->isPublic(), 'Node should be implicitly public'); } public static function implicitPublicModifiers() { return [ ['abstract'], ['final'], ['static'], ]; } /** * @dataProvider provideMagics * * @param string $name Node name */ public function testMagic(string $name): void { $node = new ClassMethod($name); $this->assertTrue($node->isMagic(), 'Method should be magic'); } public static function provideMagics() { return [ ['__construct'], ['__DESTRUCT'], ['__caLL'], ['__callstatic'], ['__get'], ['__set'], ['__isset'], ['__unset'], ['__sleep'], ['__wakeup'], ['__tostring'], ['__set_state'], ['__clone'], ['__invoke'], ['__debuginfo'], ]; } public function testFunctionLike(): void { $param = new Param(new Variable('a')); $type = new Name('Foo'); $return = new Return_(new Variable('a')); $method = new ClassMethod('test', [ 'byRef' => false, 'params' => [$param], 'returnType' => $type, 'stmts' => [$return], ]); $this->assertFalse($method->returnsByRef()); $this->assertSame([$param], $method->getParams()); $this->assertSame($type, $method->getReturnType()); $this->assertSame([$return], $method->getStmts()); $method = new ClassMethod('test', [ 'byRef' => true, 'stmts' => null, ]); $this->assertTrue($method->returnsByRef()); $this->assertNull($method->getStmts()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Stmt/ClassConstTest.php
test/PhpParser/Node/Stmt/ClassConstTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Stmt; use PhpParser\Modifiers; class ClassConstTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideModifiers */ public function testModifiers($modifier): void { $node = new ClassConst( [], // invalid constant(Modifiers::class . '::' . strtoupper($modifier)) ); $this->assertTrue($node->{'is' . $modifier}()); } public function testNoModifiers(): void { $node = new ClassConst([], 0); $this->assertTrue($node->isPublic()); $this->assertFalse($node->isProtected()); $this->assertFalse($node->isPrivate()); $this->assertFalse($node->isFinal()); } public static function provideModifiers() { return [ ['public'], ['protected'], ['private'], ['final'], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Stmt/InterfaceTest.php
test/PhpParser/Node/Stmt/InterfaceTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Stmt; use PhpParser\Node; use PhpParser\Node\Scalar\String_; class InterfaceTest extends \PHPUnit\Framework\TestCase { public function testGetMethods(): void { $methods = [ new ClassMethod('foo'), new ClassMethod('bar'), ]; $interface = new Interface_('Foo', [ 'stmts' => [ new Node\Stmt\ClassConst([new Node\Const_('C1', new Node\Scalar\String_('C1'))]), $methods[0], new Node\Stmt\ClassConst([new Node\Const_('C2', new Node\Scalar\String_('C2'))]), $methods[1], new Node\Stmt\ClassConst([new Node\Const_('C3', new Node\Scalar\String_('C3'))]), ] ]); $this->assertSame($methods, $interface->getMethods()); } public function testGetConstants(): void { $constants = [ new ClassConst([new \PhpParser\Node\Const_('foo', new String_('foo_value'))]), new ClassConst([new \PhpParser\Node\Const_('bar', new String_('bar_value'))]), ]; $class = new Interface_('Foo', [ 'stmts' => [ new TraitUse([]), $constants[0], new ClassMethod('fooBar'), $constants[1], ] ]); $this->assertSame($constants, $class->getConstants()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Expr/CallableLikeTest.php
test/PhpParser/Node/Expr/CallableLikeTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Expr; use PhpParser\Node\Arg; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\VariadicPlaceholder; class CallableLikeTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideTestIsFirstClassCallable */ public function testIsFirstClassCallable(CallLike $node, bool $isFirstClassCallable): void { $this->assertSame($isFirstClassCallable, $node->isFirstClassCallable()); if (!$isFirstClassCallable) { $this->assertSame($node->getRawArgs(), $node->getArgs()); } } /** * @dataProvider provideTestGetArg */ public function testGetArg(CallLike $node, ?Arg $expected): void { $this->assertSame($expected, $node->getArg('bar', 1)); } public static function provideTestIsFirstClassCallable() { $normalArgs = [new Arg(new Int_(1))]; $callableArgs = [new VariadicPlaceholder()]; return [ [new FuncCall(new Name('test'), $normalArgs), false], [new FuncCall(new Name('test'), $callableArgs), true], [new MethodCall(new Variable('this'), 'test', $normalArgs), false], [new MethodCall(new Variable('this'), 'test', $callableArgs), true], [new StaticCall(new Name('Test'), 'test', $normalArgs), false], [new StaticCall(new Name('Test'), 'test', $callableArgs), true], [new New_(new Name('Test'), $normalArgs), false], [new NullsafeMethodCall(new Variable('this'), 'test', $normalArgs), false], // This is not legal code, but accepted by the parser. [new New_(new Name('Test'), $callableArgs), true], [new NullsafeMethodCall(new Variable('this'), 'test', $callableArgs), true], ]; } public static function provideTestGetArg() { $foo = new Arg(new Int_(1)); $namedFoo = new Arg(new Int_(1), false, false, [], new Identifier('foo')); $bar = new Arg(new Int_(2)); $namedBar = new Arg(new Int_(2), false, false, [], new Identifier('bar')); $unpack = new Arg(new Int_(3), false, true); $callableArgs = [new VariadicPlaceholder()]; return [ [new FuncCall(new Name('test'), [$foo]), null], [new FuncCall(new Name('test'), [$namedFoo]), null], [new FuncCall(new Name('test'), [$foo, $bar]), $bar], [new FuncCall(new Name('test'), [$namedBar]), $namedBar], [new FuncCall(new Name('test'), [$namedFoo, $namedBar]), $namedBar], [new FuncCall(new Name('test'), [$namedBar, $namedFoo]), $namedBar], [new FuncCall(new Name('test'), [$namedFoo, $unpack]), null], [new FuncCall(new Name('test'), $callableArgs), null], [new MethodCall(new Variable('this'), 'test', [$foo]), null], [new MethodCall(new Variable('this'), 'test', [$namedFoo]), null], [new MethodCall(new Variable('this'), 'test', [$foo, $bar]), $bar], [new MethodCall(new Variable('this'), 'test', [$namedBar]), $namedBar], [new MethodCall(new Variable('this'), 'test', [$namedFoo, $namedBar]), $namedBar], [new MethodCall(new Variable('this'), 'test', [$namedBar, $namedFoo]), $namedBar], [new MethodCall(new Variable('this'), 'test', [$namedFoo, $unpack]), null], [new MethodCall(new Variable('this'), 'test', $callableArgs), null], [new StaticCall(new Name('Test'), 'test', [$foo]), null], [new StaticCall(new Name('Test'), 'test', [$namedFoo]), null], [new StaticCall(new Name('Test'), 'test', [$foo, $bar]), $bar], [new StaticCall(new Name('Test'), 'test', [$namedBar]), $namedBar], [new StaticCall(new Name('Test'), 'test', [$namedFoo, $namedBar]), $namedBar], [new StaticCall(new Name('Test'), 'test', [$namedBar, $namedFoo]), $namedBar], [new StaticCall(new Name('Test'), 'test', [$namedFoo, $unpack]), null], [new StaticCall(new Name('Test'), 'test', $callableArgs), null], [new New_(new Name('test'), [$foo]), null], [new New_(new Name('test'), [$namedFoo]), null], [new New_(new Name('test'), [$foo, $bar]), $bar], [new New_(new Name('test'), [$namedBar]), $namedBar], [new New_(new Name('test'), [$namedFoo, $namedBar]), $namedBar], [new New_(new Name('test'), [$namedBar, $namedFoo]), $namedBar], [new New_(new Name('test'), [$namedFoo, $unpack]), null], [new NullsafeMethodCall(new Variable('this'), 'test', [$foo]), null], [new NullsafeMethodCall(new Variable('this'), 'test', [$namedFoo]), null], [new NullsafeMethodCall(new Variable('this'), 'test', [$foo, $bar]), $bar], [new NullsafeMethodCall(new Variable('this'), 'test', [$namedBar]), $namedBar], [new NullsafeMethodCall(new Variable('this'), 'test', [$namedFoo, $namedBar]), $namedBar], [new NullsafeMethodCall(new Variable('this'), 'test', [$namedBar, $namedFoo]), $namedBar], [new NullsafeMethodCall(new Variable('this'), 'test', [$namedFoo, $unpack]), null], // This is not legal code, but accepted by the parser. [new New_(new Name('Test'), $callableArgs), null], [new NullsafeMethodCall(new Variable('this'), 'test', $callableArgs), null], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Scalar/NumberTest.php
test/PhpParser/Node/Scalar/NumberTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Scalar; use PhpParser\Node\Stmt\Echo_; use PhpParser\ParserFactory; class NumberTest extends \PHPUnit\Framework\TestCase { public function testRawValue(): void { $parser = (new ParserFactory())->createForNewestSupportedVersion(); $nodes = $parser->parse('<?php echo 1_234;'); $echo = $nodes[0]; $this->assertInstanceOf(Echo_::class, $echo); /** @var Echo_ $echo */ $lnumber = $echo->exprs[0]; $this->assertInstanceOf(Int_::class, $lnumber); /** @var Int_ $lnumber */ $this->assertSame(1234, $lnumber->value); $this->assertSame('1_234', $lnumber->getAttribute('rawValue')); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Scalar/MagicConstTest.php
test/PhpParser/Node/Scalar/MagicConstTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Scalar; class MagicConstTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider provideTestGetName */ public function testGetName(MagicConst $magicConst, $name): void { $this->assertSame($name, $magicConst->getName()); } public static function provideTestGetName() { return [ [new MagicConst\Class_(), '__CLASS__'], [new MagicConst\Dir(), '__DIR__'], [new MagicConst\File(), '__FILE__'], [new MagicConst\Function_(), '__FUNCTION__'], [new MagicConst\Line(), '__LINE__'], [new MagicConst\Method(), '__METHOD__'], [new MagicConst\Namespace_(), '__NAMESPACE__'], [new MagicConst\Trait_(), '__TRAIT__'], ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Scalar/StringTest.php
test/PhpParser/Node/Scalar/StringTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Scalar; use PhpParser\Node\Stmt\Echo_; use PhpParser\ParserFactory; class StringTest extends \PHPUnit\Framework\TestCase { public function testRawValue(): void { $parser = (new ParserFactory())->createForNewestSupportedVersion(); $nodes = $parser->parse('<?php echo "sequence \x41";'); $echo = $nodes[0]; $this->assertInstanceOf(Echo_::class, $echo); /** @var Echo_ $echo */ $string = $echo->exprs[0]; $this->assertInstanceOf(String_::class, $string); /** @var String_ $string */ $this->assertSame('sequence A', $string->value); $this->assertSame('"sequence \\x41"', $string->getAttribute('rawValue')); } /** * @dataProvider provideTestParseEscapeSequences */ public function testParseEscapeSequences($expected, $string, $quote): void { $this->assertSame( $expected, String_::parseEscapeSequences($string, $quote) ); } /** * @dataProvider provideTestParse */ public function testCreate($expected, $string): void { $this->assertSame( $expected, String_::parse($string) ); } public static function provideTestParseEscapeSequences() { return [ ['"', '\\"', '"'], ['\\"', '\\"', '`'], ['\\"\\`', '\\"\\`', null], ["\\\$\n\r\t\f\v", '\\\\\$\n\r\t\f\v', null], ["\x1B", '\e', null], [chr(255), '\xFF', null], [chr(255), '\377', null], [chr(0), '\400', null], ["\0", '\0', null], ['\xFF', '\\\\xFF', null], ]; } public static function provideTestParse() { $tests = [ ['A', '\'A\''], ['A', 'b\'A\''], ['A', '"A"'], ['A', 'b"A"'], ['\\', '\'\\\\\''], ['\'', '\'\\\'\''], ]; foreach (self::provideTestParseEscapeSequences() as $i => $test) { // skip second and third tests, they aren't for double quotes if ($i !== 1 && $i !== 2) { $tests[] = [$test[0], '"' . $test[1] . '"']; } } return $tests; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Node/Scalar/DNumberTest.php
test/PhpParser/Node/Scalar/DNumberTest.php
<?php declare(strict_types=1); namespace PhpParser\Node\Scalar; use PhpParser\Node\Stmt\Echo_; use PhpParser\ParserFactory; class DNumberTest extends \PHPUnit\Framework\TestCase { public function testRawValue(): void { $parser = (new ParserFactory())->createForNewestSupportedVersion(); $nodes = $parser->parse('<?php echo 1_234.56;'); $echo = $nodes[0]; $this->assertInstanceOf(Echo_::class, $echo); /** @var Echo_ $echo */ $dnumber = $echo->exprs[0]; $this->assertInstanceOf(Float_::class, $dnumber); /** @var Float_ $dnumber */ $this->assertSame(1234.56, $dnumber->value); $this->assertSame('1_234.56', $dnumber->getAttribute('rawValue')); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Parser/Php7Test.php
test/PhpParser/Parser/Php7Test.php
<?php declare(strict_types=1); namespace PhpParser\Parser; use PhpParser\Lexer; use PhpParser\ParserTestAbstract; class Php7Test extends ParserTestAbstract { protected function getParser(Lexer $lexer) { return new Php7($lexer); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Parser/Php8Test.php
test/PhpParser/Parser/Php8Test.php
<?php declare(strict_types=1); namespace PhpParser\Parser; use PhpParser\Lexer; use PhpParser\ParserTestAbstract; class Php8Test extends ParserTestAbstract { protected function getParser(Lexer $lexer) { return new Php8($lexer); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/ErrorHandler/ThrowingTest.php
test/PhpParser/ErrorHandler/ThrowingTest.php
<?php declare(strict_types=1); namespace PhpParser\ErrorHandler; use PhpParser\Error; class ThrowingTest extends \PHPUnit\Framework\TestCase { public function testHandleError(): void { $this->expectException(Error::class); $this->expectExceptionMessage('Test'); $errorHandler = new Throwing(); $errorHandler->handleError(new Error('Test')); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/ErrorHandler/CollectingTest.php
test/PhpParser/ErrorHandler/CollectingTest.php
<?php declare(strict_types=1); namespace PhpParser\ErrorHandler; use PhpParser\Error; class CollectingTest extends \PHPUnit\Framework\TestCase { public function testHandleError(): void { $errorHandler = new Collecting(); $this->assertFalse($errorHandler->hasErrors()); $this->assertEmpty($errorHandler->getErrors()); $errorHandler->handleError($e1 = new Error('Test 1')); $errorHandler->handleError($e2 = new Error('Test 2')); $this->assertTrue($errorHandler->hasErrors()); $this->assertSame([$e1, $e2], $errorHandler->getErrors()); $errorHandler->clearErrors(); $this->assertFalse($errorHandler->hasErrors()); $this->assertEmpty($errorHandler->getErrors()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test/PhpParser/Internal/DifferTest.php
test/PhpParser/Internal/DifferTest.php
<?php declare(strict_types=1); namespace PhpParser\Internal; class DifferTest extends \PHPUnit\Framework\TestCase { private function formatDiffString(array $diff) { $diffStr = ''; foreach ($diff as $diffElem) { switch ($diffElem->type) { case DiffElem::TYPE_KEEP: $diffStr .= $diffElem->old; break; case DiffElem::TYPE_REMOVE: $diffStr .= '-' . $diffElem->old; break; case DiffElem::TYPE_ADD: $diffStr .= '+' . $diffElem->new; break; case DiffElem::TYPE_REPLACE: $diffStr .= '/' . $diffElem->old . $diffElem->new; break; default: assert(false); break; } } return $diffStr; } /** @dataProvider provideTestDiff */ public function testDiff($oldStr, $newStr, $expectedDiffStr): void { $differ = new Differ(function ($a, $b) { return $a === $b; }); $diff = $differ->diff(str_split($oldStr), str_split($newStr)); $this->assertSame($expectedDiffStr, $this->formatDiffString($diff)); } public static function provideTestDiff() { return [ ['abc', 'abc', 'abc'], ['abc', 'abcdef', 'abc+d+e+f'], ['abcdef', 'abc', 'abc-d-e-f'], ['abcdef', 'abcxyzdef', 'abc+x+y+zdef'], ['axyzb', 'ab', 'a-x-y-zb'], ['abcdef', 'abxyef', 'ab-c-d+x+yef'], ['abcdef', 'cdefab', '-a-bcdef+a+b'], ]; } /** @dataProvider provideTestDiffWithReplacements */ public function testDiffWithReplacements($oldStr, $newStr, $expectedDiffStr): void { $differ = new Differ(function ($a, $b) { return $a === $b; }); $diff = $differ->diffWithReplacements(str_split($oldStr), str_split($newStr)); $this->assertSame($expectedDiffStr, $this->formatDiffString($diff)); } public static function provideTestDiffWithReplacements() { return [ ['abcde', 'axyze', 'a/bx/cy/dze'], ['abcde', 'xbcdy', '/axbcd/ey'], ['abcde', 'axye', 'a-b-c-d+x+ye'], ['abcde', 'axyzue', 'a-b-c-d+x+y+z+ue'], ]; } public function testNonContiguousIndices(): void { $differ = new Differ(function ($a, $b) { return $a === $b; }); $diff = $differ->diff([0 => 'a', 2 => 'b'], [0 => 'a', 3 => 'b']); $this->assertEquals([ new DiffElem(DiffElem::TYPE_KEEP, 'a', 'a'), new DiffElem(DiffElem::TYPE_KEEP, 'b', 'b'), ], $diff); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/ParserFactory.php
lib/PhpParser/ParserFactory.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Parser\Php7; use PhpParser\Parser\Php8; class ParserFactory { /** * Create a parser targeting the given version on a best-effort basis. The parser will generally * accept code for the newest supported version, but will try to accommodate code that becomes * invalid in newer versions or changes in interpretation. */ public function createForVersion(PhpVersion $version): Parser { if ($version->isHostVersion()) { $lexer = new Lexer(); } else { $lexer = new Lexer\Emulative($version); } if ($version->id >= 80000) { return new Php8($lexer, $version); } return new Php7($lexer, $version); } /** * Create a parser targeting the newest version supported by this library. Code for older * versions will be accepted if there have been no relevant backwards-compatibility breaks in * PHP. */ public function createForNewestSupportedVersion(): Parser { return $this->createForVersion(PhpVersion::getNewestSupported()); } /** * Create a parser targeting the host PHP version, that is the PHP version we're currently * running on. This parser will not use any token emulation. */ public function createForHostVersion(): Parser { return $this->createForVersion(PhpVersion::getHostVersion()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/BuilderFactory.php
lib/PhpParser/BuilderFactory.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Arg; use PhpParser\Node\Expr; use PhpParser\Node\Expr\BinaryOp\Concat; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt\Use_; class BuilderFactory { /** * Creates an attribute node. * * @param string|Name $name Name of the attribute * @param array $args Attribute named arguments */ public function attribute($name, array $args = []): Node\Attribute { return new Node\Attribute( BuilderHelpers::normalizeName($name), $this->args($args) ); } /** * Creates a namespace builder. * * @param null|string|Node\Name $name Name of the namespace * * @return Builder\Namespace_ The created namespace builder */ public function namespace($name): Builder\Namespace_ { return new Builder\Namespace_($name); } /** * Creates a class builder. * * @param string $name Name of the class * * @return Builder\Class_ The created class builder */ public function class(string $name): Builder\Class_ { return new Builder\Class_($name); } /** * Creates an interface builder. * * @param string $name Name of the interface * * @return Builder\Interface_ The created interface builder */ public function interface(string $name): Builder\Interface_ { return new Builder\Interface_($name); } /** * Creates a trait builder. * * @param string $name Name of the trait * * @return Builder\Trait_ The created trait builder */ public function trait(string $name): Builder\Trait_ { return new Builder\Trait_($name); } /** * Creates an enum builder. * * @param string $name Name of the enum * * @return Builder\Enum_ The created enum builder */ public function enum(string $name): Builder\Enum_ { return new Builder\Enum_($name); } /** * Creates a trait use builder. * * @param Node\Name|string ...$traits Trait names * * @return Builder\TraitUse The created trait use builder */ public function useTrait(...$traits): Builder\TraitUse { return new Builder\TraitUse(...$traits); } /** * Creates a trait use adaptation builder. * * @param Node\Name|string|null $trait Trait name * @param Node\Identifier|string $method Method name * * @return Builder\TraitUseAdaptation The created trait use adaptation builder */ public function traitUseAdaptation($trait, $method = null): Builder\TraitUseAdaptation { if ($method === null) { $method = $trait; $trait = null; } return new Builder\TraitUseAdaptation($trait, $method); } /** * Creates a method builder. * * @param string $name Name of the method * * @return Builder\Method The created method builder */ public function method(string $name): Builder\Method { return new Builder\Method($name); } /** * Creates a parameter builder. * * @param string $name Name of the parameter * * @return Builder\Param The created parameter builder */ public function param(string $name): Builder\Param { return new Builder\Param($name); } /** * Creates a property builder. * * @param string $name Name of the property * * @return Builder\Property The created property builder */ public function property(string $name): Builder\Property { return new Builder\Property($name); } /** * Creates a function builder. * * @param string $name Name of the function * * @return Builder\Function_ The created function builder */ public function function(string $name): Builder\Function_ { return new Builder\Function_($name); } /** * Creates a namespace/class use builder. * * @param Node\Name|string $name Name of the entity (namespace or class) to alias * * @return Builder\Use_ The created use builder */ public function use($name): Builder\Use_ { return new Builder\Use_($name, Use_::TYPE_NORMAL); } /** * Creates a function use builder. * * @param Node\Name|string $name Name of the function to alias * * @return Builder\Use_ The created use function builder */ public function useFunction($name): Builder\Use_ { return new Builder\Use_($name, Use_::TYPE_FUNCTION); } /** * Creates a constant use builder. * * @param Node\Name|string $name Name of the const to alias * * @return Builder\Use_ The created use const builder */ public function useConst($name): Builder\Use_ { return new Builder\Use_($name, Use_::TYPE_CONSTANT); } /** * Creates a class constant builder. * * @param string|Identifier $name Name * @param Node\Expr|bool|null|int|float|string|array $value Value * * @return Builder\ClassConst The created use const builder */ public function classConst($name, $value): Builder\ClassConst { return new Builder\ClassConst($name, $value); } /** * Creates an enum case builder. * * @param string|Identifier $name Name * * @return Builder\EnumCase The created use const builder */ public function enumCase($name): Builder\EnumCase { return new Builder\EnumCase($name); } /** * Creates node a for a literal value. * * @param Expr|bool|null|int|float|string|array|\UnitEnum $value $value */ public function val($value): Expr { return BuilderHelpers::normalizeValue($value); } /** * Creates variable node. * * @param string|Expr $name Name */ public function var($name): Expr\Variable { if (!\is_string($name) && !$name instanceof Expr) { throw new \LogicException('Variable name must be string or Expr'); } return new Expr\Variable($name); } /** * Normalizes an argument list. * * Creates Arg nodes for all arguments and converts literal values to expressions. * * @param array $args List of arguments to normalize * * @return list<Arg> */ public function args(array $args): array { $normalizedArgs = []; foreach ($args as $key => $arg) { if (!($arg instanceof Arg)) { $arg = new Arg(BuilderHelpers::normalizeValue($arg)); } if (\is_string($key)) { $arg->name = BuilderHelpers::normalizeIdentifier($key); } $normalizedArgs[] = $arg; } return $normalizedArgs; } /** * Creates a function call node. * * @param string|Name|Expr $name Function name * @param array $args Function arguments */ public function funcCall($name, array $args = []): Expr\FuncCall { return new Expr\FuncCall( BuilderHelpers::normalizeNameOrExpr($name), $this->args($args) ); } /** * Creates a method call node. * * @param Expr $var Variable the method is called on * @param string|Identifier|Expr $name Method name * @param array $args Method arguments */ public function methodCall(Expr $var, $name, array $args = []): Expr\MethodCall { return new Expr\MethodCall( $var, BuilderHelpers::normalizeIdentifierOrExpr($name), $this->args($args) ); } /** * Creates a static method call node. * * @param string|Name|Expr $class Class name * @param string|Identifier|Expr $name Method name * @param array $args Method arguments */ public function staticCall($class, $name, array $args = []): Expr\StaticCall { return new Expr\StaticCall( BuilderHelpers::normalizeNameOrExpr($class), BuilderHelpers::normalizeIdentifierOrExpr($name), $this->args($args) ); } /** * Creates an object creation node. * * @param string|Name|Expr $class Class name * @param array $args Constructor arguments */ public function new($class, array $args = []): Expr\New_ { return new Expr\New_( BuilderHelpers::normalizeNameOrExpr($class), $this->args($args) ); } /** * Creates a constant fetch node. * * @param string|Name $name Constant name */ public function constFetch($name): Expr\ConstFetch { return new Expr\ConstFetch(BuilderHelpers::normalizeName($name)); } /** * Creates a property fetch node. * * @param Expr $var Variable holding object * @param string|Identifier|Expr $name Property name */ public function propertyFetch(Expr $var, $name): Expr\PropertyFetch { return new Expr\PropertyFetch($var, BuilderHelpers::normalizeIdentifierOrExpr($name)); } /** * Creates a class constant fetch node. * * @param string|Name|Expr $class Class name * @param string|Identifier|Expr $name Constant name */ public function classConstFetch($class, $name): Expr\ClassConstFetch { return new Expr\ClassConstFetch( BuilderHelpers::normalizeNameOrExpr($class), BuilderHelpers::normalizeIdentifierOrExpr($name) ); } /** * Creates nested Concat nodes from a list of expressions. * * @param Expr|string ...$exprs Expressions or literal strings */ public function concat(...$exprs): Concat { $numExprs = count($exprs); if ($numExprs < 2) { throw new \LogicException('Expected at least two expressions'); } $lastConcat = $this->normalizeStringExpr($exprs[0]); for ($i = 1; $i < $numExprs; $i++) { $lastConcat = new Concat($lastConcat, $this->normalizeStringExpr($exprs[$i])); } return $lastConcat; } /** * @param string|Expr $expr */ private function normalizeStringExpr($expr): Expr { if ($expr instanceof Expr) { return $expr; } if (\is_string($expr)) { return new String_($expr); } throw new \LogicException('Expected string or Expr'); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Modifiers.php
lib/PhpParser/Modifiers.php
<?php declare(strict_types=1); namespace PhpParser; /** * Modifiers used (as a bit mask) by various flags subnodes, for example on classes, functions, * properties and constants. */ final class Modifiers { public const PUBLIC = 1; public const PROTECTED = 2; public const PRIVATE = 4; public const STATIC = 8; public const ABSTRACT = 16; public const FINAL = 32; public const READONLY = 64; public const PUBLIC_SET = 128; public const PROTECTED_SET = 256; public const PRIVATE_SET = 512; public const VISIBILITY_MASK = self::PUBLIC | self::PROTECTED | self::PRIVATE; public const VISIBILITY_SET_MASK = self::PUBLIC_SET | self::PROTECTED_SET | self::PRIVATE_SET; private const TO_STRING_MAP = [ self::PUBLIC => 'public', self::PROTECTED => 'protected', self::PRIVATE => 'private', self::STATIC => 'static', self::ABSTRACT => 'abstract', self::FINAL => 'final', self::READONLY => 'readonly', self::PUBLIC_SET => 'public(set)', self::PROTECTED_SET => 'protected(set)', self::PRIVATE_SET => 'private(set)', ]; public static function toString(int $modifier): string { if (!isset(self::TO_STRING_MAP[$modifier])) { throw new \InvalidArgumentException("Unknown modifier $modifier"); } return self::TO_STRING_MAP[$modifier]; } private static function isValidModifier(int $modifier): bool { $isPow2 = ($modifier & ($modifier - 1)) == 0 && $modifier != 0; return $isPow2 && $modifier <= self::PRIVATE_SET; } /** * @internal */ public static function verifyClassModifier(int $a, int $b): void { assert(self::isValidModifier($b)); if (($a & $b) != 0) { throw new Error( 'Multiple ' . self::toString($b) . ' modifiers are not allowed'); } if ($a & 48 && $b & 48) { throw new Error('Cannot use the final modifier on an abstract class'); } } /** * @internal */ public static function verifyModifier(int $a, int $b): void { assert(self::isValidModifier($b)); if (($a & Modifiers::VISIBILITY_MASK && $b & Modifiers::VISIBILITY_MASK) || ($a & Modifiers::VISIBILITY_SET_MASK && $b & Modifiers::VISIBILITY_SET_MASK) ) { throw new Error('Multiple access type modifiers are not allowed'); } if (($a & $b) != 0) { throw new Error( 'Multiple ' . self::toString($b) . ' modifiers are not allowed'); } if ($a & 48 && $b & 48) { throw new Error('Cannot use the final modifier on an abstract class member'); } } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Token.php
lib/PhpParser/Token.php
<?php declare(strict_types=1); namespace PhpParser; /** * A PHP token. On PHP 8.0 this extends from PhpToken. */ class Token extends Internal\TokenPolyfill { /** Get (exclusive) zero-based end position of the token. */ public function getEndPos(): int { return $this->pos + \strlen($this->text); } /** Get 1-based end line number of the token. */ public function getEndLine(): int { return $this->line + \substr_count($this->text, "\n"); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/BuilderHelpers.php
lib/PhpParser/BuilderHelpers.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\ComplexType; use PhpParser\Node\Expr; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\NullableType; use PhpParser\Node\Scalar; use PhpParser\Node\Stmt; /** * This class defines helpers used in the implementation of builders. Don't use it directly. * * @internal */ final class BuilderHelpers { /** * Normalizes a node: Converts builder objects to nodes. * * @param Node|Builder $node The node to normalize * * @return Node The normalized node */ public static function normalizeNode($node): Node { if ($node instanceof Builder) { return $node->getNode(); } if ($node instanceof Node) { return $node; } throw new \LogicException('Expected node or builder object'); } /** * Normalizes a node to a statement. * * Expressions are wrapped in a Stmt\Expression node. * * @param Node|Builder $node The node to normalize * * @return Stmt The normalized statement node */ public static function normalizeStmt($node): Stmt { $node = self::normalizeNode($node); if ($node instanceof Stmt) { return $node; } if ($node instanceof Expr) { return new Stmt\Expression($node); } throw new \LogicException('Expected statement or expression node'); } /** * Normalizes strings to Identifier. * * @param string|Identifier $name The identifier to normalize * * @return Identifier The normalized identifier */ public static function normalizeIdentifier($name): Identifier { if ($name instanceof Identifier) { return $name; } if (\is_string($name)) { return new Identifier($name); } throw new \LogicException('Expected string or instance of Node\Identifier'); } /** * Normalizes strings to Identifier, also allowing expressions. * * @param string|Identifier|Expr $name The identifier to normalize * * @return Identifier|Expr The normalized identifier or expression */ public static function normalizeIdentifierOrExpr($name) { if ($name instanceof Identifier || $name instanceof Expr) { return $name; } if (\is_string($name)) { return new Identifier($name); } throw new \LogicException('Expected string or instance of Node\Identifier or Node\Expr'); } /** * Normalizes a name: Converts string names to Name nodes. * * @param Name|string $name The name to normalize * * @return Name The normalized name */ public static function normalizeName($name): Name { if ($name instanceof Name) { return $name; } if (is_string($name)) { if (!$name) { throw new \LogicException('Name cannot be empty'); } if ($name[0] === '\\') { return new Name\FullyQualified(substr($name, 1)); } if (0 === strpos($name, 'namespace\\')) { return new Name\Relative(substr($name, strlen('namespace\\'))); } return new Name($name); } throw new \LogicException('Name must be a string or an instance of Node\Name'); } /** * Normalizes a name: Converts string names to Name nodes, while also allowing expressions. * * @param Expr|Name|string $name The name to normalize * * @return Name|Expr The normalized name or expression */ public static function normalizeNameOrExpr($name) { if ($name instanceof Expr) { return $name; } if (!is_string($name) && !($name instanceof Name)) { throw new \LogicException( 'Name must be a string or an instance of Node\Name or Node\Expr' ); } return self::normalizeName($name); } /** * Normalizes a type: Converts plain-text type names into proper AST representation. * * In particular, builtin types become Identifiers, custom types become Names and nullables * are wrapped in NullableType nodes. * * @param string|Name|Identifier|ComplexType $type The type to normalize * * @return Name|Identifier|ComplexType The normalized type */ public static function normalizeType($type) { if (!is_string($type)) { if ( !$type instanceof Name && !$type instanceof Identifier && !$type instanceof ComplexType ) { throw new \LogicException( 'Type must be a string, or an instance of Name, Identifier or ComplexType' ); } return $type; } $nullable = false; if (strlen($type) > 0 && $type[0] === '?') { $nullable = true; $type = substr($type, 1); } $builtinTypes = [ 'array', 'callable', 'bool', 'int', 'float', 'string', 'iterable', 'void', 'object', 'null', 'false', 'mixed', 'never', 'true', ]; $lowerType = strtolower($type); if (in_array($lowerType, $builtinTypes)) { $type = new Identifier($lowerType); } else { $type = self::normalizeName($type); } $notNullableTypes = [ 'void', 'mixed', 'never', ]; if ($nullable && in_array((string) $type, $notNullableTypes)) { throw new \LogicException(sprintf('%s type cannot be nullable', $type)); } return $nullable ? new NullableType($type) : $type; } /** * Normalizes a value: Converts nulls, booleans, integers, * floats, strings and arrays into their respective nodes * * @param Node\Expr|bool|null|int|float|string|array|\UnitEnum $value The value to normalize * * @return Expr The normalized value */ public static function normalizeValue($value): Expr { if ($value instanceof Node\Expr) { return $value; } if (is_null($value)) { return new Expr\ConstFetch( new Name('null') ); } if (is_bool($value)) { return new Expr\ConstFetch( new Name($value ? 'true' : 'false') ); } if (is_int($value)) { return new Scalar\Int_($value); } if (is_float($value)) { return new Scalar\Float_($value); } if (is_string($value)) { return new Scalar\String_($value); } if (is_array($value)) { $items = []; $lastKey = -1; foreach ($value as $itemKey => $itemValue) { // for consecutive, numeric keys don't generate keys if (null !== $lastKey && ++$lastKey === $itemKey) { $items[] = new Node\ArrayItem( self::normalizeValue($itemValue) ); } else { $lastKey = null; $items[] = new Node\ArrayItem( self::normalizeValue($itemValue), self::normalizeValue($itemKey) ); } } return new Expr\Array_($items); } if ($value instanceof \UnitEnum) { return new Expr\ClassConstFetch(new FullyQualified(\get_class($value)), new Identifier($value->name)); } throw new \LogicException('Invalid value'); } /** * Normalizes a doc comment: Converts plain strings to PhpParser\Comment\Doc. * * @param Comment\Doc|string $docComment The doc comment to normalize * * @return Comment\Doc The normalized doc comment */ public static function normalizeDocComment($docComment): Comment\Doc { if ($docComment instanceof Comment\Doc) { return $docComment; } if (is_string($docComment)) { return new Comment\Doc($docComment); } throw new \LogicException('Doc comment must be a string or an instance of PhpParser\Comment\Doc'); } /** * Normalizes a attribute: Converts attribute to the Attribute Group if needed. * * @param Node\Attribute|Node\AttributeGroup $attribute * * @return Node\AttributeGroup The Attribute Group */ public static function normalizeAttribute($attribute): Node\AttributeGroup { if ($attribute instanceof Node\AttributeGroup) { return $attribute; } if (!($attribute instanceof Node\Attribute)) { throw new \LogicException('Attribute must be an instance of PhpParser\Node\Attribute or PhpParser\Node\AttributeGroup'); } return new Node\AttributeGroup([$attribute]); } /** * Adds a modifier and returns new modifier bitmask. * * @param int $modifiers Existing modifiers * @param int $modifier Modifier to set * * @return int New modifiers */ public static function addModifier(int $modifiers, int $modifier): int { Modifiers::verifyModifier($modifiers, $modifier); return $modifiers | $modifier; } /** * Adds a modifier and returns new modifier bitmask. * @return int New modifiers */ public static function addClassModifier(int $existingModifiers, int $modifierToSet): int { Modifiers::verifyClassModifier($existingModifiers, $modifierToSet); return $existingModifiers | $modifierToSet; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Lexer.php
lib/PhpParser/Lexer.php
<?php declare(strict_types=1); namespace PhpParser; require __DIR__ . '/compatibility_tokens.php'; class Lexer { /** * Tokenize the provided source code. * * The token array is in the same format as provided by the PhpToken::tokenize() method in * PHP 8.0. The tokens are instances of PhpParser\Token, to abstract over a polyfill * implementation in earlier PHP version. * * The token array is terminated by a sentinel token with token ID 0. * The token array does not discard any tokens (i.e. whitespace and comments are included). * The token position attributes are against this token array. * * @param string $code The source code to tokenize. * @param ErrorHandler|null $errorHandler Error handler to use for lexing errors. Defaults to * ErrorHandler\Throwing. * @return Token[] Tokens */ public function tokenize(string $code, ?ErrorHandler $errorHandler = null): array { if (null === $errorHandler) { $errorHandler = new ErrorHandler\Throwing(); } $scream = ini_set('xdebug.scream', '0'); $tokens = @Token::tokenize($code); $this->postprocessTokens($tokens, $errorHandler); if (false !== $scream) { ini_set('xdebug.scream', $scream); } return $tokens; } private function handleInvalidCharacter(Token $token, ErrorHandler $errorHandler): void { $chr = $token->text; if ($chr === "\0") { // PHP cuts error message after null byte, so need special case $errorMsg = 'Unexpected null byte'; } else { $errorMsg = sprintf( 'Unexpected character "%s" (ASCII %d)', $chr, ord($chr) ); } $errorHandler->handleError(new Error($errorMsg, [ 'startLine' => $token->line, 'endLine' => $token->line, 'startFilePos' => $token->pos, 'endFilePos' => $token->pos, ])); } private function isUnterminatedComment(Token $token): bool { return $token->is([\T_COMMENT, \T_DOC_COMMENT]) && substr($token->text, 0, 2) === '/*' && substr($token->text, -2) !== '*/'; } /** * @param list<Token> $tokens */ protected function postprocessTokens(array &$tokens, ErrorHandler $errorHandler): void { // This function reports errors (bad characters and unterminated comments) in the token // array, and performs certain canonicalizations: // * Use PHP 8.1 T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG and // T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG tokens used to disambiguate intersection types. // * Add a sentinel token with ID 0. $numTokens = \count($tokens); if ($numTokens === 0) { // Empty input edge case: Just add the sentinel token. $tokens[] = new Token(0, "\0", 1, 0); return; } for ($i = 0; $i < $numTokens; $i++) { $token = $tokens[$i]; if ($token->id === \T_BAD_CHARACTER) { $this->handleInvalidCharacter($token, $errorHandler); } if ($token->id === \ord('&')) { $next = $i + 1; while (isset($tokens[$next]) && $tokens[$next]->id === \T_WHITESPACE) { $next++; } $followedByVarOrVarArg = isset($tokens[$next]) && $tokens[$next]->is([\T_VARIABLE, \T_ELLIPSIS]); $token->id = $followedByVarOrVarArg ? \T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG : \T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG; } } // Check for unterminated comment $lastToken = $tokens[$numTokens - 1]; if ($this->isUnterminatedComment($lastToken)) { $errorHandler->handleError(new Error('Unterminated comment', [ 'startLine' => $lastToken->line, 'endLine' => $lastToken->getEndLine(), 'startFilePos' => $lastToken->pos, 'endFilePos' => $lastToken->getEndPos(), ])); } // Add sentinel token. $tokens[] = new Token(0, "\0", $lastToken->getEndLine(), $lastToken->getEndPos()); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/PrettyPrinterAbstract.php
lib/PhpParser/PrettyPrinterAbstract.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Internal\DiffElem; use PhpParser\Internal\Differ; use PhpParser\Internal\PrintableNewAnonClassNode; use PhpParser\Internal\TokenStream; use PhpParser\Node\AttributeGroup; use PhpParser\Node\Expr; use PhpParser\Node\Expr\AssignOp; use PhpParser\Node\Expr\BinaryOp; use PhpParser\Node\Expr\Cast; use PhpParser\Node\IntersectionType; use PhpParser\Node\MatchArm; use PhpParser\Node\Param; use PhpParser\Node\PropertyHook; use PhpParser\Node\Scalar; use PhpParser\Node\Stmt; use PhpParser\Node\UnionType; abstract class PrettyPrinterAbstract implements PrettyPrinter { protected const FIXUP_PREC_LEFT = 0; // LHS operand affected by precedence protected const FIXUP_PREC_RIGHT = 1; // RHS operand affected by precedence protected const FIXUP_PREC_UNARY = 2; // Only operand affected by precedence protected const FIXUP_CALL_LHS = 3; // LHS of call protected const FIXUP_DEREF_LHS = 4; // LHS of dereferencing operation protected const FIXUP_STATIC_DEREF_LHS = 5; // LHS of static dereferencing operation protected const FIXUP_BRACED_NAME = 6; // Name operand that may require bracing protected const FIXUP_VAR_BRACED_NAME = 7; // Name operand that may require ${} bracing protected const FIXUP_ENCAPSED = 8; // Encapsed string part protected const FIXUP_NEW = 9; // New/instanceof operand protected const MAX_PRECEDENCE = 1000; /** @var array<class-string, array{int, int, int}> */ protected array $precedenceMap = [ // [precedence, precedenceLHS, precedenceRHS] // Where the latter two are the precedences to use for the LHS and RHS of a binary operator, // where 1 is added to one of the sides depending on associativity. This information is not // used for unary operators and set to -1. Expr\Clone_::class => [-10, 0, 1], BinaryOp\Pow::class => [ 0, 0, 1], Expr\BitwiseNot::class => [ 10, -1, -1], Expr\UnaryPlus::class => [ 10, -1, -1], Expr\UnaryMinus::class => [ 10, -1, -1], Cast\Int_::class => [ 10, -1, -1], Cast\Double::class => [ 10, -1, -1], Cast\String_::class => [ 10, -1, -1], Cast\Array_::class => [ 10, -1, -1], Cast\Object_::class => [ 10, -1, -1], Cast\Bool_::class => [ 10, -1, -1], Cast\Unset_::class => [ 10, -1, -1], Expr\ErrorSuppress::class => [ 10, -1, -1], Expr\Instanceof_::class => [ 20, -1, -1], Expr\BooleanNot::class => [ 30, -1, -1], BinaryOp\Mul::class => [ 40, 41, 40], BinaryOp\Div::class => [ 40, 41, 40], BinaryOp\Mod::class => [ 40, 41, 40], BinaryOp\Plus::class => [ 50, 51, 50], BinaryOp\Minus::class => [ 50, 51, 50], // FIXME: This precedence is incorrect for PHP 8. BinaryOp\Concat::class => [ 50, 51, 50], BinaryOp\ShiftLeft::class => [ 60, 61, 60], BinaryOp\ShiftRight::class => [ 60, 61, 60], BinaryOp\Pipe::class => [ 65, 66, 65], BinaryOp\Smaller::class => [ 70, 70, 70], BinaryOp\SmallerOrEqual::class => [ 70, 70, 70], BinaryOp\Greater::class => [ 70, 70, 70], BinaryOp\GreaterOrEqual::class => [ 70, 70, 70], BinaryOp\Equal::class => [ 80, 80, 80], BinaryOp\NotEqual::class => [ 80, 80, 80], BinaryOp\Identical::class => [ 80, 80, 80], BinaryOp\NotIdentical::class => [ 80, 80, 80], BinaryOp\Spaceship::class => [ 80, 80, 80], BinaryOp\BitwiseAnd::class => [ 90, 91, 90], BinaryOp\BitwiseXor::class => [100, 101, 100], BinaryOp\BitwiseOr::class => [110, 111, 110], BinaryOp\BooleanAnd::class => [120, 121, 120], BinaryOp\BooleanOr::class => [130, 131, 130], BinaryOp\Coalesce::class => [140, 140, 141], Expr\Ternary::class => [150, 150, 150], Expr\Assign::class => [160, -1, -1], Expr\AssignRef::class => [160, -1, -1], AssignOp\Plus::class => [160, -1, -1], AssignOp\Minus::class => [160, -1, -1], AssignOp\Mul::class => [160, -1, -1], AssignOp\Div::class => [160, -1, -1], AssignOp\Concat::class => [160, -1, -1], AssignOp\Mod::class => [160, -1, -1], AssignOp\BitwiseAnd::class => [160, -1, -1], AssignOp\BitwiseOr::class => [160, -1, -1], AssignOp\BitwiseXor::class => [160, -1, -1], AssignOp\ShiftLeft::class => [160, -1, -1], AssignOp\ShiftRight::class => [160, -1, -1], AssignOp\Pow::class => [160, -1, -1], AssignOp\Coalesce::class => [160, -1, -1], Expr\YieldFrom::class => [170, -1, -1], Expr\Yield_::class => [175, -1, -1], Expr\Print_::class => [180, -1, -1], BinaryOp\LogicalAnd::class => [190, 191, 190], BinaryOp\LogicalXor::class => [200, 201, 200], BinaryOp\LogicalOr::class => [210, 211, 210], Expr\Include_::class => [220, -1, -1], Expr\ArrowFunction::class => [230, -1, -1], Expr\Throw_::class => [240, -1, -1], Expr\Cast\Void_::class => [250, -1, -1], ]; /** @var int Current indentation level. */ protected int $indentLevel; /** @var string String for single level of indentation */ private string $indent; /** @var int Width in spaces to indent by. */ private int $indentWidth; /** @var bool Whether to use tab indentation. */ private bool $useTabs; /** @var int Width in spaces of one tab. */ private int $tabWidth = 4; /** @var string Newline style. Does not include current indentation. */ protected string $newline; /** @var string Newline including current indentation. */ protected string $nl; /** @var string|null Token placed at end of doc string to ensure it is followed by a newline. * Null if flexible doc strings are used. */ protected ?string $docStringEndToken; /** @var bool Whether semicolon namespaces can be used (i.e. no global namespace is used) */ protected bool $canUseSemicolonNamespaces; /** @var bool Whether to use short array syntax if the node specifies no preference */ protected bool $shortArraySyntax; /** @var PhpVersion PHP version to target */ protected PhpVersion $phpVersion; /** @var TokenStream|null Original tokens for use in format-preserving pretty print */ protected ?TokenStream $origTokens; /** @var Internal\Differ<Node> Differ for node lists */ protected Differ $nodeListDiffer; /** @var array<string, bool> Map determining whether a certain character is a label character */ protected array $labelCharMap; /** * @var array<string, array<string, int>> Map from token classes and subnode names to FIXUP_* constants. * This is used during format-preserving prints to place additional parens/braces if necessary. */ protected array $fixupMap; /** * @var array<string, array{left?: int|string, right?: int|string}> Map from "{$node->getType()}->{$subNode}" * to ['left' => $l, 'right' => $r], where $l and $r specify the token type that needs to be stripped * when removing this node. */ protected array $removalMap; /** * @var array<string, array{int|string|null, bool, string|null, string|null}> Map from * "{$node->getType()}->{$subNode}" to [$find, $beforeToken, $extraLeft, $extraRight]. * $find is an optional token after which the insertion occurs. $extraLeft/Right * are optionally added before/after the main insertions. */ protected array $insertionMap; /** * @var array<string, string> Map From "{$class}->{$subNode}" to string that should be inserted * between elements of this list subnode. */ protected array $listInsertionMap; /** * @var array<string, array{int|string|null, string, string}> */ protected array $emptyListInsertionMap; /** @var array<string, array{string, int, int}> * Map from "{$class}->{$subNode}" to [$printFn, $skipToken, $findToken] where $printFn is the function to * print the modifiers, $skipToken is the token to skip at the start and $findToken is the token before which * the modifiers should be reprinted. */ protected array $modifierChangeMap; /** * Creates a pretty printer instance using the given options. * * Supported options: * * PhpVersion $phpVersion: The PHP version to target (default to PHP 7.4). This option * controls compatibility of the generated code with older PHP * versions in cases where a simple stylistic choice exists (e.g. * array() vs []). It is safe to pretty-print an AST for a newer * PHP version while specifying an older target (but the result will * of course not be compatible with the older version in that case). * * string $newline: The newline style to use. Should be "\n" (default) or "\r\n". * * string $indent: The indentation to use. Should either be all spaces or a single * tab. Defaults to four spaces (" "). * * bool $shortArraySyntax: Whether to use [] instead of array() as the default array * syntax, if the node does not specify a format. Defaults to whether * the phpVersion support short array syntax. * * @param array{ * phpVersion?: PhpVersion, newline?: string, indent?: string, shortArraySyntax?: bool * } $options Dictionary of formatting options */ public function __construct(array $options = []) { $this->phpVersion = $options['phpVersion'] ?? PhpVersion::fromComponents(7, 4); $this->newline = $options['newline'] ?? "\n"; if ($this->newline !== "\n" && $this->newline != "\r\n") { throw new \LogicException('Option "newline" must be one of "\n" or "\r\n"'); } $this->shortArraySyntax = $options['shortArraySyntax'] ?? $this->phpVersion->supportsShortArraySyntax(); $this->docStringEndToken = $this->phpVersion->supportsFlexibleHeredoc() ? null : '_DOC_STRING_END_' . mt_rand(); $this->indent = $indent = $options['indent'] ?? ' '; if ($indent === "\t") { $this->useTabs = true; $this->indentWidth = $this->tabWidth; } elseif ($indent === \str_repeat(' ', \strlen($indent))) { $this->useTabs = false; $this->indentWidth = \strlen($indent); } else { throw new \LogicException('Option "indent" must either be all spaces or a single tab'); } } /** * Reset pretty printing state. */ protected function resetState(): void { $this->indentLevel = 0; $this->nl = $this->newline; $this->origTokens = null; } /** * Set indentation level * * @param int $level Level in number of spaces */ protected function setIndentLevel(int $level): void { $this->indentLevel = $level; if ($this->useTabs) { $tabs = \intdiv($level, $this->tabWidth); $spaces = $level % $this->tabWidth; $this->nl = $this->newline . \str_repeat("\t", $tabs) . \str_repeat(' ', $spaces); } else { $this->nl = $this->newline . \str_repeat(' ', $level); } } /** * Increase indentation level. */ protected function indent(): void { $this->indentLevel += $this->indentWidth; $this->nl .= $this->indent; } /** * Decrease indentation level. */ protected function outdent(): void { assert($this->indentLevel >= $this->indentWidth); $this->setIndentLevel($this->indentLevel - $this->indentWidth); } /** * Pretty prints an array of statements. * * @param Node[] $stmts Array of statements * * @return string Pretty printed statements */ public function prettyPrint(array $stmts): string { $this->resetState(); $this->preprocessNodes($stmts); return ltrim($this->handleMagicTokens($this->pStmts($stmts, false))); } /** * Pretty prints an expression. * * @param Expr $node Expression node * * @return string Pretty printed node */ public function prettyPrintExpr(Expr $node): string { $this->resetState(); return $this->handleMagicTokens($this->p($node)); } /** * Pretty prints a file of statements (includes the opening <?php tag if it is required). * * @param Node[] $stmts Array of statements * * @return string Pretty printed statements */ public function prettyPrintFile(array $stmts): string { if (!$stmts) { return "<?php" . $this->newline . $this->newline; } $p = "<?php" . $this->newline . $this->newline . $this->prettyPrint($stmts); if ($stmts[0] instanceof Stmt\InlineHTML) { $p = preg_replace('/^<\?php\s+\?>\r?\n?/', '', $p); } if ($stmts[count($stmts) - 1] instanceof Stmt\InlineHTML) { $p = preg_replace('/<\?php$/', '', rtrim($p)); } return $p; } /** * Preprocesses the top-level nodes to initialize pretty printer state. * * @param Node[] $nodes Array of nodes */ protected function preprocessNodes(array $nodes): void { /* We can use semicolon-namespaces unless there is a global namespace declaration */ $this->canUseSemicolonNamespaces = true; foreach ($nodes as $node) { if ($node instanceof Stmt\Namespace_ && null === $node->name) { $this->canUseSemicolonNamespaces = false; break; } } } /** * Handles (and removes) doc-string-end tokens. */ protected function handleMagicTokens(string $str): string { if ($this->docStringEndToken !== null) { // Replace doc-string-end tokens with nothing or a newline $str = str_replace( $this->docStringEndToken . ';' . $this->newline, ';' . $this->newline, $str); $str = str_replace($this->docStringEndToken, $this->newline, $str); } return $str; } /** * Pretty prints an array of nodes (statements) and indents them optionally. * * @param Node[] $nodes Array of nodes * @param bool $indent Whether to indent the printed nodes * * @return string Pretty printed statements */ protected function pStmts(array $nodes, bool $indent = true): string { if ($indent) { $this->indent(); } $result = ''; foreach ($nodes as $node) { $comments = $node->getComments(); if ($comments) { $result .= $this->nl . $this->pComments($comments); if ($node instanceof Stmt\Nop) { continue; } } $result .= $this->nl . $this->p($node); } if ($indent) { $this->outdent(); } return $result; } /** * Pretty-print an infix operation while taking precedence into account. * * @param string $class Node class of operator * @param Node $leftNode Left-hand side node * @param string $operatorString String representation of the operator * @param Node $rightNode Right-hand side node * @param int $precedence Precedence of parent operator * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator * * @return string Pretty printed infix operation */ protected function pInfixOp( string $class, Node $leftNode, string $operatorString, Node $rightNode, int $precedence, int $lhsPrecedence ): string { list($opPrecedence, $newPrecedenceLHS, $newPrecedenceRHS) = $this->precedenceMap[$class]; $prefix = ''; $suffix = ''; if ($opPrecedence >= $precedence) { $prefix = '('; $suffix = ')'; $lhsPrecedence = self::MAX_PRECEDENCE; } return $prefix . $this->p($leftNode, $newPrecedenceLHS, $newPrecedenceLHS) . $operatorString . $this->p($rightNode, $newPrecedenceRHS, $lhsPrecedence) . $suffix; } /** * Pretty-print a prefix operation while taking precedence into account. * * @param string $class Node class of operator * @param string $operatorString String representation of the operator * @param Node $node Node * @param int $precedence Precedence of parent operator * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator * * @return string Pretty printed prefix operation */ protected function pPrefixOp(string $class, string $operatorString, Node $node, int $precedence, int $lhsPrecedence): string { $opPrecedence = $this->precedenceMap[$class][0]; $prefix = ''; $suffix = ''; if ($opPrecedence >= $lhsPrecedence) { $prefix = '('; $suffix = ')'; $lhsPrecedence = self::MAX_PRECEDENCE; } $printedArg = $this->p($node, $opPrecedence, $lhsPrecedence); if (($operatorString === '+' && $printedArg[0] === '+') || ($operatorString === '-' && $printedArg[0] === '-') ) { // Avoid printing +(+$a) as ++$a and similar. $printedArg = '(' . $printedArg . ')'; } return $prefix . $operatorString . $printedArg . $suffix; } /** * Pretty-print a postfix operation while taking precedence into account. * * @param string $class Node class of operator * @param string $operatorString String representation of the operator * @param Node $node Node * @param int $precedence Precedence of parent operator * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator * * @return string Pretty printed postfix operation */ protected function pPostfixOp(string $class, Node $node, string $operatorString, int $precedence, int $lhsPrecedence): string { $opPrecedence = $this->precedenceMap[$class][0]; $prefix = ''; $suffix = ''; if ($opPrecedence >= $precedence) { $prefix = '('; $suffix = ')'; $lhsPrecedence = self::MAX_PRECEDENCE; } if ($opPrecedence < $lhsPrecedence) { $lhsPrecedence = $opPrecedence; } return $prefix . $this->p($node, $opPrecedence, $lhsPrecedence) . $operatorString . $suffix; } /** * Pretty prints an array of nodes and implodes the printed values. * * @param Node[] $nodes Array of Nodes to be printed * @param string $glue Character to implode with * * @return string Imploded pretty printed nodes> $pre */ protected function pImplode(array $nodes, string $glue = ''): string { $pNodes = []; foreach ($nodes as $node) { if (null === $node) { $pNodes[] = ''; } else { $pNodes[] = $this->p($node); } } return implode($glue, $pNodes); } /** * Pretty prints an array of nodes and implodes the printed values with commas. * * @param Node[] $nodes Array of Nodes to be printed * * @return string Comma separated pretty printed nodes */ protected function pCommaSeparated(array $nodes): string { return $this->pImplode($nodes, ', '); } /** * Pretty prints a comma-separated list of nodes in multiline style, including comments. * * The result includes a leading newline and one level of indentation (same as pStmts). * * @param Node[] $nodes Array of Nodes to be printed * @param bool $trailingComma Whether to use a trailing comma * * @return string Comma separated pretty printed nodes in multiline style */ protected function pCommaSeparatedMultiline(array $nodes, bool $trailingComma): string { $this->indent(); $result = ''; $lastIdx = count($nodes) - 1; foreach ($nodes as $idx => $node) { if ($node !== null) { $comments = $node->getComments(); if ($comments) { $result .= $this->nl . $this->pComments($comments); } $result .= $this->nl . $this->p($node); } else { $result .= $this->nl; } if ($trailingComma || $idx !== $lastIdx) { $result .= ','; } } $this->outdent(); return $result; } /** * Prints reformatted text of the passed comments. * * @param Comment[] $comments List of comments * * @return string Reformatted text of comments */ protected function pComments(array $comments): string { $formattedComments = []; foreach ($comments as $comment) { $formattedComments[] = str_replace("\n", $this->nl, $comment->getReformattedText()); } return implode($this->nl, $formattedComments); } /** * Perform a format-preserving pretty print of an AST. * * The format preservation is best effort. For some changes to the AST the formatting will not * be preserved (at least not locally). * * In order to use this method a number of prerequisites must be satisfied: * * The startTokenPos and endTokenPos attributes in the lexer must be enabled. * * The CloningVisitor must be run on the AST prior to modification. * * The original tokens must be provided, using the getTokens() method on the lexer. * * @param Node[] $stmts Modified AST with links to original AST * @param Node[] $origStmts Original AST with token offset information * @param Token[] $origTokens Tokens of the original code */ public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string { $this->initializeNodeListDiffer(); $this->initializeLabelCharMap(); $this->initializeFixupMap(); $this->initializeRemovalMap(); $this->initializeInsertionMap(); $this->initializeListInsertionMap(); $this->initializeEmptyListInsertionMap(); $this->initializeModifierChangeMap(); $this->resetState(); $this->origTokens = new TokenStream($origTokens, $this->tabWidth); $this->preprocessNodes($stmts); $pos = 0; $result = $this->pArray($stmts, $origStmts, $pos, 0, 'File', 'stmts', null); if (null !== $result) { $result .= $this->origTokens->getTokenCode($pos, count($origTokens) - 1, 0); } else { // Fallback // TODO Add <?php properly $result = "<?php" . $this->newline . $this->pStmts($stmts, false); } return $this->handleMagicTokens($result); } protected function pFallback(Node $node, int $precedence, int $lhsPrecedence): string { return $this->{'p' . $node->getType()}($node, $precedence, $lhsPrecedence); } /** * Pretty prints a node. * * This method also handles formatting preservation for nodes. * * @param Node $node Node to be pretty printed * @param int $precedence Precedence of parent operator * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator * @param bool $parentFormatPreserved Whether parent node has preserved formatting * * @return string Pretty printed node */ protected function p( Node $node, int $precedence = self::MAX_PRECEDENCE, int $lhsPrecedence = self::MAX_PRECEDENCE, bool $parentFormatPreserved = false ): string { // No orig tokens means this is a normal pretty print without preservation of formatting if (!$this->origTokens) { return $this->{'p' . $node->getType()}($node, $precedence, $lhsPrecedence); } /** @var Node|null $origNode */ $origNode = $node->getAttribute('origNode'); if (null === $origNode) { return $this->pFallback($node, $precedence, $lhsPrecedence); } $class = \get_class($node); \assert($class === \get_class($origNode)); $startPos = $origNode->getStartTokenPos(); $endPos = $origNode->getEndTokenPos(); \assert($startPos >= 0 && $endPos >= 0); $fallbackNode = $node; if ($node instanceof Expr\New_ && $node->class instanceof Stmt\Class_) { // Normalize node structure of anonymous classes assert($origNode instanceof Expr\New_); $node = PrintableNewAnonClassNode::fromNewNode($node); $origNode = PrintableNewAnonClassNode::fromNewNode($origNode); $class = PrintableNewAnonClassNode::class; } // InlineHTML node does not contain closing and opening PHP tags. If the parent formatting // is not preserved, then we need to use the fallback code to make sure the tags are // printed. if ($node instanceof Stmt\InlineHTML && !$parentFormatPreserved) { return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); } $indentAdjustment = $this->indentLevel - $this->origTokens->getIndentationBefore($startPos); $type = $node->getType(); $fixupInfo = $this->fixupMap[$class] ?? null; $result = ''; $pos = $startPos; foreach ($node->getSubNodeNames() as $subNodeName) { $subNode = $node->$subNodeName; $origSubNode = $origNode->$subNodeName; if ((!$subNode instanceof Node && $subNode !== null) || (!$origSubNode instanceof Node && $origSubNode !== null) ) { if ($subNode === $origSubNode) { // Unchanged, can reuse old code continue; } if (is_array($subNode) && is_array($origSubNode)) { // Array subnode changed, we might be able to reconstruct it $listResult = $this->pArray( $subNode, $origSubNode, $pos, $indentAdjustment, $class, $subNodeName, $fixupInfo[$subNodeName] ?? null ); if (null === $listResult) { return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); } $result .= $listResult; continue; } // Check if this is a modifier change $key = $class . '->' . $subNodeName; if (!isset($this->modifierChangeMap[$key])) { return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); } [$printFn, $skipToken, $findToken] = $this->modifierChangeMap[$key]; $skipWSPos = $this->origTokens->skipRight($pos, $skipToken); $result .= $this->origTokens->getTokenCode($pos, $skipWSPos, $indentAdjustment); $result .= $this->$printFn($subNode); $pos = $this->origTokens->findRight($skipWSPos, $findToken); continue; } $extraLeft = ''; $extraRight = ''; if ($origSubNode !== null) { $subStartPos = $origSubNode->getStartTokenPos(); $subEndPos = $origSubNode->getEndTokenPos(); \assert($subStartPos >= 0 && $subEndPos >= 0); } else { if ($subNode === null) { // Both null, nothing to do continue; } // A node has been inserted, check if we have insertion information for it $key = $type . '->' . $subNodeName; if (!isset($this->insertionMap[$key])) { return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); } list($findToken, $beforeToken, $extraLeft, $extraRight) = $this->insertionMap[$key]; if (null !== $findToken) { $subStartPos = $this->origTokens->findRight($pos, $findToken) + (int) !$beforeToken; } else { $subStartPos = $pos; } if (null === $extraLeft && null !== $extraRight) { // If inserting on the right only, skipping whitespace looks better $subStartPos = $this->origTokens->skipRightWhitespace($subStartPos); } $subEndPos = $subStartPos - 1; } if (null === $subNode) { // A node has been removed, check if we have removal information for it $key = $type . '->' . $subNodeName; if (!isset($this->removalMap[$key])) { return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence); } // Adjust positions to account for additional tokens that must be skipped $removalInfo = $this->removalMap[$key]; if (isset($removalInfo['left'])) { $subStartPos = $this->origTokens->skipLeft($subStartPos - 1, $removalInfo['left']) + 1; } if (isset($removalInfo['right'])) { $subEndPos = $this->origTokens->skipRight($subEndPos + 1, $removalInfo['right']) - 1; } } $result .= $this->origTokens->getTokenCode($pos, $subStartPos, $indentAdjustment); if (null !== $subNode) { $result .= $extraLeft; $origIndentLevel = $this->indentLevel; $this->setIndentLevel(max($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment, 0)); // If it's the same node that was previously in this position, it certainly doesn't // need fixup. It's important to check this here, because our fixup checks are more // conservative than strictly necessary. if (isset($fixupInfo[$subNodeName]) && $subNode->getAttribute('origNode') !== $origSubNode ) { $fixup = $fixupInfo[$subNodeName]; $res = $this->pFixup($fixup, $subNode, $class, $subStartPos, $subEndPos); } else { $res = $this->p($subNode, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true); } $this->safeAppend($result, $res); $this->setIndentLevel($origIndentLevel); $result .= $extraRight; } $pos = $subEndPos + 1; } $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment); return $result; } /** * Perform a format-preserving pretty print of an array. * * @param Node[] $nodes New nodes * @param Node[] $origNodes Original nodes * @param int $pos Current token position (updated by reference) * @param int $indentAdjustment Adjustment for indentation * @param string $parentNodeClass Class of the containing node.
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
true
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Builder.php
lib/PhpParser/Builder.php
<?php declare(strict_types=1); namespace PhpParser; interface Builder { /** * Returns the built node. * * @return Node The built node */ public function getNode(): Node; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NodeVisitorAbstract.php
lib/PhpParser/NodeVisitorAbstract.php
<?php declare(strict_types=1); namespace PhpParser; /** * @codeCoverageIgnore */ abstract class NodeVisitorAbstract implements NodeVisitor { public function beforeTraverse(array $nodes) { return null; } public function enterNode(Node $node) { return null; } public function leaveNode(Node $node) { return null; } public function afterTraverse(array $nodes) { return null; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/PhpVersion.php
lib/PhpParser/PhpVersion.php
<?php declare(strict_types=1); namespace PhpParser; /** * A PHP version, representing only the major and minor version components. */ class PhpVersion { /** @var int Version ID in PHP_VERSION_ID format */ public int $id; /** @var int[] Minimum versions for builtin types */ private const BUILTIN_TYPE_VERSIONS = [ 'array' => 50100, 'callable' => 50400, 'bool' => 70000, 'int' => 70000, 'float' => 70000, 'string' => 70000, 'iterable' => 70100, 'void' => 70100, 'object' => 70200, 'null' => 80000, 'false' => 80000, 'mixed' => 80000, 'never' => 80100, 'true' => 80200, ]; private function __construct(int $id) { $this->id = $id; } /** * Create a PhpVersion object from major and minor version components. */ public static function fromComponents(int $major, int $minor): self { return new self($major * 10000 + $minor * 100); } /** * Get the newest PHP version supported by this library. Support for this version may be partial, * if it is still under development. */ public static function getNewestSupported(): self { return self::fromComponents(8, 5); } /** * Get the host PHP version, that is the PHP version we're currently running on. */ public static function getHostVersion(): self { return self::fromComponents(\PHP_MAJOR_VERSION, \PHP_MINOR_VERSION); } /** * Parse the version from a string like "8.1". */ public static function fromString(string $version): self { if (!preg_match('/^(\d+)\.(\d+)/', $version, $matches)) { throw new \LogicException("Invalid PHP version \"$version\""); } return self::fromComponents((int) $matches[1], (int) $matches[2]); } /** * Check whether two versions are the same. */ public function equals(PhpVersion $other): bool { return $this->id === $other->id; } /** * Check whether this version is greater than or equal to the argument. */ public function newerOrEqual(PhpVersion $other): bool { return $this->id >= $other->id; } /** * Check whether this version is older than the argument. */ public function older(PhpVersion $other): bool { return $this->id < $other->id; } /** * Check whether this is the host PHP version. */ public function isHostVersion(): bool { return $this->equals(self::getHostVersion()); } /** * Check whether this PHP version supports the given builtin type. Type name must be lowercase. */ public function supportsBuiltinType(string $type): bool { $minVersion = self::BUILTIN_TYPE_VERSIONS[$type] ?? null; return $minVersion !== null && $this->id >= $minVersion; } /** * Whether this version supports [] array literals. */ public function supportsShortArraySyntax(): bool { return $this->id >= 50400; } /** * Whether this version supports [] for destructuring. */ public function supportsShortArrayDestructuring(): bool { return $this->id >= 70100; } /** * Whether this version supports flexible heredoc/nowdoc. */ public function supportsFlexibleHeredoc(): bool { return $this->id >= 70300; } /** * Whether this version supports trailing commas in parameter lists. */ public function supportsTrailingCommaInParamList(): bool { return $this->id >= 80000; } /** * Whether this version allows "$var =& new Obj". */ public function allowsAssignNewByReference(): bool { return $this->id < 70000; } /** * Whether this version allows invalid octals like "08". */ public function allowsInvalidOctals(): bool { return $this->id < 70000; } /** * Whether this version allows DEL (\x7f) to occur in identifiers. */ public function allowsDelInIdentifiers(): bool { return $this->id < 70100; } /** * Whether this version supports yield in expression context without parentheses. */ public function supportsYieldWithoutParentheses(): bool { return $this->id >= 70000; } /** * Whether this version supports unicode escape sequences in strings. */ public function supportsUnicodeEscapes(): bool { return $this->id >= 70000; } /* * Whether this version supports attributes. */ public function supportsAttributes(): bool { return $this->id >= 80000; } public function supportsNewDereferenceWithoutParentheses(): bool { return $this->id >= 80400; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/ParserAbstract.php
lib/PhpParser/ParserAbstract.php
<?php declare(strict_types=1); namespace PhpParser; /* * This parser is based on a skeleton written by Moriyoshi Koizumi, which in * turn is based on work by Masato Bito. */ use PhpParser\Node\Arg; use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\Cast\Double; use PhpParser\Node\Identifier; use PhpParser\Node\InterpolatedStringPart; use PhpParser\Node\Name; use PhpParser\Node\Param; use PhpParser\Node\PropertyHook; use PhpParser\Node\Scalar\InterpolatedString; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassConst; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Const_; use PhpParser\Node\Stmt\Else_; use PhpParser\Node\Stmt\ElseIf_; use PhpParser\Node\Stmt\Enum_; use PhpParser\Node\Stmt\Interface_; use PhpParser\Node\Stmt\Namespace_; use PhpParser\Node\Stmt\Nop; use PhpParser\Node\Stmt\Property; use PhpParser\Node\Stmt\TryCatch; use PhpParser\Node\UseItem; use PhpParser\Node\VarLikeIdentifier; use PhpParser\NodeVisitor\CommentAnnotatingVisitor; abstract class ParserAbstract implements Parser { private const SYMBOL_NONE = -1; /** @var Lexer Lexer that is used when parsing */ protected Lexer $lexer; /** @var PhpVersion PHP version to target on a best-effort basis */ protected PhpVersion $phpVersion; /* * The following members will be filled with generated parsing data: */ /** @var int Size of $tokenToSymbol map */ protected int $tokenToSymbolMapSize; /** @var int Size of $action table */ protected int $actionTableSize; /** @var int Size of $goto table */ protected int $gotoTableSize; /** @var int Symbol number signifying an invalid token */ protected int $invalidSymbol; /** @var int Symbol number of error recovery token */ protected int $errorSymbol; /** @var int Action number signifying default action */ protected int $defaultAction; /** @var int Rule number signifying that an unexpected token was encountered */ protected int $unexpectedTokenRule; protected int $YY2TBLSTATE; /** @var int Number of non-leaf states */ protected int $numNonLeafStates; /** @var int[] Map of PHP token IDs to internal symbols */ protected array $phpTokenToSymbol; /** @var array<int, bool> Map of PHP token IDs to drop */ protected array $dropTokens; /** @var int[] Map of external symbols (static::T_*) to internal symbols */ protected array $tokenToSymbol; /** @var string[] Map of symbols to their names */ protected array $symbolToName; /** @var array<int, string> Names of the production rules (only necessary for debugging) */ protected array $productions; /** @var int[] Map of states to a displacement into the $action table. The corresponding action for this * state/symbol pair is $action[$actionBase[$state] + $symbol]. If $actionBase[$state] is 0, the * action is defaulted, i.e. $actionDefault[$state] should be used instead. */ protected array $actionBase; /** @var int[] Table of actions. Indexed according to $actionBase comment. */ protected array $action; /** @var int[] Table indexed analogously to $action. If $actionCheck[$actionBase[$state] + $symbol] != $symbol * then the action is defaulted, i.e. $actionDefault[$state] should be used instead. */ protected array $actionCheck; /** @var int[] Map of states to their default action */ protected array $actionDefault; /** @var callable[] Semantic action callbacks */ protected array $reduceCallbacks; /** @var int[] Map of non-terminals to a displacement into the $goto table. The corresponding goto state for this * non-terminal/state pair is $goto[$gotoBase[$nonTerminal] + $state] (unless defaulted) */ protected array $gotoBase; /** @var int[] Table of states to goto after reduction. Indexed according to $gotoBase comment. */ protected array $goto; /** @var int[] Table indexed analogously to $goto. If $gotoCheck[$gotoBase[$nonTerminal] + $state] != $nonTerminal * then the goto state is defaulted, i.e. $gotoDefault[$nonTerminal] should be used. */ protected array $gotoCheck; /** @var int[] Map of non-terminals to the default state to goto after their reduction */ protected array $gotoDefault; /** @var int[] Map of rules to the non-terminal on their left-hand side, i.e. the non-terminal to use for * determining the state to goto after reduction. */ protected array $ruleToNonTerminal; /** @var int[] Map of rules to the length of their right-hand side, which is the number of elements that have to * be popped from the stack(s) on reduction. */ protected array $ruleToLength; /* * The following members are part of the parser state: */ /** @var mixed Temporary value containing the result of last semantic action (reduction) */ protected $semValue; /** @var mixed[] Semantic value stack (contains values of tokens and semantic action results) */ protected array $semStack; /** @var int[] Token start position stack */ protected array $tokenStartStack; /** @var int[] Token end position stack */ protected array $tokenEndStack; /** @var ErrorHandler Error handler */ protected ErrorHandler $errorHandler; /** @var int Error state, used to avoid error floods */ protected int $errorState; /** @var \SplObjectStorage<Array_, null>|null Array nodes created during parsing, for postprocessing of empty elements. */ protected ?\SplObjectStorage $createdArrays; /** @var \SplObjectStorage<Expr\ArrowFunction, null>|null * Arrow functions that are wrapped in parentheses, to enforce the pipe operator parentheses requirements. */ protected ?\SplObjectStorage $parenthesizedArrowFunctions; /** @var Token[] Tokens for the current parse */ protected array $tokens; /** @var int Current position in token array */ protected int $tokenPos; /** * Initialize $reduceCallbacks map. */ abstract protected function initReduceCallbacks(): void; /** * Creates a parser instance. * * Options: * * phpVersion: ?PhpVersion, * * @param Lexer $lexer A lexer * @param PhpVersion $phpVersion PHP version to target, defaults to latest supported. This * option is best-effort: Even if specified, parsing will generally assume the latest * supported version and only adjust behavior in minor ways, for example by omitting * errors in older versions and interpreting type hints as a name or identifier depending * on version. */ public function __construct(Lexer $lexer, ?PhpVersion $phpVersion = null) { $this->lexer = $lexer; $this->phpVersion = $phpVersion ?? PhpVersion::getNewestSupported(); $this->initReduceCallbacks(); $this->phpTokenToSymbol = $this->createTokenMap(); $this->dropTokens = array_fill_keys( [\T_WHITESPACE, \T_OPEN_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_BAD_CHARACTER], true ); } /** * Parses PHP code into a node tree. * * If a non-throwing error handler is used, the parser will continue parsing after an error * occurred and attempt to build a partial AST. * * @param string $code The source code to parse * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults * to ErrorHandler\Throwing. * * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and * the parser was unable to recover from an error). */ public function parse(string $code, ?ErrorHandler $errorHandler = null): ?array { $this->errorHandler = $errorHandler ?: new ErrorHandler\Throwing(); $this->createdArrays = new \SplObjectStorage(); $this->parenthesizedArrowFunctions = new \SplObjectStorage(); $this->tokens = $this->lexer->tokenize($code, $this->errorHandler); $result = $this->doParse(); // Report errors for any empty elements used inside arrays. This is delayed until after the main parse, // because we don't know a priori whether a given array expression will be used in a destructuring context // or not. foreach ($this->createdArrays as $node) { foreach ($node->items as $item) { if ($item->value instanceof Expr\Error) { $this->errorHandler->handleError( new Error('Cannot use empty array elements in arrays', $item->getAttributes())); } } } // Clear out some of the interior state, so we don't hold onto unnecessary // memory between uses of the parser $this->tokenStartStack = []; $this->tokenEndStack = []; $this->semStack = []; $this->semValue = null; $this->createdArrays = null; $this->parenthesizedArrowFunctions = null; if ($result !== null) { $traverser = new NodeTraverser(new CommentAnnotatingVisitor($this->tokens)); $traverser->traverse($result); } return $result; } public function getTokens(): array { return $this->tokens; } /** @return Stmt[]|null */ protected function doParse(): ?array { // We start off with no lookahead-token $symbol = self::SYMBOL_NONE; $tokenValue = null; $this->tokenPos = -1; // Keep stack of start and end attributes $this->tokenStartStack = []; $this->tokenEndStack = [0]; // Start off in the initial state and keep a stack of previous states $state = 0; $stateStack = [$state]; // Semantic value stack (contains values of tokens and semantic action results) $this->semStack = []; // Current position in the stack(s) $stackPos = 0; $this->errorState = 0; for (;;) { //$this->traceNewState($state, $symbol); if ($this->actionBase[$state] === 0) { $rule = $this->actionDefault[$state]; } else { if ($symbol === self::SYMBOL_NONE) { do { $token = $this->tokens[++$this->tokenPos]; $tokenId = $token->id; } while (isset($this->dropTokens[$tokenId])); // Map the lexer token id to the internally used symbols. $tokenValue = $token->text; if (!isset($this->phpTokenToSymbol[$tokenId])) { throw new \RangeException(sprintf( 'The lexer returned an invalid token (id=%d, value=%s)', $tokenId, $tokenValue )); } $symbol = $this->phpTokenToSymbol[$tokenId]; //$this->traceRead($symbol); } $idx = $this->actionBase[$state] + $symbol; if ((($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol) || ($state < $this->YY2TBLSTATE && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol)) && ($action = $this->action[$idx]) !== $this->defaultAction) { /* * >= numNonLeafStates: shift and reduce * > 0: shift * = 0: accept * < 0: reduce * = -YYUNEXPECTED: error */ if ($action > 0) { /* shift */ //$this->traceShift($symbol); ++$stackPos; $stateStack[$stackPos] = $state = $action; $this->semStack[$stackPos] = $tokenValue; $this->tokenStartStack[$stackPos] = $this->tokenPos; $this->tokenEndStack[$stackPos] = $this->tokenPos; $symbol = self::SYMBOL_NONE; if ($this->errorState) { --$this->errorState; } if ($action < $this->numNonLeafStates) { continue; } /* $yyn >= numNonLeafStates means shift-and-reduce */ $rule = $action - $this->numNonLeafStates; } else { $rule = -$action; } } else { $rule = $this->actionDefault[$state]; } } for (;;) { if ($rule === 0) { /* accept */ //$this->traceAccept(); return $this->semValue; } if ($rule !== $this->unexpectedTokenRule) { /* reduce */ //$this->traceReduce($rule); $ruleLength = $this->ruleToLength[$rule]; try { $callback = $this->reduceCallbacks[$rule]; if ($callback !== null) { $callback($this, $stackPos); } elseif ($ruleLength > 0) { $this->semValue = $this->semStack[$stackPos - $ruleLength + 1]; } } catch (Error $e) { if (-1 === $e->getStartLine()) { $e->setStartLine($this->tokens[$this->tokenPos]->line); } $this->emitError($e); // Can't recover from this type of error return null; } /* Goto - shift nonterminal */ $lastTokenEnd = $this->tokenEndStack[$stackPos]; $stackPos -= $ruleLength; $nonTerminal = $this->ruleToNonTerminal[$rule]; $idx = $this->gotoBase[$nonTerminal] + $stateStack[$stackPos]; if ($idx >= 0 && $idx < $this->gotoTableSize && $this->gotoCheck[$idx] === $nonTerminal) { $state = $this->goto[$idx]; } else { $state = $this->gotoDefault[$nonTerminal]; } ++$stackPos; $stateStack[$stackPos] = $state; $this->semStack[$stackPos] = $this->semValue; $this->tokenEndStack[$stackPos] = $lastTokenEnd; if ($ruleLength === 0) { // Empty productions use the start attributes of the lookahead token. $this->tokenStartStack[$stackPos] = $this->tokenPos; } } else { /* error */ switch ($this->errorState) { case 0: $msg = $this->getErrorMessage($symbol, $state); $this->emitError(new Error($msg, $this->getAttributesForToken($this->tokenPos))); // Break missing intentionally // no break case 1: case 2: $this->errorState = 3; // Pop until error-expecting state uncovered while (!( (($idx = $this->actionBase[$state] + $this->errorSymbol) >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol) || ($state < $this->YY2TBLSTATE && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $this->errorSymbol) >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $this->errorSymbol) ) || ($action = $this->action[$idx]) === $this->defaultAction) { // Not totally sure about this if ($stackPos <= 0) { // Could not recover from error return null; } $state = $stateStack[--$stackPos]; //$this->tracePop($state); } //$this->traceShift($this->errorSymbol); ++$stackPos; $stateStack[$stackPos] = $state = $action; // We treat the error symbol as being empty, so we reset the end attributes // to the end attributes of the last non-error symbol $this->tokenStartStack[$stackPos] = $this->tokenPos; $this->tokenEndStack[$stackPos] = $this->tokenEndStack[$stackPos - 1]; break; case 3: if ($symbol === 0) { // Reached EOF without recovering from error return null; } //$this->traceDiscard($symbol); $symbol = self::SYMBOL_NONE; break 2; } } if ($state < $this->numNonLeafStates) { break; } /* >= numNonLeafStates means shift-and-reduce */ $rule = $state - $this->numNonLeafStates; } } } protected function emitError(Error $error): void { $this->errorHandler->handleError($error); } /** * Format error message including expected tokens. * * @param int $symbol Unexpected symbol * @param int $state State at time of error * * @return string Formatted error message */ protected function getErrorMessage(int $symbol, int $state): string { $expectedString = ''; if ($expected = $this->getExpectedTokens($state)) { $expectedString = ', expecting ' . implode(' or ', $expected); } return 'Syntax error, unexpected ' . $this->symbolToName[$symbol] . $expectedString; } /** * Get limited number of expected tokens in given state. * * @param int $state State * * @return string[] Expected tokens. If too many, an empty array is returned. */ protected function getExpectedTokens(int $state): array { $expected = []; $base = $this->actionBase[$state]; foreach ($this->symbolToName as $symbol => $name) { $idx = $base + $symbol; if ($idx >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol || $state < $this->YY2TBLSTATE && ($idx = $this->actionBase[$state + $this->numNonLeafStates] + $symbol) >= 0 && $idx < $this->actionTableSize && $this->actionCheck[$idx] === $symbol ) { if ($this->action[$idx] !== $this->unexpectedTokenRule && $this->action[$idx] !== $this->defaultAction && $symbol !== $this->errorSymbol ) { if (count($expected) === 4) { /* Too many expected tokens */ return []; } $expected[] = $name; } } } return $expected; } /** * Get attributes for a node with the given start and end token positions. * * @param int $tokenStartPos Token position the node starts at * @param int $tokenEndPos Token position the node ends at * @return array<string, mixed> Attributes */ protected function getAttributes(int $tokenStartPos, int $tokenEndPos): array { $startToken = $this->tokens[$tokenStartPos]; $afterEndToken = $this->tokens[$tokenEndPos + 1]; return [ 'startLine' => $startToken->line, 'startTokenPos' => $tokenStartPos, 'startFilePos' => $startToken->pos, 'endLine' => $afterEndToken->line, 'endTokenPos' => $tokenEndPos, 'endFilePos' => $afterEndToken->pos - 1, ]; } /** * Get attributes for a single token at the given token position. * * @return array<string, mixed> Attributes */ protected function getAttributesForToken(int $tokenPos): array { if ($tokenPos < \count($this->tokens) - 1) { return $this->getAttributes($tokenPos, $tokenPos); } // Get attributes for the sentinel token. $token = $this->tokens[$tokenPos]; return [ 'startLine' => $token->line, 'startTokenPos' => $tokenPos, 'startFilePos' => $token->pos, 'endLine' => $token->line, 'endTokenPos' => $tokenPos, 'endFilePos' => $token->pos, ]; } /* * Tracing functions used for debugging the parser. */ /* protected function traceNewState($state, $symbol): void { echo '% State ' . $state . ', Lookahead ' . ($symbol == self::SYMBOL_NONE ? '--none--' : $this->symbolToName[$symbol]) . "\n"; } protected function traceRead($symbol): void { echo '% Reading ' . $this->symbolToName[$symbol] . "\n"; } protected function traceShift($symbol): void { echo '% Shift ' . $this->symbolToName[$symbol] . "\n"; } protected function traceAccept(): void { echo "% Accepted.\n"; } protected function traceReduce($n): void { echo '% Reduce by (' . $n . ') ' . $this->productions[$n] . "\n"; } protected function tracePop($state): void { echo '% Recovering, uncovered state ' . $state . "\n"; } protected function traceDiscard($symbol): void { echo '% Discard ' . $this->symbolToName[$symbol] . "\n"; } */ /* * Helper functions invoked by semantic actions */ /** * Moves statements of semicolon-style namespaces into $ns->stmts and checks various error conditions. * * @param Node\Stmt[] $stmts * @return Node\Stmt[] */ protected function handleNamespaces(array $stmts): array { $hasErrored = false; $style = $this->getNamespacingStyle($stmts); if (null === $style) { // not namespaced, nothing to do return $stmts; } if ('brace' === $style) { // For braced namespaces we only have to check that there are no invalid statements between the namespaces $afterFirstNamespace = false; foreach ($stmts as $stmt) { if ($stmt instanceof Node\Stmt\Namespace_) { $afterFirstNamespace = true; } elseif (!$stmt instanceof Node\Stmt\HaltCompiler && !$stmt instanceof Node\Stmt\Nop && $afterFirstNamespace && !$hasErrored) { $this->emitError(new Error( 'No code may exist outside of namespace {}', $stmt->getAttributes())); $hasErrored = true; // Avoid one error for every statement } } return $stmts; } else { // For semicolon namespaces we have to move the statements after a namespace declaration into ->stmts $resultStmts = []; $targetStmts = &$resultStmts; $lastNs = null; foreach ($stmts as $stmt) { if ($stmt instanceof Node\Stmt\Namespace_) { if ($lastNs !== null) { $this->fixupNamespaceAttributes($lastNs); } if ($stmt->stmts === null) { $stmt->stmts = []; $targetStmts = &$stmt->stmts; $resultStmts[] = $stmt; } else { // This handles the invalid case of mixed style namespaces $resultStmts[] = $stmt; $targetStmts = &$resultStmts; } $lastNs = $stmt; } elseif ($stmt instanceof Node\Stmt\HaltCompiler) { // __halt_compiler() is not moved into the namespace $resultStmts[] = $stmt; } else { $targetStmts[] = $stmt; } } if ($lastNs !== null) { $this->fixupNamespaceAttributes($lastNs); } return $resultStmts; } } private function fixupNamespaceAttributes(Node\Stmt\Namespace_ $stmt): void { // We moved the statements into the namespace node, as such the end of the namespace node // needs to be extended to the end of the statements. if (empty($stmt->stmts)) { return; } // We only move the builtin end attributes here. This is the best we can do with the // knowledge we have. $endAttributes = ['endLine', 'endFilePos', 'endTokenPos']; $lastStmt = $stmt->stmts[count($stmt->stmts) - 1]; foreach ($endAttributes as $endAttribute) { if ($lastStmt->hasAttribute($endAttribute)) { $stmt->setAttribute($endAttribute, $lastStmt->getAttribute($endAttribute)); } } } /** @return array<string, mixed> */ private function getNamespaceErrorAttributes(Namespace_ $node): array { $attrs = $node->getAttributes(); // Adjust end attributes to only cover the "namespace" keyword, not the whole namespace. if (isset($attrs['startLine'])) { $attrs['endLine'] = $attrs['startLine']; } if (isset($attrs['startTokenPos'])) { $attrs['endTokenPos'] = $attrs['startTokenPos']; } if (isset($attrs['startFilePos'])) { $attrs['endFilePos'] = $attrs['startFilePos'] + \strlen('namespace') - 1; } return $attrs; } /** * Determine namespacing style (semicolon or brace) * * @param Node[] $stmts Top-level statements. * * @return null|string One of "semicolon", "brace" or null (no namespaces) */ private function getNamespacingStyle(array $stmts): ?string { $style = null; $hasNotAllowedStmts = false; foreach ($stmts as $i => $stmt) { if ($stmt instanceof Node\Stmt\Namespace_) { $currentStyle = null === $stmt->stmts ? 'semicolon' : 'brace'; if (null === $style) { $style = $currentStyle; if ($hasNotAllowedStmts) { $this->emitError(new Error( 'Namespace declaration statement has to be the very first statement in the script', $this->getNamespaceErrorAttributes($stmt) )); } } elseif ($style !== $currentStyle) { $this->emitError(new Error( 'Cannot mix bracketed namespace declarations with unbracketed namespace declarations', $this->getNamespaceErrorAttributes($stmt) )); // Treat like semicolon style for namespace normalization return 'semicolon'; } continue; } /* declare(), __halt_compiler() and nops can be used before a namespace declaration */ if ($stmt instanceof Node\Stmt\Declare_ || $stmt instanceof Node\Stmt\HaltCompiler || $stmt instanceof Node\Stmt\Nop) { continue; } /* There may be a hashbang line at the very start of the file */ if ($i === 0 && $stmt instanceof Node\Stmt\InlineHTML && preg_match('/\A#!.*\r?\n\z/', $stmt->value)) { continue; } /* Everything else if forbidden before namespace declarations */ $hasNotAllowedStmts = true; } return $style; } /** @return Name|Identifier */ protected function handleBuiltinTypes(Name $name) { if (!$name->isUnqualified()) { return $name; } $lowerName = $name->toLowerString(); if (!$this->phpVersion->supportsBuiltinType($lowerName)) { return $name; } return new Node\Identifier($lowerName, $name->getAttributes()); } /** * Get combined start and end attributes at a stack location * * @param int $stackPos Stack location * * @return array<string, mixed> Combined start and end attributes */ protected function getAttributesAt(int $stackPos): array { return $this->getAttributes($this->tokenStartStack[$stackPos], $this->tokenEndStack[$stackPos]); } protected function getFloatCastKind(string $cast): int { $cast = strtolower($cast); if (strpos($cast, 'float') !== false) { return Double::KIND_FLOAT; } if (strpos($cast, 'real') !== false) { return Double::KIND_REAL; } return Double::KIND_DOUBLE; } protected function getIntCastKind(string $cast): int { $cast = strtolower($cast); if (strpos($cast, 'integer') !== false) { return Expr\Cast\Int_::KIND_INTEGER; } return Expr\Cast\Int_::KIND_INT; } protected function getBoolCastKind(string $cast): int { $cast = strtolower($cast); if (strpos($cast, 'boolean') !== false) { return Expr\Cast\Bool_::KIND_BOOLEAN; } return Expr\Cast\Bool_::KIND_BOOL; } protected function getStringCastKind(string $cast): int { $cast = strtolower($cast); if (strpos($cast, 'binary') !== false) { return Expr\Cast\String_::KIND_BINARY; } return Expr\Cast\String_::KIND_STRING; } /** @param array<string, mixed> $attributes */ protected function parseLNumber(string $str, array $attributes, bool $allowInvalidOctal = false): Int_ { try { return Int_::fromString($str, $attributes, $allowInvalidOctal); } catch (Error $error) { $this->emitError($error); // Use dummy value return new Int_(0, $attributes); } } /** * Parse a T_NUM_STRING token into either an integer or string node. * * @param string $str Number string * @param array<string, mixed> $attributes Attributes * * @return Int_|String_ Integer or string node. */ protected function parseNumString(string $str, array $attributes) { if (!preg_match('/^(?:0|-?[1-9][0-9]*)$/', $str)) { return new String_($str, $attributes); } $num = +$str; if (!is_int($num)) { return new String_($str, $attributes); } return new Int_($num, $attributes); } /** @param array<string, mixed> $attributes */ protected function stripIndentation( string $string, int $indentLen, string $indentChar, bool $newlineAtStart, bool $newlineAtEnd, array $attributes ): string { if ($indentLen === 0) { return $string; } $start = $newlineAtStart ? '(?:(?<=\n)|\A)' : '(?<=\n)'; $end = $newlineAtEnd ? '(?:(?=[\r\n])|\z)' : '(?=[\r\n])'; $regex = '/' . $start . '([ \t]*)(' . $end . ')?/'; return preg_replace_callback( $regex, function ($matches) use ($indentLen, $indentChar, $attributes) { $prefix = substr($matches[1], 0, $indentLen);
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
true
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/ErrorHandler.php
lib/PhpParser/ErrorHandler.php
<?php declare(strict_types=1); namespace PhpParser; interface ErrorHandler { /** * Handle an error generated during lexing, parsing or some other operation. * * @param Error $error The error that needs to be handled */ public function handleError(Error $error): void; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Comment.php
lib/PhpParser/Comment.php
<?php declare(strict_types=1); namespace PhpParser; class Comment implements \JsonSerializable { protected string $text; protected int $startLine; protected int $startFilePos; protected int $startTokenPos; protected int $endLine; protected int $endFilePos; protected int $endTokenPos; /** * Constructs a comment node. * * @param string $text Comment text (including comment delimiters like /*) * @param int $startLine Line number the comment started on * @param int $startFilePos File offset the comment started on * @param int $startTokenPos Token offset the comment started on */ public function __construct( string $text, int $startLine = -1, int $startFilePos = -1, int $startTokenPos = -1, int $endLine = -1, int $endFilePos = -1, int $endTokenPos = -1 ) { $this->text = $text; $this->startLine = $startLine; $this->startFilePos = $startFilePos; $this->startTokenPos = $startTokenPos; $this->endLine = $endLine; $this->endFilePos = $endFilePos; $this->endTokenPos = $endTokenPos; } /** * Gets the comment text. * * @return string The comment text (including comment delimiters like /*) */ public function getText(): string { return $this->text; } /** * Gets the line number the comment started on. * * @return int Line number (or -1 if not available) * @phpstan-return -1|positive-int */ public function getStartLine(): int { return $this->startLine; } /** * Gets the file offset the comment started on. * * @return int File offset (or -1 if not available) */ public function getStartFilePos(): int { return $this->startFilePos; } /** * Gets the token offset the comment started on. * * @return int Token offset (or -1 if not available) */ public function getStartTokenPos(): int { return $this->startTokenPos; } /** * Gets the line number the comment ends on. * * @return int Line number (or -1 if not available) * @phpstan-return -1|positive-int */ public function getEndLine(): int { return $this->endLine; } /** * Gets the file offset the comment ends on. * * @return int File offset (or -1 if not available) */ public function getEndFilePos(): int { return $this->endFilePos; } /** * Gets the token offset the comment ends on. * * @return int Token offset (or -1 if not available) */ public function getEndTokenPos(): int { return $this->endTokenPos; } /** * Gets the comment text. * * @return string The comment text (including comment delimiters like /*) */ public function __toString(): string { return $this->text; } /** * Gets the reformatted comment text. * * "Reformatted" here means that we try to clean up the whitespace at the * starts of the lines. This is necessary because we receive the comments * without leading whitespace on the first line, but with leading whitespace * on all subsequent lines. * * Additionally, this normalizes CRLF newlines to LF newlines. */ public function getReformattedText(): string { $text = str_replace("\r\n", "\n", $this->text); $newlinePos = strpos($text, "\n"); if (false === $newlinePos) { // Single line comments don't need further processing return $text; } if (preg_match('(^.*(?:\n\s+\*.*)+$)', $text)) { // Multi line comment of the type // // /* // * Some text. // * Some more text. // */ // // is handled by replacing the whitespace sequences before the * by a single space return preg_replace('(^\s+\*)m', ' *', $text); } if (preg_match('(^/\*\*?\s*\n)', $text) && preg_match('(\n(\s*)\*/$)', $text, $matches)) { // Multi line comment of the type // // /* // Some text. // Some more text. // */ // // is handled by removing the whitespace sequence on the line before the closing // */ on all lines. So if the last line is " */", then " " is removed at the // start of all lines. return preg_replace('(^' . preg_quote($matches[1]) . ')m', '', $text); } if (preg_match('(^/\*\*?\s*(?!\s))', $text, $matches)) { // Multi line comment of the type // // /* Some text. // Some more text. // Indented text. // Even more text. */ // // is handled by removing the difference between the shortest whitespace prefix on all // lines and the length of the "/* " opening sequence. $prefixLen = $this->getShortestWhitespacePrefixLen(substr($text, $newlinePos + 1)); $removeLen = $prefixLen - strlen($matches[0]); return preg_replace('(^\s{' . $removeLen . '})m', '', $text); } // No idea how to format this comment, so simply return as is return $text; } /** * Get length of shortest whitespace prefix (at the start of a line). * * If there is a line with no prefix whitespace, 0 is a valid return value. * * @param string $str String to check * @return int Length in characters. Tabs count as single characters. */ private function getShortestWhitespacePrefixLen(string $str): int { $lines = explode("\n", $str); $shortestPrefixLen = \PHP_INT_MAX; foreach ($lines as $line) { preg_match('(^\s*)', $line, $matches); $prefixLen = strlen($matches[0]); if ($prefixLen < $shortestPrefixLen) { $shortestPrefixLen = $prefixLen; } } return $shortestPrefixLen; } /** * @return array{nodeType:string, text:mixed, line:mixed, filePos:mixed} */ public function jsonSerialize(): array { // Technically not a node, but we make it look like one anyway $type = $this instanceof Comment\Doc ? 'Comment_Doc' : 'Comment'; return [ 'nodeType' => $type, 'text' => $this->text, // TODO: Rename these to include "start". 'line' => $this->startLine, 'filePos' => $this->startFilePos, 'tokenPos' => $this->startTokenPos, 'endLine' => $this->endLine, 'endFilePos' => $this->endFilePos, 'endTokenPos' => $this->endTokenPos, ]; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/ConstExprEvaluator.php
lib/PhpParser/ConstExprEvaluator.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; use PhpParser\Node\Scalar; use function array_merge; /** * Evaluates constant expressions. * * This evaluator is able to evaluate all constant expressions (as defined by PHP), which can be * evaluated without further context. If a subexpression is not of this type, a user-provided * fallback evaluator is invoked. To support all constant expressions that are also supported by * PHP (and not already handled by this class), the fallback evaluator must be able to handle the * following node types: * * * All Scalar\MagicConst\* nodes. * * Expr\ConstFetch nodes. Only null/false/true are already handled by this class. * * Expr\ClassConstFetch nodes. * * The fallback evaluator should throw ConstExprEvaluationException for nodes it cannot evaluate. * * The evaluation is dependent on runtime configuration in two respects: Firstly, floating * point to string conversions are affected by the precision ini setting. Secondly, they are also * affected by the LC_NUMERIC locale. */ class ConstExprEvaluator { /** @var callable|null */ private $fallbackEvaluator; /** * Create a constant expression evaluator. * * The provided fallback evaluator is invoked whenever a subexpression cannot be evaluated. See * class doc comment for more information. * * @param callable|null $fallbackEvaluator To call if subexpression cannot be evaluated */ public function __construct(?callable $fallbackEvaluator = null) { $this->fallbackEvaluator = $fallbackEvaluator ?? function (Expr $expr) { throw new ConstExprEvaluationException( "Expression of type {$expr->getType()} cannot be evaluated" ); }; } /** * Silently evaluates a constant expression into a PHP value. * * Thrown Errors, warnings or notices will be converted into a ConstExprEvaluationException. * The original source of the exception is available through getPrevious(). * * If some part of the expression cannot be evaluated, the fallback evaluator passed to the * constructor will be invoked. By default, if no fallback is provided, an exception of type * ConstExprEvaluationException is thrown. * * See class doc comment for caveats and limitations. * * @param Expr $expr Constant expression to evaluate * @return mixed Result of evaluation * * @throws ConstExprEvaluationException if the expression cannot be evaluated or an error occurred */ public function evaluateSilently(Expr $expr) { set_error_handler(function ($num, $str, $file, $line) { throw new \ErrorException($str, 0, $num, $file, $line); }); try { return $this->evaluate($expr); } catch (\Throwable $e) { if (!$e instanceof ConstExprEvaluationException) { $e = new ConstExprEvaluationException( "An error occurred during constant expression evaluation", 0, $e); } throw $e; } finally { restore_error_handler(); } } /** * Directly evaluates a constant expression into a PHP value. * * May generate Error exceptions, warnings or notices. Use evaluateSilently() to convert these * into a ConstExprEvaluationException. * * If some part of the expression cannot be evaluated, the fallback evaluator passed to the * constructor will be invoked. By default, if no fallback is provided, an exception of type * ConstExprEvaluationException is thrown. * * See class doc comment for caveats and limitations. * * @param Expr $expr Constant expression to evaluate * @return mixed Result of evaluation * * @throws ConstExprEvaluationException if the expression cannot be evaluated */ public function evaluateDirectly(Expr $expr) { return $this->evaluate($expr); } /** @return mixed */ private function evaluate(Expr $expr) { if ($expr instanceof Scalar\Int_ || $expr instanceof Scalar\Float_ || $expr instanceof Scalar\String_ ) { return $expr->value; } if ($expr instanceof Expr\Array_) { return $this->evaluateArray($expr); } // Unary operators if ($expr instanceof Expr\UnaryPlus) { return +$this->evaluate($expr->expr); } if ($expr instanceof Expr\UnaryMinus) { return -$this->evaluate($expr->expr); } if ($expr instanceof Expr\BooleanNot) { return !$this->evaluate($expr->expr); } if ($expr instanceof Expr\BitwiseNot) { return ~$this->evaluate($expr->expr); } if ($expr instanceof Expr\BinaryOp) { return $this->evaluateBinaryOp($expr); } if ($expr instanceof Expr\Ternary) { return $this->evaluateTernary($expr); } if ($expr instanceof Expr\ArrayDimFetch && null !== $expr->dim) { return $this->evaluate($expr->var)[$this->evaluate($expr->dim)]; } if ($expr instanceof Expr\ConstFetch) { return $this->evaluateConstFetch($expr); } return ($this->fallbackEvaluator)($expr); } private function evaluateArray(Expr\Array_ $expr): array { $array = []; foreach ($expr->items as $item) { if (null !== $item->key) { $array[$this->evaluate($item->key)] = $this->evaluate($item->value); } elseif ($item->unpack) { $array = array_merge($array, $this->evaluate($item->value)); } else { $array[] = $this->evaluate($item->value); } } return $array; } /** @return mixed */ private function evaluateTernary(Expr\Ternary $expr) { if (null === $expr->if) { return $this->evaluate($expr->cond) ?: $this->evaluate($expr->else); } return $this->evaluate($expr->cond) ? $this->evaluate($expr->if) : $this->evaluate($expr->else); } /** @return mixed */ private function evaluateBinaryOp(Expr\BinaryOp $expr) { if ($expr instanceof Expr\BinaryOp\Coalesce && $expr->left instanceof Expr\ArrayDimFetch ) { // This needs to be special cased to respect BP_VAR_IS fetch semantics return $this->evaluate($expr->left->var)[$this->evaluate($expr->left->dim)] ?? $this->evaluate($expr->right); } // The evaluate() calls are repeated in each branch, because some of the operators are // short-circuiting and evaluating the RHS in advance may be illegal in that case $l = $expr->left; $r = $expr->right; switch ($expr->getOperatorSigil()) { case '&': return $this->evaluate($l) & $this->evaluate($r); case '|': return $this->evaluate($l) | $this->evaluate($r); case '^': return $this->evaluate($l) ^ $this->evaluate($r); case '&&': return $this->evaluate($l) && $this->evaluate($r); case '||': return $this->evaluate($l) || $this->evaluate($r); case '??': return $this->evaluate($l) ?? $this->evaluate($r); case '.': return $this->evaluate($l) . $this->evaluate($r); case '/': return $this->evaluate($l) / $this->evaluate($r); case '==': return $this->evaluate($l) == $this->evaluate($r); case '>': return $this->evaluate($l) > $this->evaluate($r); case '>=': return $this->evaluate($l) >= $this->evaluate($r); case '===': return $this->evaluate($l) === $this->evaluate($r); case 'and': return $this->evaluate($l) and $this->evaluate($r); case 'or': return $this->evaluate($l) or $this->evaluate($r); case 'xor': return $this->evaluate($l) xor $this->evaluate($r); case '-': return $this->evaluate($l) - $this->evaluate($r); case '%': return $this->evaluate($l) % $this->evaluate($r); case '*': return $this->evaluate($l) * $this->evaluate($r); case '!=': return $this->evaluate($l) != $this->evaluate($r); case '!==': return $this->evaluate($l) !== $this->evaluate($r); case '+': return $this->evaluate($l) + $this->evaluate($r); case '**': return $this->evaluate($l) ** $this->evaluate($r); case '<<': return $this->evaluate($l) << $this->evaluate($r); case '>>': return $this->evaluate($l) >> $this->evaluate($r); case '<': return $this->evaluate($l) < $this->evaluate($r); case '<=': return $this->evaluate($l) <= $this->evaluate($r); case '<=>': return $this->evaluate($l) <=> $this->evaluate($r); case '|>': $lval = $this->evaluate($l); return $this->evaluate($r)($lval); } throw new \Exception('Should not happen'); } /** @return mixed */ private function evaluateConstFetch(Expr\ConstFetch $expr) { $name = $expr->name->toLowerString(); switch ($name) { case 'null': return null; case 'false': return false; case 'true': return true; } return ($this->fallbackEvaluator)($expr); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NodeVisitor.php
lib/PhpParser/NodeVisitor.php
<?php declare(strict_types=1); namespace PhpParser; interface NodeVisitor { /** * If NodeVisitor::enterNode() returns DONT_TRAVERSE_CHILDREN, child nodes * of the current node will not be traversed for any visitors. * * For subsequent visitors enterNode() will still be called on the current * node and leaveNode() will also be invoked for the current node. */ public const DONT_TRAVERSE_CHILDREN = 1; /** * If NodeVisitor::enterNode() or NodeVisitor::leaveNode() returns * STOP_TRAVERSAL, traversal is aborted. * * The afterTraverse() method will still be invoked. */ public const STOP_TRAVERSAL = 2; /** * If NodeVisitor::leaveNode() returns REMOVE_NODE for a node that occurs * in an array, it will be removed from the array. * * For subsequent visitors leaveNode() will still be invoked for the * removed node. */ public const REMOVE_NODE = 3; /** * If NodeVisitor::enterNode() returns DONT_TRAVERSE_CURRENT_AND_CHILDREN, child nodes * of the current node will not be traversed for any visitors. * * For subsequent visitors enterNode() will not be called as well. * leaveNode() will be invoked for visitors that has enterNode() method invoked. */ public const DONT_TRAVERSE_CURRENT_AND_CHILDREN = 4; /** * If NodeVisitor::enterNode() or NodeVisitor::leaveNode() returns REPLACE_WITH_NULL, * the node will be replaced with null. This is not a legal return value if the node is part * of an array, rather than another node. */ public const REPLACE_WITH_NULL = 5; /** * Called once before traversal. * * Return value semantics: * * null: $nodes stays as-is * * otherwise: $nodes is set to the return value * * @param Node[] $nodes Array of nodes * * @return null|Node[] Array of nodes */ public function beforeTraverse(array $nodes); /** * Called when entering a node. * * Return value semantics: * * null * => $node stays as-is * * array (of Nodes) * => The return value is merged into the parent array (at the position of the $node) * * NodeVisitor::REMOVE_NODE * => $node is removed from the parent array * * NodeVisitor::REPLACE_WITH_NULL * => $node is replaced with null * * NodeVisitor::DONT_TRAVERSE_CHILDREN * => Children of $node are not traversed. $node stays as-is * * NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN * => Further visitors for the current node are skipped, and its children are not * traversed. $node stays as-is. * * NodeVisitor::STOP_TRAVERSAL * => Traversal is aborted. $node stays as-is * * otherwise * => $node is set to the return value * * @param Node $node Node * * @return null|int|Node|Node[] Replacement node (or special return value) */ public function enterNode(Node $node); /** * Called when leaving a node. * * Return value semantics: * * null * => $node stays as-is * * NodeVisitor::REMOVE_NODE * => $node is removed from the parent array * * NodeVisitor::REPLACE_WITH_NULL * => $node is replaced with null * * NodeVisitor::STOP_TRAVERSAL * => Traversal is aborted. $node stays as-is * * array (of Nodes) * => The return value is merged into the parent array (at the position of the $node) * * otherwise * => $node is set to the return value * * @param Node $node Node * * @return null|int|Node|Node[] Replacement node (or special return value) */ public function leaveNode(Node $node); /** * Called once after traversal. * * Return value semantics: * * null: $nodes stays as-is * * otherwise: $nodes is set to the return value * * @param Node[] $nodes Array of nodes * * @return null|Node[] Array of nodes */ public function afterTraverse(array $nodes); }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NodeFinder.php
lib/PhpParser/NodeFinder.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\NodeVisitor\FindingVisitor; use PhpParser\NodeVisitor\FirstFindingVisitor; class NodeFinder { /** * Find all nodes satisfying a filter callback. * * @param Node|Node[] $nodes Single node or array of nodes to search in * @param callable $filter Filter callback: function(Node $node) : bool * * @return Node[] Found nodes satisfying the filter callback */ public function find($nodes, callable $filter): array { if ($nodes === []) { return []; } if (!is_array($nodes)) { $nodes = [$nodes]; } $visitor = new FindingVisitor($filter); $traverser = new NodeTraverser($visitor); $traverser->traverse($nodes); return $visitor->getFoundNodes(); } /** * Find all nodes that are instances of a certain class. * @template TNode as Node * * @param Node|Node[] $nodes Single node or array of nodes to search in * @param class-string<TNode> $class Class name * * @return TNode[] Found nodes (all instances of $class) */ public function findInstanceOf($nodes, string $class): array { return $this->find($nodes, function ($node) use ($class) { return $node instanceof $class; }); } /** * Find first node satisfying a filter callback. * * @param Node|Node[] $nodes Single node or array of nodes to search in * @param callable $filter Filter callback: function(Node $node) : bool * * @return null|Node Found node (or null if none found) */ public function findFirst($nodes, callable $filter): ?Node { if ($nodes === []) { return null; } if (!is_array($nodes)) { $nodes = [$nodes]; } $visitor = new FirstFindingVisitor($filter); $traverser = new NodeTraverser($visitor); $traverser->traverse($nodes); return $visitor->getFoundNode(); } /** * Find first node that is an instance of a certain class. * * @template TNode as Node * * @param Node|Node[] $nodes Single node or array of nodes to search in * @param class-string<TNode> $class Class name * * @return null|TNode Found node, which is an instance of $class (or null if none found) */ public function findFirstInstanceOf($nodes, string $class): ?Node { return $this->findFirst($nodes, function ($node) use ($class) { return $node instanceof $class; }); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NameContext.php
lib/PhpParser/NameContext.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Name; use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Stmt; class NameContext { /** @var null|Name Current namespace */ protected ?Name $namespace; /** @var Name[][] Map of format [aliasType => [aliasName => originalName]] */ protected array $aliases = []; /** @var Name[][] Same as $aliases but preserving original case */ protected array $origAliases = []; /** @var ErrorHandler Error handler */ protected ErrorHandler $errorHandler; /** * Create a name context. * * @param ErrorHandler $errorHandler Error handling used to report errors */ public function __construct(ErrorHandler $errorHandler) { $this->errorHandler = $errorHandler; } /** * Start a new namespace. * * This also resets the alias table. * * @param Name|null $namespace Null is the global namespace */ public function startNamespace(?Name $namespace = null): void { $this->namespace = $namespace; $this->origAliases = $this->aliases = [ Stmt\Use_::TYPE_NORMAL => [], Stmt\Use_::TYPE_FUNCTION => [], Stmt\Use_::TYPE_CONSTANT => [], ]; } /** * Add an alias / import. * * @param Name $name Original name * @param string $aliasName Aliased name * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_* * @param array<string, mixed> $errorAttrs Attributes to use to report an error */ public function addAlias(Name $name, string $aliasName, int $type, array $errorAttrs = []): void { // Constant names are case sensitive, everything else case insensitive if ($type === Stmt\Use_::TYPE_CONSTANT) { $aliasLookupName = $aliasName; } else { $aliasLookupName = strtolower($aliasName); } if (isset($this->aliases[$type][$aliasLookupName])) { $typeStringMap = [ Stmt\Use_::TYPE_NORMAL => '', Stmt\Use_::TYPE_FUNCTION => 'function ', Stmt\Use_::TYPE_CONSTANT => 'const ', ]; $this->errorHandler->handleError(new Error( sprintf( 'Cannot use %s%s as %s because the name is already in use', $typeStringMap[$type], $name, $aliasName ), $errorAttrs )); return; } $this->aliases[$type][$aliasLookupName] = $name; $this->origAliases[$type][$aliasName] = $name; } /** * Get current namespace. * * @return null|Name Namespace (or null if global namespace) */ public function getNamespace(): ?Name { return $this->namespace; } /** * Get resolved name. * * @param Name $name Name to resolve * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_{FUNCTION|CONSTANT} * * @return null|Name Resolved name, or null if static resolution is not possible */ public function getResolvedName(Name $name, int $type): ?Name { // don't resolve special class names if ($type === Stmt\Use_::TYPE_NORMAL && $name->isSpecialClassName()) { if (!$name->isUnqualified()) { $this->errorHandler->handleError(new Error( sprintf("'\\%s' is an invalid class name", $name->toString()), $name->getAttributes() )); } return $name; } // fully qualified names are already resolved if ($name->isFullyQualified()) { return $name; } // Try to resolve aliases if (null !== $resolvedName = $this->resolveAlias($name, $type)) { return $resolvedName; } if ($type !== Stmt\Use_::TYPE_NORMAL && $name->isUnqualified()) { if (null === $this->namespace) { // outside of a namespace unaliased unqualified is same as fully qualified return new FullyQualified($name, $name->getAttributes()); } // Cannot resolve statically return null; } // if no alias exists prepend current namespace return FullyQualified::concat($this->namespace, $name, $name->getAttributes()); } /** * Get resolved class name. * * @param Name $name Class ame to resolve * * @return Name Resolved name */ public function getResolvedClassName(Name $name): Name { return $this->getResolvedName($name, Stmt\Use_::TYPE_NORMAL); } /** * Get possible ways of writing a fully qualified name (e.g., by making use of aliases). * * @param string $name Fully-qualified name (without leading namespace separator) * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_* * * @return Name[] Possible representations of the name */ public function getPossibleNames(string $name, int $type): array { $lcName = strtolower($name); if ($type === Stmt\Use_::TYPE_NORMAL) { // self, parent and static must always be unqualified if ($lcName === "self" || $lcName === "parent" || $lcName === "static") { return [new Name($name)]; } } // Collect possible ways to write this name, starting with the fully-qualified name $possibleNames = [new FullyQualified($name)]; if (null !== $nsRelativeName = $this->getNamespaceRelativeName($name, $lcName, $type)) { // Make sure there is no alias that makes the normally namespace-relative name // into something else if (null === $this->resolveAlias($nsRelativeName, $type)) { $possibleNames[] = $nsRelativeName; } } // Check for relevant namespace use statements foreach ($this->origAliases[Stmt\Use_::TYPE_NORMAL] as $alias => $orig) { $lcOrig = $orig->toLowerString(); if (0 === strpos($lcName, $lcOrig . '\\')) { $possibleNames[] = new Name($alias . substr($name, strlen($lcOrig))); } } // Check for relevant type-specific use statements foreach ($this->origAliases[$type] as $alias => $orig) { if ($type === Stmt\Use_::TYPE_CONSTANT) { // Constants are complicated-sensitive $normalizedOrig = $this->normalizeConstName($orig->toString()); if ($normalizedOrig === $this->normalizeConstName($name)) { $possibleNames[] = new Name($alias); } } else { // Everything else is case-insensitive if ($orig->toLowerString() === $lcName) { $possibleNames[] = new Name($alias); } } } return $possibleNames; } /** * Get shortest representation of this fully-qualified name. * * @param string $name Fully-qualified name (without leading namespace separator) * @param Stmt\Use_::TYPE_* $type One of Stmt\Use_::TYPE_* * * @return Name Shortest representation */ public function getShortName(string $name, int $type): Name { $possibleNames = $this->getPossibleNames($name, $type); // Find shortest name $shortestName = null; $shortestLength = \INF; foreach ($possibleNames as $possibleName) { $length = strlen($possibleName->toCodeString()); if ($length < $shortestLength) { $shortestName = $possibleName; $shortestLength = $length; } } return $shortestName; } private function resolveAlias(Name $name, int $type): ?FullyQualified { $firstPart = $name->getFirst(); if ($name->isQualified()) { // resolve aliases for qualified names, always against class alias table $checkName = strtolower($firstPart); if (isset($this->aliases[Stmt\Use_::TYPE_NORMAL][$checkName])) { $alias = $this->aliases[Stmt\Use_::TYPE_NORMAL][$checkName]; return FullyQualified::concat($alias, $name->slice(1), $name->getAttributes()); } } elseif ($name->isUnqualified()) { // constant aliases are case-sensitive, function aliases case-insensitive $checkName = $type === Stmt\Use_::TYPE_CONSTANT ? $firstPart : strtolower($firstPart); if (isset($this->aliases[$type][$checkName])) { // resolve unqualified aliases return new FullyQualified($this->aliases[$type][$checkName], $name->getAttributes()); } } // No applicable aliases return null; } private function getNamespaceRelativeName(string $name, string $lcName, int $type): ?Name { if (null === $this->namespace) { return new Name($name); } if ($type === Stmt\Use_::TYPE_CONSTANT) { // The constants true/false/null always resolve to the global symbols, even inside a // namespace, so they may be used without qualification if ($lcName === "true" || $lcName === "false" || $lcName === "null") { return new Name($name); } } $namespacePrefix = strtolower($this->namespace . '\\'); if (0 === strpos($lcName, $namespacePrefix)) { return new Name(substr($name, strlen($namespacePrefix))); } return null; } private function normalizeConstName(string $name): string { $nsSep = strrpos($name, '\\'); if (false === $nsSep) { return $name; } // Constants have case-insensitive namespace and case-sensitive short-name $ns = substr($name, 0, $nsSep); $shortName = substr($name, $nsSep + 1); return strtolower($ns) . '\\' . $shortName; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/JsonDecoder.php
lib/PhpParser/JsonDecoder.php
<?php declare(strict_types=1); namespace PhpParser; class JsonDecoder { /** @var \ReflectionClass<Node>[] Node type to reflection class map */ private array $reflectionClassCache; /** @return mixed */ public function decode(string $json) { $value = json_decode($json, true); if (json_last_error()) { throw new \RuntimeException('JSON decoding error: ' . json_last_error_msg()); } return $this->decodeRecursive($value); } /** * @param mixed $value * @return mixed */ private function decodeRecursive($value) { if (\is_array($value)) { if (isset($value['nodeType'])) { if ($value['nodeType'] === 'Comment' || $value['nodeType'] === 'Comment_Doc') { return $this->decodeComment($value); } return $this->decodeNode($value); } return $this->decodeArray($value); } return $value; } private function decodeArray(array $array): array { $decodedArray = []; foreach ($array as $key => $value) { $decodedArray[$key] = $this->decodeRecursive($value); } return $decodedArray; } private function decodeNode(array $value): Node { $nodeType = $value['nodeType']; if (!\is_string($nodeType)) { throw new \RuntimeException('Node type must be a string'); } $reflectionClass = $this->reflectionClassFromNodeType($nodeType); $node = $reflectionClass->newInstanceWithoutConstructor(); if (isset($value['attributes'])) { if (!\is_array($value['attributes'])) { throw new \RuntimeException('Attributes must be an array'); } $node->setAttributes($this->decodeArray($value['attributes'])); } foreach ($value as $name => $subNode) { if ($name === 'nodeType' || $name === 'attributes') { continue; } $node->$name = $this->decodeRecursive($subNode); } return $node; } private function decodeComment(array $value): Comment { $className = $value['nodeType'] === 'Comment' ? Comment::class : Comment\Doc::class; if (!isset($value['text'])) { throw new \RuntimeException('Comment must have text'); } return new $className( $value['text'], $value['line'] ?? -1, $value['filePos'] ?? -1, $value['tokenPos'] ?? -1, $value['endLine'] ?? -1, $value['endFilePos'] ?? -1, $value['endTokenPos'] ?? -1 ); } /** @return \ReflectionClass<Node> */ private function reflectionClassFromNodeType(string $nodeType): \ReflectionClass { if (!isset($this->reflectionClassCache[$nodeType])) { $className = $this->classNameFromNodeType($nodeType); $this->reflectionClassCache[$nodeType] = new \ReflectionClass($className); } return $this->reflectionClassCache[$nodeType]; } /** @return class-string<Node> */ private function classNameFromNodeType(string $nodeType): string { $className = 'PhpParser\\Node\\' . strtr($nodeType, '_', '\\'); if (class_exists($className)) { return $className; } $className .= '_'; if (class_exists($className)) { return $className; } throw new \RuntimeException("Unknown node type \"$nodeType\""); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Parser.php
lib/PhpParser/Parser.php
<?php declare(strict_types=1); namespace PhpParser; interface Parser { /** * Parses PHP code into a node tree. * * @param string $code The source code to parse * @param ErrorHandler|null $errorHandler Error handler to use for lexer/parser errors, defaults * to ErrorHandler\Throwing. * * @return Node\Stmt[]|null Array of statements (or null non-throwing error handler is used and * the parser was unable to recover from an error). */ public function parse(string $code, ?ErrorHandler $errorHandler = null): ?array; /** * Return tokens for the last parse. * * @return Token[] */ public function getTokens(): array; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Error.php
lib/PhpParser/Error.php
<?php declare(strict_types=1); namespace PhpParser; class Error extends \RuntimeException { protected string $rawMessage; /** @var array<string, mixed> */ protected array $attributes; /** * Creates an Exception signifying a parse error. * * @param string $message Error message * @param array<string, mixed> $attributes Attributes of node/token where error occurred */ public function __construct(string $message, array $attributes = []) { $this->rawMessage = $message; $this->attributes = $attributes; $this->updateMessage(); } /** * Gets the error message * * @return string Error message */ public function getRawMessage(): string { return $this->rawMessage; } /** * Gets the line the error starts in. * * @return int Error start line * @phpstan-return -1|positive-int */ public function getStartLine(): int { return $this->attributes['startLine'] ?? -1; } /** * Gets the line the error ends in. * * @return int Error end line * @phpstan-return -1|positive-int */ public function getEndLine(): int { return $this->attributes['endLine'] ?? -1; } /** * Gets the attributes of the node/token the error occurred at. * * @return array<string, mixed> */ public function getAttributes(): array { return $this->attributes; } /** * Sets the attributes of the node/token the error occurred at. * * @param array<string, mixed> $attributes */ public function setAttributes(array $attributes): void { $this->attributes = $attributes; $this->updateMessage(); } /** * Sets the line of the PHP file the error occurred in. * * @param string $message Error message */ public function setRawMessage(string $message): void { $this->rawMessage = $message; $this->updateMessage(); } /** * Sets the line the error starts in. * * @param int $line Error start line */ public function setStartLine(int $line): void { $this->attributes['startLine'] = $line; $this->updateMessage(); } /** * Returns whether the error has start and end column information. * * For column information enable the startFilePos and endFilePos in the lexer options. */ public function hasColumnInfo(): bool { return isset($this->attributes['startFilePos'], $this->attributes['endFilePos']); } /** * Gets the start column (1-based) into the line where the error started. * * @param string $code Source code of the file */ public function getStartColumn(string $code): int { if (!$this->hasColumnInfo()) { throw new \RuntimeException('Error does not have column information'); } return $this->toColumn($code, $this->attributes['startFilePos']); } /** * Gets the end column (1-based) into the line where the error ended. * * @param string $code Source code of the file */ public function getEndColumn(string $code): int { if (!$this->hasColumnInfo()) { throw new \RuntimeException('Error does not have column information'); } return $this->toColumn($code, $this->attributes['endFilePos']); } /** * Formats message including line and column information. * * @param string $code Source code associated with the error, for calculation of the columns * * @return string Formatted message */ public function getMessageWithColumnInfo(string $code): string { return sprintf( '%s from %d:%d to %d:%d', $this->getRawMessage(), $this->getStartLine(), $this->getStartColumn($code), $this->getEndLine(), $this->getEndColumn($code) ); } /** * Converts a file offset into a column. * * @param string $code Source code that $pos indexes into * @param int $pos 0-based position in $code * * @return int 1-based column (relative to start of line) */ private function toColumn(string $code, int $pos): int { if ($pos > strlen($code)) { throw new \RuntimeException('Invalid position information'); } $lineStartPos = strrpos($code, "\n", $pos - strlen($code)); if (false === $lineStartPos) { $lineStartPos = -1; } return $pos - $lineStartPos; } /** * Updates the exception message after a change to rawMessage or rawLine. */ protected function updateMessage(): void { $this->message = $this->rawMessage; if (-1 === $this->getStartLine()) { $this->message .= ' on unknown line'; } else { $this->message .= ' on line ' . $this->getStartLine(); } } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NodeTraverserInterface.php
lib/PhpParser/NodeTraverserInterface.php
<?php declare(strict_types=1); namespace PhpParser; interface NodeTraverserInterface { /** * Adds a visitor. * * @param NodeVisitor $visitor Visitor to add */ public function addVisitor(NodeVisitor $visitor): void; /** * Removes an added visitor. */ public function removeVisitor(NodeVisitor $visitor): void; /** * Traverses an array of nodes using the registered visitors. * * @param Node[] $nodes Array of nodes * * @return Node[] Traversed array of nodes */ public function traverse(array $nodes): array; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/PrettyPrinter.php
lib/PhpParser/PrettyPrinter.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr; interface PrettyPrinter { /** * Pretty prints an array of statements. * * @param Node[] $stmts Array of statements * * @return string Pretty printed statements */ public function prettyPrint(array $stmts): string; /** * Pretty prints an expression. * * @param Expr $node Expression node * * @return string Pretty printed node */ public function prettyPrintExpr(Expr $node): string; /** * Pretty prints a file of statements (includes the opening <?php tag if it is required). * * @param Node[] $stmts Array of statements * * @return string Pretty printed statements */ public function prettyPrintFile(array $stmts): string; /** * Perform a format-preserving pretty print of an AST. * * The format preservation is best effort. For some changes to the AST the formatting will not * be preserved (at least not locally). * * In order to use this method a number of prerequisites must be satisfied: * * The startTokenPos and endTokenPos attributes in the lexer must be enabled. * * The CloningVisitor must be run on the AST prior to modification. * * The original tokens must be provided, using the getTokens() method on the lexer. * * @param Node[] $stmts Modified AST with links to original AST * @param Node[] $origStmts Original AST with token offset information * @param Token[] $origTokens Tokens of the original code */ public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node.php
lib/PhpParser/Node.php
<?php declare(strict_types=1); namespace PhpParser; interface Node { /** * Gets the type of the node. * * @psalm-return non-empty-string * @return string Type of the node */ public function getType(): string; /** * Gets the names of the sub nodes. * * @return string[] Names of sub nodes */ public function getSubNodeNames(): array; /** * Gets line the node started in (alias of getStartLine). * * @return int Start line (or -1 if not available) * @phpstan-return -1|positive-int * * @deprecated Use getStartLine() instead */ public function getLine(): int; /** * Gets line the node started in. * * Requires the 'startLine' attribute to be enabled in the lexer (enabled by default). * * @return int Start line (or -1 if not available) * @phpstan-return -1|positive-int */ public function getStartLine(): int; /** * Gets the line the node ended in. * * Requires the 'endLine' attribute to be enabled in the lexer (enabled by default). * * @return int End line (or -1 if not available) * @phpstan-return -1|positive-int */ public function getEndLine(): int; /** * Gets the token offset of the first token that is part of this node. * * The offset is an index into the array returned by Lexer::getTokens(). * * Requires the 'startTokenPos' attribute to be enabled in the lexer (DISABLED by default). * * @return int Token start position (or -1 if not available) */ public function getStartTokenPos(): int; /** * Gets the token offset of the last token that is part of this node. * * The offset is an index into the array returned by Lexer::getTokens(). * * Requires the 'endTokenPos' attribute to be enabled in the lexer (DISABLED by default). * * @return int Token end position (or -1 if not available) */ public function getEndTokenPos(): int; /** * Gets the file offset of the first character that is part of this node. * * Requires the 'startFilePos' attribute to be enabled in the lexer (DISABLED by default). * * @return int File start position (or -1 if not available) */ public function getStartFilePos(): int; /** * Gets the file offset of the last character that is part of this node. * * Requires the 'endFilePos' attribute to be enabled in the lexer (DISABLED by default). * * @return int File end position (or -1 if not available) */ public function getEndFilePos(): int; /** * Gets all comments directly preceding this node. * * The comments are also available through the "comments" attribute. * * @return Comment[] */ public function getComments(): array; /** * Gets the doc comment of the node. * * @return null|Comment\Doc Doc comment object or null */ public function getDocComment(): ?Comment\Doc; /** * Sets the doc comment of the node. * * This will either replace an existing doc comment or add it to the comments array. * * @param Comment\Doc $docComment Doc comment to set */ public function setDocComment(Comment\Doc $docComment): void; /** * Sets an attribute on a node. * * @param mixed $value */ public function setAttribute(string $key, $value): void; /** * Returns whether an attribute exists. */ public function hasAttribute(string $key): bool; /** * Returns the value of an attribute. * * @param mixed $default * * @return mixed */ public function getAttribute(string $key, $default = null); /** * Returns all the attributes of this node. * * @return array<string, mixed> */ public function getAttributes(): array; /** * Replaces all the attributes of this node. * * @param array<string, mixed> $attributes */ public function setAttributes(array $attributes): void; }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/ConstExprEvaluationException.php
lib/PhpParser/ConstExprEvaluationException.php
<?php declare(strict_types=1); namespace PhpParser; class ConstExprEvaluationException extends \Exception { }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NodeDumper.php
lib/PhpParser/NodeDumper.php
<?php declare(strict_types=1); namespace PhpParser; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\Include_; use PhpParser\Node\Expr\List_; use PhpParser\Node\Scalar\Int_; use PhpParser\Node\Scalar\InterpolatedString; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt\GroupUse; use PhpParser\Node\Stmt\Use_; use PhpParser\Node\UseItem; class NodeDumper { private bool $dumpComments; private bool $dumpPositions; private bool $dumpOtherAttributes; private ?string $code; private string $res; private string $nl; private const IGNORE_ATTRIBUTES = [ 'comments' => true, 'startLine' => true, 'endLine' => true, 'startFilePos' => true, 'endFilePos' => true, 'startTokenPos' => true, 'endTokenPos' => true, ]; /** * Constructs a NodeDumper. * * Supported options: * * bool dumpComments: Whether comments should be dumped. * * bool dumpPositions: Whether line/offset information should be dumped. To dump offset * information, the code needs to be passed to dump(). * * bool dumpOtherAttributes: Whether non-comment, non-position attributes should be dumped. * * @param array $options Options (see description) */ public function __construct(array $options = []) { $this->dumpComments = !empty($options['dumpComments']); $this->dumpPositions = !empty($options['dumpPositions']); $this->dumpOtherAttributes = !empty($options['dumpOtherAttributes']); } /** * Dumps a node or array. * * @param array|Node $node Node or array to dump * @param string|null $code Code corresponding to dumped AST. This only needs to be passed if * the dumpPositions option is enabled and the dumping of node offsets * is desired. * * @return string Dumped value */ public function dump($node, ?string $code = null): string { $this->code = $code; $this->res = ''; $this->nl = "\n"; $this->dumpRecursive($node, false); return $this->res; } /** @param mixed $node */ protected function dumpRecursive($node, bool $indent = true): void { if ($indent) { $this->nl .= " "; } if ($node instanceof Node) { $this->res .= $node->getType(); if ($this->dumpPositions && null !== $p = $this->dumpPosition($node)) { $this->res .= $p; } $this->res .= '('; foreach ($node->getSubNodeNames() as $key) { $this->res .= "$this->nl " . $key . ': '; $value = $node->$key; if (\is_int($value)) { if ('flags' === $key || 'newModifier' === $key) { $this->res .= $this->dumpFlags($value); continue; } if ('type' === $key && $node instanceof Include_) { $this->res .= $this->dumpIncludeType($value); continue; } if ('type' === $key && ($node instanceof Use_ || $node instanceof UseItem || $node instanceof GroupUse)) { $this->res .= $this->dumpUseType($value); continue; } } $this->dumpRecursive($value); } if ($this->dumpComments && $comments = $node->getComments()) { $this->res .= "$this->nl comments: "; $this->dumpRecursive($comments); } if ($this->dumpOtherAttributes) { foreach ($node->getAttributes() as $key => $value) { if (isset(self::IGNORE_ATTRIBUTES[$key])) { continue; } $this->res .= "$this->nl $key: "; if (\is_int($value)) { if ('kind' === $key) { if ($node instanceof Int_) { $this->res .= $this->dumpIntKind($value); continue; } if ($node instanceof String_ || $node instanceof InterpolatedString) { $this->res .= $this->dumpStringKind($value); continue; } if ($node instanceof Array_) { $this->res .= $this->dumpArrayKind($value); continue; } if ($node instanceof List_) { $this->res .= $this->dumpListKind($value); continue; } } } $this->dumpRecursive($value); } } $this->res .= "$this->nl)"; } elseif (\is_array($node)) { $this->res .= 'array('; foreach ($node as $key => $value) { $this->res .= "$this->nl " . $key . ': '; $this->dumpRecursive($value); } $this->res .= "$this->nl)"; } elseif ($node instanceof Comment) { $this->res .= \str_replace("\n", $this->nl, $node->getReformattedText()); } elseif (\is_string($node)) { $this->res .= \str_replace("\n", $this->nl, $node); } elseif (\is_int($node) || \is_float($node)) { $this->res .= $node; } elseif (null === $node) { $this->res .= 'null'; } elseif (false === $node) { $this->res .= 'false'; } elseif (true === $node) { $this->res .= 'true'; } else { throw new \InvalidArgumentException('Can only dump nodes and arrays.'); } if ($indent) { $this->nl = \substr($this->nl, 0, -4); } } protected function dumpFlags(int $flags): string { $strs = []; if ($flags & Modifiers::PUBLIC) { $strs[] = 'PUBLIC'; } if ($flags & Modifiers::PROTECTED) { $strs[] = 'PROTECTED'; } if ($flags & Modifiers::PRIVATE) { $strs[] = 'PRIVATE'; } if ($flags & Modifiers::ABSTRACT) { $strs[] = 'ABSTRACT'; } if ($flags & Modifiers::STATIC) { $strs[] = 'STATIC'; } if ($flags & Modifiers::FINAL) { $strs[] = 'FINAL'; } if ($flags & Modifiers::READONLY) { $strs[] = 'READONLY'; } if ($flags & Modifiers::PUBLIC_SET) { $strs[] = 'PUBLIC_SET'; } if ($flags & Modifiers::PROTECTED_SET) { $strs[] = 'PROTECTED_SET'; } if ($flags & Modifiers::PRIVATE_SET) { $strs[] = 'PRIVATE_SET'; } if ($strs) { return implode(' | ', $strs) . ' (' . $flags . ')'; } else { return (string) $flags; } } /** @param array<int, string> $map */ private function dumpEnum(int $value, array $map): string { if (!isset($map[$value])) { return (string) $value; } return $map[$value] . ' (' . $value . ')'; } private function dumpIncludeType(int $type): string { return $this->dumpEnum($type, [ Include_::TYPE_INCLUDE => 'TYPE_INCLUDE', Include_::TYPE_INCLUDE_ONCE => 'TYPE_INCLUDE_ONCE', Include_::TYPE_REQUIRE => 'TYPE_REQUIRE', Include_::TYPE_REQUIRE_ONCE => 'TYPE_REQUIRE_ONCE', ]); } private function dumpUseType(int $type): string { return $this->dumpEnum($type, [ Use_::TYPE_UNKNOWN => 'TYPE_UNKNOWN', Use_::TYPE_NORMAL => 'TYPE_NORMAL', Use_::TYPE_FUNCTION => 'TYPE_FUNCTION', Use_::TYPE_CONSTANT => 'TYPE_CONSTANT', ]); } private function dumpIntKind(int $kind): string { return $this->dumpEnum($kind, [ Int_::KIND_BIN => 'KIND_BIN', Int_::KIND_OCT => 'KIND_OCT', Int_::KIND_DEC => 'KIND_DEC', Int_::KIND_HEX => 'KIND_HEX', ]); } private function dumpStringKind(int $kind): string { return $this->dumpEnum($kind, [ String_::KIND_SINGLE_QUOTED => 'KIND_SINGLE_QUOTED', String_::KIND_DOUBLE_QUOTED => 'KIND_DOUBLE_QUOTED', String_::KIND_HEREDOC => 'KIND_HEREDOC', String_::KIND_NOWDOC => 'KIND_NOWDOC', ]); } private function dumpArrayKind(int $kind): string { return $this->dumpEnum($kind, [ Array_::KIND_LONG => 'KIND_LONG', Array_::KIND_SHORT => 'KIND_SHORT', ]); } private function dumpListKind(int $kind): string { return $this->dumpEnum($kind, [ List_::KIND_LIST => 'KIND_LIST', List_::KIND_ARRAY => 'KIND_ARRAY', ]); } /** * Dump node position, if possible. * * @param Node $node Node for which to dump position * * @return string|null Dump of position, or null if position information not available */ protected function dumpPosition(Node $node): ?string { if (!$node->hasAttribute('startLine') || !$node->hasAttribute('endLine')) { return null; } $start = $node->getStartLine(); $end = $node->getEndLine(); if ($node->hasAttribute('startFilePos') && $node->hasAttribute('endFilePos') && null !== $this->code ) { $start .= ':' . $this->toColumn($this->code, $node->getStartFilePos()); $end .= ':' . $this->toColumn($this->code, $node->getEndFilePos()); } return "[$start - $end]"; } // Copied from Error class private function toColumn(string $code, int $pos): int { if ($pos > strlen($code)) { throw new \RuntimeException('Invalid position information'); } $lineStartPos = strrpos($code, "\n", $pos - strlen($code)); if (false === $lineStartPos) { $lineStartPos = -1; } return $pos - $lineStartPos; } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/compatibility_tokens.php
lib/PhpParser/compatibility_tokens.php
<?php declare(strict_types=1); namespace PhpParser; if (!\function_exists('PhpParser\defineCompatibilityTokens')) { function defineCompatibilityTokens(): void { $compatTokens = [ // PHP 8.0 'T_NAME_QUALIFIED', 'T_NAME_FULLY_QUALIFIED', 'T_NAME_RELATIVE', 'T_MATCH', 'T_NULLSAFE_OBJECT_OPERATOR', 'T_ATTRIBUTE', // PHP 8.1 'T_ENUM', 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'T_READONLY', // PHP 8.4 'T_PROPERTY_C', 'T_PUBLIC_SET', 'T_PROTECTED_SET', 'T_PRIVATE_SET', // PHP 8.5 'T_PIPE', 'T_VOID_CAST', ]; // PHP-Parser might be used together with another library that also emulates some or all // of these tokens. Perform a sanity-check that all already defined tokens have been // assigned a unique ID. $usedTokenIds = []; foreach ($compatTokens as $token) { if (\defined($token)) { $tokenId = \constant($token); if (!\is_int($tokenId)) { throw new \Error(sprintf( 'Token %s has ID of type %s, should be int. ' . 'You may be using a library with broken token emulation', $token, \gettype($tokenId) )); } $clashingToken = $usedTokenIds[$tokenId] ?? null; if ($clashingToken !== null) { throw new \Error(sprintf( 'Token %s has same ID as token %s, ' . 'you may be using a library with broken token emulation', $token, $clashingToken )); } $usedTokenIds[$tokenId] = $token; } } // Now define any tokens that have not yet been emulated. Try to assign IDs from -1 // downwards, but skip any IDs that may already be in use. $newTokenId = -1; foreach ($compatTokens as $token) { if (!\defined($token)) { while (isset($usedTokenIds[$newTokenId])) { $newTokenId--; } \define($token, $newTokenId); $newTokenId--; } } } defineCompatibilityTokens(); }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NodeAbstract.php
lib/PhpParser/NodeAbstract.php
<?php declare(strict_types=1); namespace PhpParser; abstract class NodeAbstract implements Node, \JsonSerializable { /** @var array<string, mixed> Attributes */ protected array $attributes; /** * Creates a Node. * * @param array<string, mixed> $attributes Array of attributes */ public function __construct(array $attributes = []) { $this->attributes = $attributes; } /** * Gets line the node started in (alias of getStartLine). * * @return int Start line (or -1 if not available) * @phpstan-return -1|positive-int */ public function getLine(): int { return $this->attributes['startLine'] ?? -1; } /** * Gets line the node started in. * * Requires the 'startLine' attribute to be enabled in the lexer (enabled by default). * * @return int Start line (or -1 if not available) * @phpstan-return -1|positive-int */ public function getStartLine(): int { return $this->attributes['startLine'] ?? -1; } /** * Gets the line the node ended in. * * Requires the 'endLine' attribute to be enabled in the lexer (enabled by default). * * @return int End line (or -1 if not available) * @phpstan-return -1|positive-int */ public function getEndLine(): int { return $this->attributes['endLine'] ?? -1; } /** * Gets the token offset of the first token that is part of this node. * * The offset is an index into the array returned by Lexer::getTokens(). * * Requires the 'startTokenPos' attribute to be enabled in the lexer (DISABLED by default). * * @return int Token start position (or -1 if not available) */ public function getStartTokenPos(): int { return $this->attributes['startTokenPos'] ?? -1; } /** * Gets the token offset of the last token that is part of this node. * * The offset is an index into the array returned by Lexer::getTokens(). * * Requires the 'endTokenPos' attribute to be enabled in the lexer (DISABLED by default). * * @return int Token end position (or -1 if not available) */ public function getEndTokenPos(): int { return $this->attributes['endTokenPos'] ?? -1; } /** * Gets the file offset of the first character that is part of this node. * * Requires the 'startFilePos' attribute to be enabled in the lexer (DISABLED by default). * * @return int File start position (or -1 if not available) */ public function getStartFilePos(): int { return $this->attributes['startFilePos'] ?? -1; } /** * Gets the file offset of the last character that is part of this node. * * Requires the 'endFilePos' attribute to be enabled in the lexer (DISABLED by default). * * @return int File end position (or -1 if not available) */ public function getEndFilePos(): int { return $this->attributes['endFilePos'] ?? -1; } /** * Gets all comments directly preceding this node. * * The comments are also available through the "comments" attribute. * * @return Comment[] */ public function getComments(): array { return $this->attributes['comments'] ?? []; } /** * Gets the doc comment of the node. * * @return null|Comment\Doc Doc comment object or null */ public function getDocComment(): ?Comment\Doc { $comments = $this->getComments(); for ($i = count($comments) - 1; $i >= 0; $i--) { $comment = $comments[$i]; if ($comment instanceof Comment\Doc) { return $comment; } } return null; } /** * Sets the doc comment of the node. * * This will either replace an existing doc comment or add it to the comments array. * * @param Comment\Doc $docComment Doc comment to set */ public function setDocComment(Comment\Doc $docComment): void { $comments = $this->getComments(); for ($i = count($comments) - 1; $i >= 0; $i--) { if ($comments[$i] instanceof Comment\Doc) { // Replace existing doc comment. $comments[$i] = $docComment; $this->setAttribute('comments', $comments); return; } } // Append new doc comment. $comments[] = $docComment; $this->setAttribute('comments', $comments); } public function setAttribute(string $key, $value): void { $this->attributes[$key] = $value; } public function hasAttribute(string $key): bool { return array_key_exists($key, $this->attributes); } public function getAttribute(string $key, $default = null) { if (array_key_exists($key, $this->attributes)) { return $this->attributes[$key]; } return $default; } public function getAttributes(): array { return $this->attributes; } public function setAttributes(array $attributes): void { $this->attributes = $attributes; } /** * @return array<string, mixed> */ public function jsonSerialize(): array { return ['nodeType' => $this->getType()] + get_object_vars($this); } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false
nikic/PHP-Parser
https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/NodeTraverser.php
lib/PhpParser/NodeTraverser.php
<?php declare(strict_types=1); namespace PhpParser; class NodeTraverser implements NodeTraverserInterface { /** * @deprecated Use NodeVisitor::DONT_TRAVERSE_CHILDREN instead. */ public const DONT_TRAVERSE_CHILDREN = NodeVisitor::DONT_TRAVERSE_CHILDREN; /** * @deprecated Use NodeVisitor::STOP_TRAVERSAL instead. */ public const STOP_TRAVERSAL = NodeVisitor::STOP_TRAVERSAL; /** * @deprecated Use NodeVisitor::REMOVE_NODE instead. */ public const REMOVE_NODE = NodeVisitor::REMOVE_NODE; /** * @deprecated Use NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN instead. */ public const DONT_TRAVERSE_CURRENT_AND_CHILDREN = NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN; /** @var list<NodeVisitor> Visitors */ protected array $visitors = []; /** @var bool Whether traversal should be stopped */ protected bool $stopTraversal; /** * Create a traverser with the given visitors. * * @param NodeVisitor ...$visitors Node visitors */ public function __construct(NodeVisitor ...$visitors) { $this->visitors = $visitors; } /** * Adds a visitor. * * @param NodeVisitor $visitor Visitor to add */ public function addVisitor(NodeVisitor $visitor): void { $this->visitors[] = $visitor; } /** * Removes an added visitor. */ public function removeVisitor(NodeVisitor $visitor): void { $index = array_search($visitor, $this->visitors); if ($index !== false) { array_splice($this->visitors, $index, 1, []); } } /** * Traverses an array of nodes using the registered visitors. * * @param Node[] $nodes Array of nodes * * @return Node[] Traversed array of nodes */ public function traverse(array $nodes): array { $this->stopTraversal = false; foreach ($this->visitors as $visitor) { if (null !== $return = $visitor->beforeTraverse($nodes)) { $nodes = $return; } } $nodes = $this->traverseArray($nodes); for ($i = \count($this->visitors) - 1; $i >= 0; --$i) { $visitor = $this->visitors[$i]; if (null !== $return = $visitor->afterTraverse($nodes)) { $nodes = $return; } } return $nodes; } /** * Recursively traverse a node. * * @param Node $node Node to traverse. */ protected function traverseNode(Node $node): void { foreach ($node->getSubNodeNames() as $name) { $subNode = $node->$name; if (\is_array($subNode)) { $node->$name = $this->traverseArray($subNode); if ($this->stopTraversal) { break; } continue; } if (!$subNode instanceof Node) { continue; } $traverseChildren = true; $visitorIndex = -1; foreach ($this->visitors as $visitorIndex => $visitor) { $return = $visitor->enterNode($subNode); if (null !== $return) { if ($return instanceof Node) { $this->ensureReplacementReasonable($subNode, $return); $subNode = $node->$name = $return; } elseif (NodeVisitor::DONT_TRAVERSE_CHILDREN === $return) { $traverseChildren = false; } elseif (NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN === $return) { $traverseChildren = false; break; } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { $this->stopTraversal = true; break 2; } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { $node->$name = null; continue 2; } else { throw new \LogicException( 'enterNode() returned invalid value of type ' . gettype($return) ); } } } if ($traverseChildren) { $this->traverseNode($subNode); if ($this->stopTraversal) { break; } } for (; $visitorIndex >= 0; --$visitorIndex) { $visitor = $this->visitors[$visitorIndex]; $return = $visitor->leaveNode($subNode); if (null !== $return) { if ($return instanceof Node) { $this->ensureReplacementReasonable($subNode, $return); $subNode = $node->$name = $return; } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { $this->stopTraversal = true; break 2; } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { $node->$name = null; break; } elseif (\is_array($return)) { throw new \LogicException( 'leaveNode() may only return an array ' . 'if the parent structure is an array' ); } else { throw new \LogicException( 'leaveNode() returned invalid value of type ' . gettype($return) ); } } } } } /** * Recursively traverse array (usually of nodes). * * @param Node[] $nodes Array to traverse * * @return Node[] Result of traversal (may be original array or changed one) */ protected function traverseArray(array $nodes): array { $doNodes = []; foreach ($nodes as $i => $node) { if (!$node instanceof Node) { if (\is_array($node)) { throw new \LogicException('Invalid node structure: Contains nested arrays'); } continue; } $traverseChildren = true; $visitorIndex = -1; foreach ($this->visitors as $visitorIndex => $visitor) { $return = $visitor->enterNode($node); if (null !== $return) { if ($return instanceof Node) { $this->ensureReplacementReasonable($node, $return); $nodes[$i] = $node = $return; } elseif (\is_array($return)) { $doNodes[] = [$i, $return]; continue 2; } elseif (NodeVisitor::REMOVE_NODE === $return) { $doNodes[] = [$i, []]; continue 2; } elseif (NodeVisitor::DONT_TRAVERSE_CHILDREN === $return) { $traverseChildren = false; } elseif (NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN === $return) { $traverseChildren = false; break; } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { $this->stopTraversal = true; break 2; } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { throw new \LogicException( 'REPLACE_WITH_NULL can not be used if the parent structure is an array'); } else { throw new \LogicException( 'enterNode() returned invalid value of type ' . gettype($return) ); } } } if ($traverseChildren) { $this->traverseNode($node); if ($this->stopTraversal) { break; } } for (; $visitorIndex >= 0; --$visitorIndex) { $visitor = $this->visitors[$visitorIndex]; $return = $visitor->leaveNode($node); if (null !== $return) { if ($return instanceof Node) { $this->ensureReplacementReasonable($node, $return); $nodes[$i] = $node = $return; } elseif (\is_array($return)) { $doNodes[] = [$i, $return]; break; } elseif (NodeVisitor::REMOVE_NODE === $return) { $doNodes[] = [$i, []]; break; } elseif (NodeVisitor::STOP_TRAVERSAL === $return) { $this->stopTraversal = true; break 2; } elseif (NodeVisitor::REPLACE_WITH_NULL === $return) { throw new \LogicException( 'REPLACE_WITH_NULL can not be used if the parent structure is an array'); } else { throw new \LogicException( 'leaveNode() returned invalid value of type ' . gettype($return) ); } } } } if (!empty($doNodes)) { while (list($i, $replace) = array_pop($doNodes)) { array_splice($nodes, $i, 1, $replace); } } return $nodes; } private function ensureReplacementReasonable(Node $old, Node $new): void { if ($old instanceof Node\Stmt && $new instanceof Node\Expr) { throw new \LogicException( "Trying to replace statement ({$old->getType()}) " . "with expression ({$new->getType()}). Are you missing a " . "Stmt_Expression wrapper?" ); } if ($old instanceof Node\Expr && $new instanceof Node\Stmt) { throw new \LogicException( "Trying to replace expression ({$old->getType()}) " . "with statement ({$new->getType()})" ); } } }
php
BSD-3-Clause
8c360e27327c8bd29e1c57721574709d0d706118
2026-01-04T15:02:34.433891Z
false