作者:babet
项目:HellaEngin
/**
* 获取常量说明文档
*
* @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;
}
作者:clytemnestr
项目:JMSTranslationBundl
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;
}
作者:joshdifabi
项目:semantic-dif
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])]);
}
}
作者:jorisstey
项目:phptag
/**
* 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;
}
作者:i-am-ains-l
项目:sd
/**
* 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());
}
}
作者:thomasrui
项目:file-modifie
/**
* @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;
}
作者:Cecicecicec
项目:MySJSU-Class-Registratio
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);
}
作者:thomasrui
项目:file-modifie
/**
* 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();
}
作者:phpr
项目:grumph
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);
}
作者:hippoph
项目:hipp
/**
* @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;
});
}
作者:magento-ec
项目:magento-finde
/**
* @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);
}
作者:angrybende
项目:phpP
/**
* @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);
}
作者:christianblo
项目:codedoc
/**
* @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();
}
作者:rnuernber
项目:deprecation-detecto
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;
}
作者:maartensta
项目:phpt
/**
* 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];
}
作者:e1himsel
项目:php-x-component
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));
}
作者:hippoph
项目:hipp
/**
* 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);
}
}
作者:e1himsel
项目:php-x-component
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));
}
作者:niki
项目:php-parse
private function tryParse(Parser $parser, ErrorHandler $errorHandler, $code)
{
$stmts = null;
$error = null;
try {
$stmts = $parser->parse($code, $errorHandler);
} catch (Error $error) {
}
return [$stmts, $error];
}
作者:jacmo
项目:php-worksho
/**
* @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);
}