本文整理汇总了PHP中PhpParser\Parser类的典型用法代码示例。如果您正苦于以下问题:PHP Parser类的具体用法?PHP Parser怎么用?PHP Parser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Parser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getConstDocument
/**
* 获取常量说明文档
*
* @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;
}
示例2: extract
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;
}
示例3: provideGetStatus
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])]);
}
}
示例4: getTags
/**
* 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;
}
示例5: __construct
/**
* 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());
}
}
示例6: build
/**
* @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;
}
示例7: doTestPrettyPrintMethod
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);
}
示例8:
/**
* 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();
}
示例9: SplFileInfo
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);
}
示例10: getSyntaxTree
/**
* @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;
});
}
示例11: getMagentoVersion
/**
* @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);
}
示例12: testRun
/**
* @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);
}
示例13: parseFile
/**
* @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();
}
示例14: parsePhpFileFromStringAndTraverseWithVisitor
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;
}
示例15: check
/**
* @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);
}