/** * 获取常量说明文档 * * @param unknown $classname * @return multitype:|multitype:string */ static function getConstDocument($classname) { if (!class_exists($classname)) { return []; } $classref = new \ReflectionClass($classname); $filename = $classref->getFileName(); $filecontents = file_get_contents($filename); $parser = new Parser(new Emulative()); $stmt = $parser->parse($filecontents); $constants_Document = []; $classnode = self::_get_class_node($stmt, $classref->getShortName()); if (is_null($classnode)) { return $constants_Document; } foreach ($classnode->stmts as $value) { if ($value instanceof ClassConst) { foreach ($value->consts as $valueconsts) { if ($valueconsts instanceof Const_) { $docComment = $value->getDocComment(); if (!is_null($docComment)) { $constants_Document[$valueconsts->name] = $value->getDocComment()->getText(); } } } } } return $constants_Document; }
private function extract($file, ValidationExtractor $extractor = null) { if (!is_file($file = __DIR__ . '/Fixture/' . $file)) { throw new RuntimeException(sprintf('The file "%s" does not exist.', $file)); } $file = new \SplFileInfo($file); //use correct factory class depending on whether using Symfony 2 or 3 if (class_exists('Symfony\\Component\\Validator\\Mapping\\Factory\\LazyLoadingMetadataFactory')) { $metadataFactoryClass = 'Symfony\\Component\\Validator\\Mapping\\Factory\\LazyLoadingMetadataFactory'; } else { $metadataFactoryClass = 'Symfony\\Component\\Validator\\Mapping\\ClassMetadataFactory'; } if (null === $extractor) { $factory = new $metadataFactoryClass(new AnnotationLoader(new AnnotationReader())); $extractor = new ValidationExtractor($factory); } $lexer = new Lexer(); if (class_exists('PhpParser\\ParserFactory')) { $factory = new ParserFactory(); $parser = $factory->create(ParserFactory::PREFER_PHP7, $lexer); } else { $parser = new Parser($lexer); } $ast = $parser->parse(file_get_contents($file)); $catalogue = new MessageCatalogue(); $extractor->visitPhpFile($file, $catalogue, $ast); return $catalogue; }
public function provideGetStatus() { $parser = new Parser(new Lexer()); foreach ($this->getTestCases() as $testId => $testCase) { (yield $testId => [$testCase[0], $parser->parse($testCase[1]), $parser->parse($testCase[2])]); } }
/** * @param ExerciseInterface $exercise * @param string $fileName * @return ResultInterface */ public function check(ExerciseInterface $exercise, $fileName) { if (!$exercise instanceof FunctionRequirementsExerciseCheck) { throw new \InvalidArgumentException(); } $requiredFunctions = $exercise->getRequiredFunctions(); $bannedFunctions = $exercise->getBannedFunctions(); $code = file_get_contents($fileName); try { $ast = $this->parser->parse($code); } catch (Error $e) { return Failure::fromCheckAndCodeParseFailure($this, $e, $fileName); } $visitor = new FunctionVisitor($requiredFunctions, $bannedFunctions); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $traverser->traverse($ast); $bannedFunctions = []; if ($visitor->hasUsedBannedFunctions()) { $bannedFunctions = array_map(function (FuncCall $node) { return ['function' => $node->name->__toString(), 'line' => $node->getLine()]; }, $visitor->getBannedUsages()); } $missingFunctions = []; if (!$visitor->hasMetFunctionRequirements()) { $missingFunctions = $visitor->getMissingRequirements(); } if (!empty($bannedFunctions) || !empty($missingFunctions)) { return new FunctionRequirementsFailure($this, $bannedFunctions, $missingFunctions); } return Success::fromCheck($this); }
/** * Parse a file and return found tags. * * @param string $filePath Full path to filename. * @return array */ public function getTags($filePath) { // Create a PHP-Parser instance. $parser = new PhpParser(new Lexer(array('usedAttributes' => array('startLine', 'endLine', 'startFilePos', 'endFilePos')))); // Parse the source code into a list of statements. $source = $this->getContents($filePath); $statements = $parser->parse($source); $traverser = new NodeTraverser(); // Make sure all names are resolved as fully qualified. $traverser->addVisitor(new NameResolver()); // Create visitors that turn statements into tags. $visitors = array(new Visitor\ClassDefinition(), new Visitor\ClassReference(), new Visitor\ConstantDefinition(), new Visitor\FunctionDefinition(), new Visitor\GlobalVariableDefinition(), new Visitor\InterfaceDefinition(), new Visitor\TraitDefinition()); foreach ($visitors as $visitor) { $traverser->addVisitor($visitor); } $traverser->traverse($statements); // Extract tags from the visitors. $tags = array(); foreach ($visitors as $visitor) { $tags = array_merge($tags, array_map(function (Tag $tag) use($source) { $comment = substr($source, $tag->getStartFilePos(), $tag->getEndFilePos() - $tag->getStartFilePos() + 1); if (($bracePos = strpos($comment, '{')) !== false) { $comment = substr($comment, 0, $bracePos) . ' {}'; } return $tag->setComment(preg_replace('/\\s+/', ' ', $comment)); }, $visitor->getTags())); } return $tags; }
/** * ClassDiff constructor. * * @param string $currentFilePath * @param string $currentClassName * @param ClassGenerator $newClassGenerator */ public function __construct($currentFilePath, $currentClassName, ClassGenerator $newClassGenerator) { $this->currentFilePath = $currentFilePath; $this->currentClassName = $currentClassName; $this->currentClassCode = file_get_contents($currentFilePath); $this->currentClassGenerator = $this->getGeneratorFromReflection(new ClassReflection($currentClassName)); $this->newClassGenerator = $newClassGenerator; /* * PHP Reflections don't take into account use statements, so an entire * plugin is needed just for that. //shakes head */ $parser = new Parser(new Lexer()); $nodes = $parser->parse($this->currentClassCode); foreach ($nodes as $node) { /** @var $node Namespace_ */ if (get_class($node) == 'PhpParser\\Node\\Stmt\\Namespace_') { /** @var Use_ $stmt */ foreach ($node->stmts as $stmt) { if (get_class($stmt) == 'PhpParser\\Node\\Stmt\\Use_') { /** @var UseUse $use */ foreach ($stmt->uses as $use) { $this->currentClassGenerator->addUse($use->name->toString()); } } } } } if (in_array($this->currentClassGenerator->getExtendedClass(), $this->currentClassGenerator->getUses())) { $extended = new \ReflectionClass($this->currentClassGenerator->getExtendedClass()); $this->currentClassGenerator->setExtendedClass($extended->getShortName()); } }
/** * @param string $contents * * @return File */ public function build($contents) { $file = new File($this->codeFactory->buildNamespace()); $nodes = $this->PHPParser->parse($contents); $this->parser->parse($nodes, $file); return $file; }
protected function doTestPrettyPrintMethod($method, $name, $code, $dump) { $parser = new Parser(new Lexer\Emulative()); $prettyPrinter = new Standard(); $stmts = $parser->parse($code); $this->assertSame($this->canonicalize($dump), $this->canonicalize($prettyPrinter->{$method}($stmts)), $name); }
/** * @param Patch $patch * @param string $code * @return string */ private function applyPatch(Patch $patch, $code) { $statements = $this->parser->parse($code); foreach ($patch->getInsertions() as $insertion) { try { $codeToInsert = $insertion->getCode(); $codeToInsert = sprintf('<?php %s', preg_replace('/^\\s*<\\?php/', '', $codeToInsert)); $additionalStatements = $this->parser->parse($codeToInsert); } catch (Error $e) { //we should probably log this and have a dev mode or something continue; } switch ($insertion->getType()) { case CodeInsertion::TYPE_BEFORE: array_unshift($statements, ...$additionalStatements); break; case CodeInsertion::TYPE_AFTER: array_push($statements, ...$additionalStatements); break; } } foreach ($patch->getTransformers() as $transformer) { $statements = $transformer($statements); } return $this->printer->prettyPrintFile($statements); }
/** * Build a file */ function it_build_a_file(CodeFactoryContract $codeFactory, PHPNamespace $namespace, Parser $PHPParser, ParserContract $parser) { $codeFactory->buildNamespace()->willReturn($namespace)->shouldBeCalled(); $PHPParser->parse('foo')->willReturn([]); $file = $this->build('foo'); $file->shouldBeAnInstanceOf('FileModifier\\File\\File'); $parser->parse([], $file)->shouldHaveBeenCalled(); }
function it_catches_parse_exceptions(Parser $parser) { $file = new SplFileInfo('php://memory'); $parser->parse(Argument::any())->willThrow(new Error('Error ....')); $errors = $this->parse($file); $errors->shouldBeAnInstanceOf(ParseErrorsCollection::class); $errors->count()->shouldBe(1); }
/** * @return mixed */ public function getSyntaxTree() { return $this->lazyFactory->get(self::CONTEXT_AST, function () { $parser = new Parser(new Emulative()); $stmts = $parser->parse($this->file->getSource()); return $stmts; }); }
public function validate($code) { $traverser = new NodeTraverser(); $traverser->addVisitor($this->visitor); $code = "<?php\n" . $code; $ast = $this->parser->parse($code); $traverser->traverse($ast); }
/** * @param $mageClassPath * @return string */ public function getMagentoVersion($mageClassPath) { $parser = new PhpParser\Parser(new PhpParser\Lexer\Emulative()); $traverser = new PhpParser\NodeTraverser(); $this->xml = new SimpleXMLElement($traverser->traverse($parser->parse(file_get_contents($mageClassPath)))); $version = array($this->getVersionPart('major'), $this->getVersionPart('minor'), $this->getVersionPart('revision'), $this->getVersionPart('patch')); return implode('.', $version); }
/** * @param string $code * @param int $lineNumber * @return Node */ public function parse($code, $lineNumber) { $stmts = $this->parser->parse($code); $this->nodeVisitor->setLine($lineNumber); $this->nodeTraverser->addVisitor($this->nodeVisitor); $this->nodeTraverser->traverse($stmts); $node = $this->nodeVisitor->getNode(); return $node; }
/** * @dataProvider dataProvider * @param string $code * @param array $pattern */ public function testRun($code, $isNestedKeysName, array $pattern) { $code = '<?php ' . $code . ' = $foo;'; $parser = new Parser(new Lexer()); $prettyPrinter = new Standard(); $parserList = new ParserList($prettyPrinter); $resutlPattern = $parserList->parse($parser->parse($code)[0], $isNestedKeysName); $this->assertEquals($pattern, $resutlPattern); }
/** * @param string $file * * @return RefClass[] * @throws RuntimeException */ protected function parseFile($file) { $stmts = $this->phpParser->parse(file_get_contents($file)); $visitor = new RefVisitor($file); $this->traverser->addVisitor($visitor); $this->traverser->traverse($stmts); $this->traverser->removeVisitor($visitor); return $visitor->getClasses(); }
/** * @param ClassReflection $reflection * * @return string */ public function __invoke(ClassReflection $reflection) { $stubCode = ClassGenerator::fromReflection($reflection)->generate(); $isInterface = $reflection->isInterface(); if (!($isInterface || $reflection->isTrait())) { return $stubCode; } return $this->prettyPrinter->prettyPrint($this->replaceNodesRecursively($this->parser->parse('<?php ' . $stubCode), $isInterface)); }
/** * Get the fullyqualified imports and typehints. * * @param string $path * * @return string[] */ public function analyze($path) { $traverser = new NodeTraverser(); $traverser->addVisitor(new NameResolver()); $traverser->addVisitor($imports = new ImportVisitor()); $traverser->addVisitor($names = new NameVisitor()); $traverser->traverse($this->parser->parse(file_get_contents($path))); return array_unique(array_merge($imports->getImports(), $names->getNames())); }
protected function parsePhpFileFromStringAndTraverseWithVisitor(PhpFileInfo $phpFileInfo, $source, VisitorInterface $visitor) { $traverser = new NodeTraverser(); $traverser->addVisitor(new NameResolver()); $traverser->addVisitor($visitor->setPhpFileInfo($phpFileInfo)); $parser = new Parser(new Emulative()); $traverser->traverse($parser->parse($source)); return $phpFileInfo; }
/** * Take a PHP array and convert it to a string * * @param array $array * @return string * @throws RetrofitException */ public function printArray(array $array) { $string = var_export($array, true); $string = preg_replace('/\'\\$(.+)\'/', '$' . '\\1', $string); $statements = $this->parser->parse($string); if (null === $statements) { throw new RetrofitException('There was an error parsing the array'); } return $this->printer->prettyPrintFile($statements); }
/** * Create a function node from the given code. * * @param string $code; * @return \PhpParser\Node\Stmt\Function_ */ protected function createFunctionNode($code) { // Fix up code a bit to look like a function. $function = 'function testFunction() { ' . trim($code, ';') . '; }'; $parser = new Parser(new Lexer()); $nodes = $parser->parse('<?php ' . $function); return $nodes[0]; }
private function assertCompilerOutput($source, $expected) { $nodes = $this->parser->parse($source); $compiler = new SourceCompiler(new SimpleComponentCompiler(), $this->componentsProvider); $compiled = $compiler->compileTemplate($nodes); echo $compiled; $compiledNodes = $this->phpParser->parse($compiled); $expectedNodes = $this->phpParser->parse($expected); $this->assertEquals($this->serializer->serialize($expectedNodes), $this->serializer->serialize($compiledNodes)); }
/** * checkFileInternal(): defined by AbstractCheck. * * @see AbstractCheck::checkFileInternal() * * @param CheckContext $checkContext * @param Config $config */ protected function checkFileInternal(CheckContext $checkContext, Config $config) { $file = $checkContext->getFile(); $parser = new Parser(new Emulative()); try { $parser->parse($file->getSource()); } catch (PhpParserError $e) { $this->addViolation($file, $e->getStartLine(), 0, $e->getRawMessage(), Violation::SEVERITY_ERROR); } }
private function assertTokenizerOutput($source_file, $tokens_file) { $source = $this->loadFixture($source_file); $expected_tokens = json_decode($this->loadFixture($tokens_file), true); $nodes = $this->phpParser->parse($source); $tokenizer = new TreeEmittingTokenizer(new PhpNodesInputStream($nodes), $tree = new DecodingTreeBuilder()); $tokenizer->parse(); $actual_tokens = $tree->save(); $this->assertEquals($expected_tokens, $this->normalize($actual_tokens)); }
/** * * @param SourceIterator $source * @param array $options * @return array */ public function analyze(SourceIterator $source, array $options) { $result = []; foreach ($source as $filename => $code) { $ast = $this->parser->parse($code); $issues = $this->getIssues($ast, ['filename' => $filename]); $result[$filename] = new AnalyzedFile($filename, $issues); } return $result; }
/** * Get an array of reflections found in some code. * * @param Reflector $reflector * @param LocatedSource $locatedSource * @param IdentifierType $identifierType * @return \BetterReflection\Reflection\Reflection[] * @throws Exception\ParseToAstFailure */ public function findReflectionsOfType(Reflector $reflector, LocatedSource $locatedSource, IdentifierType $identifierType) { try { return $this->findReflectionsInTree->__invoke($reflector, $this->parser->parse($locatedSource->getSource()), $identifierType, $locatedSource); } catch (\Exception $exception) { throw Exception\ParseToAstFailure::fromLocatedSource($locatedSource, $exception); } catch (\Throwable $exception) { throw Exception\ParseToAstFailure::fromLocatedSource($locatedSource, $exception); } }
/** * This check grabs the contents of the student's solution and * attempts to parse it with `nikic/php-parser`. If any exceptions are thrown * by the parser, it is treated as a failure. * * @param ExerciseInterface $exercise The exercise to check against. * @param Input $input The command line arguments passed to the command. * @return ResultInterface The result of the check. */ public function check(ExerciseInterface $exercise, Input $input) { $code = file_get_contents($input->getArgument('program')); try { $this->parser->parse($code); } catch (Error $e) { return Failure::fromCheckAndCodeParseFailure($this, $e, $input->getArgument('program')); } return Success::fromCheck($this); }
private function tryParse(Parser $parser, ErrorHandler $errorHandler, $code) { $stmts = null; $error = null; try { $stmts = $parser->parse($code, $errorHandler); } catch (Error $error) { } return [$stmts, $error]; }
/** * @param ExerciseInterface $exercise * @param string $fileName * @return ResultInterface */ public function check(ExerciseInterface $exercise, $fileName) { $code = file_get_contents($fileName); try { $this->parser->parse($code); } catch (Error $e) { return Failure::fromCheckAndCodeParseFailure($this, $e, $fileName); } return Success::fromCheck($this); }