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;
 }
Beispiel #2
0
 public function __construct()
 {
     $this->printer = new NodePrinter();
     $this->lexer = new Lexer();
     $factory = new ParserFactory();
     $this->parser = $factory->create(ParserFactory::PREFER_PHP7, $this->lexer);
 }
Beispiel #3
0
 /**
  * parses all given files for classes and interfaces that are defined or used in this
  * files.
  *
  * @param array $files
  */
 public function parseFilesForClassesAndInterfaces($files)
 {
     $parserFactory = new ParserFactory();
     $parser = $parserFactory->create(ParserFactory::PREFER_PHP7);
     $progressbar = new Progressbar($this->output, count($files));
     foreach ($files as $file) {
         $namespace = (string) new NamespaceString($this->namespaceVendor, $this->root, $file);
         $originalFileContent = $this->filesystem->getFile($file);
         try {
             $stmts = $parser->parse($originalFileContent);
             $firstStatement = $stmts[0];
             if ($firstStatement instanceof Namespace_) {
                 $namespaceOfFile = implode('\\', $firstStatement->name->parts);
                 if ($namespace !== $namespaceOfFile) {
                     $this->foundError = true;
                     $this->output->addError('Namespace does not match folder structure, got ' . $namespaceOfFile . ' expected ' . $namespace, $file, $firstStatement->getLine());
                 }
             }
         } catch (Error $e) {
             $this->foundError = true;
             $this->output->addError('Parse Error: ' . $e->getMessage(), $file, 1);
         }
         $fileContent = $this->cleanContent($originalFileContent);
         $this->parseDefinedEntities($file, $namespace, $fileContent, $originalFileContent);
         $this->parseUsedEntities($file, $namespace, $fileContent, $originalFileContent);
         $this->parseUseStatements($file, $namespace, $fileContent, $originalFileContent);
         $progressbar->step();
     }
 }
Beispiel #4
0
 /**
  * @return SyntaxHighlighter
  */
 public function __invoke()
 {
     $lexer = new Lexer(['usedAttributes' => ['comments', 'startLine', 'endLine', 'startFilePos', 'endFilePos', 'startTokenPos', 'endTokenPos']]);
     $parserFactory = new ParserFactory();
     $color = new Color();
     $color->setForceStyle(true);
     return new SyntaxHighlighter($parserFactory->create(ParserFactory::PREFER_PHP7, $lexer), new SyntaxHighlightPrinter(new SyntaxHighlighterConfig(), new ColorsAdapter($color)));
 }
Beispiel #5
0
 /**
  * @param RuleCollection $rules
  * @param bool           $fix
  * @param book           $debug
  */
 public function __construct($rules, $fix = false, $debug = false)
 {
     $parserFactory = new ParserFactory();
     $this->parser = $parserFactory->create(ParserFactory::PREFER_PHP7);
     $this->traverser = new NodeTraverser();
     $this->linterVisitor = new LinterVisitor($rules, $fix, $debug);
     $this->traverser->addVisitor($this->linterVisitor);
 }
Beispiel #6
0
 /**
  * Optionally inject parser
  *
  * @param string $snippet
  * @param Parser $parser
  */
 public function __construct($snippet, Parser $parser = null)
 {
     if (is_null($parser)) {
         $parserFactory = new ParserFactory();
         $parser = $parserFactory->create(ParserFactory::PREFER_PHP5);
     }
     $this->global = $parser->parse($snippet);
     $this->findDefinitions($this->global, new Name(''));
 }
 public function setUp()
 {
     $parserFactory = new ParserFactory();
     $this->parser = $parserFactory->create(ParserFactory::PREFER_PHP7);
     $this->check = new FunctionRequirementsCheck($this->parser);
     $this->exercise = new FunctionRequirementsExercise();
     $this->assertEquals('Function Requirements Check', $this->check->getName());
     $this->assertEquals(FunctionRequirementsExerciseCheck::class, $this->check->getExerciseInterface());
     $this->assertTrue($this->check->canRun(ExerciseType::CGI()));
     $this->assertTrue($this->check->canRun(ExerciseType::CLI()));
 }
Beispiel #8
0
 /**
  * Optionally inject parser
  *
  * @param  string $snippet
  * @param  Parser $parser
  * @throws ReaderException If snippet contains a syntax error
  */
 public function __construct($snippet, Parser $parser = null)
 {
     if (is_null($parser)) {
         $parserFactory = new ParserFactory();
         $parser = $parserFactory->create(ParserFactory::PREFER_PHP5);
     }
     try {
         $this->global = $parser->parse($snippet);
     } catch (\PhpParser\Error $exception) {
         throw new ReaderException($exception->getRawMessage() . ' on line ' . $exception->getStartLine());
     }
     $this->findDefinitions($this->global, new Name(''));
 }
 /**
  * Parse a PHP file.
  *
  * @param string $path File path
  *
  * @return \PhpParser\Node[]
  *
  * @throws \Exception
  */
 public function parseFile($path)
 {
     $factory = new ParserFactory();
     $parser = $factory->create(ParserFactory::PREFER_PHP7);
     try {
         $statements = $parser->parse($this->loadFile($path));
     } catch (Error $e) {
         throw new \RuntimeException(sprintf('Failed to parse %s file due to parse error: %s', $path, $e->getMessage()), 0, $e);
     }
     if ($statements === null) {
         throw new \RuntimeException(sprintf('Failed to parse %s', $path));
     }
     return $statements;
 }
Beispiel #10
0
 /**
  * Parses specified PHP file.
  *
  * @param   string $filename
  */
 public function __construct($filename)
 {
     $contents = php_strip_whitespace($filename);
     $pos = strpos($contents, '<?php');
     if ($pos !== false) {
         $contents = substr($contents, $pos);
         $factory = new PhpParser\ParserFactory();
         $parser = $factory->create(PhpParser\ParserFactory::PREFER_PHP7);
         $serializer = new PhpParser\Serializer\XML();
         $nodes = $parser->parse($contents);
         $xml = $serializer->serialize($nodes);
         $this->functions = $this->findFunctions($xml);
         $this->constants = $this->findConstants($xml);
         $this->classes = $this->findClasses($xml);
         $this->classConstants = $this->findClassConstants($xml);
     }
 }
 /**
  * New parser instance with given kind.
  *
  * @param string|null $kind One of class constants (only for PHP parser 2.0 and above).
  *
  * @return Parser
  */
 public function createParser($kind = null)
 {
     if ($this->hasKindsSupport()) {
         $originalFactory = new OriginalParserFactory();
         $kind = $kind ?: $this->getDefaultKind();
         if (!in_array($kind, static::getPossibleKinds())) {
             throw new \InvalidArgumentException('Unknown parser kind');
         }
         $parser = $originalFactory->create(constant('PhpParser\\ParserFactory::' . $kind));
     } else {
         if ($kind !== null) {
             throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind');
         }
         $parser = new Parser(new Lexer());
     }
     return $parser;
 }
 public static function build()
 {
     if (class_exists('PhpParser\\ParserFactory')) {
         $parserFactory = new ParserFactory();
         $parser = $parserFactory->create(ParserFactory::PREFER_PHP5);
     } else {
         $parser = new Parser(new Lexer());
     }
     $resolver = new Resolver(Jane::buildSerializer());
     $bodyParameter = new BodyParameterGenerator($parser, $resolver);
     $pathParameter = new PathParameterGenerator($parser);
     $formDataParameter = new FormDataParameterGenerator($parser);
     $headerParameter = new HeaderParameterGenerator($parser);
     $queryParameter = new QueryParameterGenerator($parser);
     $operation = new OperationGenerator($resolver, $bodyParameter, $formDataParameter, $headerParameter, $pathParameter, $queryParameter);
     $operationManager = new OperationManager();
     $operationNaming = new ChainOperationNaming([new OperationIdNaming(), new OperationUrlNaming()]);
     $client = new ClientGenerator($operationManager, $operation, $operationNaming);
     return $client;
 }
 public function __construct(\Twig_Environment $twig, LoggerInterface $logger, array $visitors)
 {
     $this->twig = $twig;
     $this->logger = $logger;
     $this->visitors = $visitors;
     $lexer = new Lexer();
     if (class_exists('PhpParser\\ParserFactory')) {
         $factory = new ParserFactory();
         $this->phpParser = $factory->create(ParserFactory::PREFER_PHP7, $lexer);
     } else {
         $this->phpParser = new \PHPParser_Parser($lexer);
     }
     foreach ($this->twig->getNodeVisitors() as $visitor) {
         if ($visitor instanceof RemovingNodeVisitor) {
             $this->removingTwigVisitor = $visitor;
         }
         if ($visitor instanceof DefaultApplyingNodeVisitor) {
             $this->defaultApplyingTwigVisitor = $visitor;
         }
     }
 }
    public function testPrintWithBrackets()
    {
        $parserFactory = new ParserFactory();
        $parser = $parserFactory->create(ParserFactory::PREFER_PHP5);
        $printer = new BracketingPrinter();
        $stmts = $parser->parse(<<<EOF
<?php namespace foo;
class Bar
{
}
EOF
);
        $expected = <<<EOF
namespace foo {
    class Bar
    {
    }
}
EOF;
        $this->assertEquals($expected, $printer->prettyPrint($stmts));
    }
 private function extract($file, TranslationContainerExtractor $extractor = null)
 {
     if (!is_file($file = __DIR__ . '/Fixture/' . $file)) {
         throw new RuntimeException(sprintf('The file "%s" does not exist.', $file));
     }
     $file = new \SplFileInfo($file);
     if (null === $extractor) {
         $extractor = new TranslationContainerExtractor();
     }
     $lexer = new Lexer();
     if (class_exists('PhpParser\\ParserFactory')) {
         $factory = new ParserFactory();
         $parser = $factory->create(ParserFactory::PREFER_PHP7, $lexer);
     } else {
         $parser = new \PHPParser_Parser($lexer);
     }
     $ast = $parser->parse(file_get_contents($file));
     $catalogue = new MessageCatalogue();
     $extractor->visitPhpFile($file, $catalogue, $ast);
     return $catalogue;
 }
 /**
  * Parses a migration definition file, and returns the list of actions to take
  *
  * @param MigrationDefinition $definition
  * @return MigrationDefinition
  */
 public function parseMigrationDefinition(MigrationDefinition $definition)
 {
     $status = MigrationDefinition::STATUS_PARSED;
     /// validate that php file is ok, contains a class with good interface
     $className = $this->getClassNameFromFile($definition->path);
     if ($className == '') {
         $status = MigrationDefinition::STATUS_INVALID;
         $message = 'The migration definition file should contain a valid class name. The class name is the part of the filename after the 1st underscore';
     } else {
         // we use smart parsing instead before plain file inclusion, by usage of nikic/php-parser
         // this should help with broken php migrations
         $pf = new ParserFactory();
         $parser = $pf->create(ParserFactory::PREFER_PHP7);
         try {
             $parser->parse(file_get_contents($definition->path));
             include_once $definition->path;
             if (!class_exists($className)) {
                 $status = MigrationDefinition::STATUS_INVALID;
                 $message = "The migration definition file should contain a valid class '{$className}'";
             } else {
                 $interfaces = class_implements($className);
                 if (!in_array($this->mandatoryInterface, $interfaces)) {
                     $status = MigrationDefinition::STATUS_INVALID;
                     $message = "The migration definition class '{$className}' should implement the interface '{$this->mandatoryInterface}'";
                 }
             }
         } catch (Error $e) {
             $status = MigrationDefinition::STATUS_INVALID;
             $message = "The migration definition file '{$definition->path}' is not valid php'";
         }
     }
     if ($status != MigrationDefinition::STATUS_PARSED) {
         return new MigrationDefinition($definition->name, $definition->path, $definition->rawDefinition, $status, array(), $message);
     }
     return new MigrationDefinition($definition->name, $definition->path, $definition->rawDefinition, MigrationDefinition::STATUS_PARSED, array(new MigrationStep('php', array('class' => $className), array('path' => $definition->path))));
 }
<?php

// example call
// view-source:http://test.dev.vk-web.de/php-parser/parse-example.php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set('xdebug.max_nesting_level', 3000);
define('DS', DIRECTORY_SEPARATOR);
require __DIR__ . DS . 'vendor' . DS . 'autoload.php';
// require implode(DS, array(__DIR__, 'vendor', 'nikic', 'php-parser', 'lib', 'bootstrap.php') );
// example https://github.com/vitali-korezki/PHP-Parser/blob/master/doc/2_Usage_of_basic_components.markdown
require_once implode(DS, array(__DIR__, 'Visualizer.php'));
use PhpParser\Error;
use PhpParser\ParserFactory;
$code = file_get_contents(implode(DS, array(__DIR__, 'Draw.php')));
$factory = new ParserFactory();
$parser = $factory->create(ParserFactory::ONLY_PHP5);
$serializer = new PhpParser\Serializer\XML();
$prettyPrinter = new PhpParser\PrettyPrinter\Standard();
$visualizer = new Visualizer();
try {
    $stmts = $parser->parse($code);
    // print_r($stmts);
    // echo $serializer->serialize($stmts);
    echo $visualizer->serialize($stmts);
    // echo '<pre>'.json_encode($stmts, JSON_PRETTY_PRINT).'</pre>';
    // echo '<pre>'.print_r($stmts, true).'</pre>';
    // just export the file
    // echo $prettyPrinter->prettyPrintFile($stmts);
} catch (Error $e) {
    echo 'Parse Error: ', $e->getMessage();
Beispiel #18
0
 /** Validate passed callable for execution
  *
  * @param   callable|string $code      The callable or string of code to validate
  *
  * @return  $this      Returns the PHPSandbox instance for fluent querying
  */
 public function validate($code)
 {
     $this->preparsed_code = $this->disassemble($code);
     $factory = new ParserFactory();
     $parser = $factory->create(ParserFactory::PREFER_PHP5);
     try {
         $this->parsed_ast = $parser->parse($this->preparsed_code);
     } catch (ParserError $error) {
         $this->validationError("Could not parse sandboxed code!", Error::PARSER_ERROR, null, $this->preparsed_code, $error);
     }
     $prettyPrinter = new Standard();
     if ($this->allow_functions && $this->auto_whitelist_functions || $this->allow_constants && $this->auto_whitelist_constants || $this->allow_classes && $this->auto_whitelist_classes || $this->allow_interfaces && $this->auto_whitelist_interfaces || $this->allow_traits && $this->auto_whitelist_traits || $this->allow_globals && $this->auto_whitelist_globals) {
         $traverser = new NodeTraverser();
         $whitelister = new SandboxWhitelistVisitor($this);
         $traverser->addVisitor($whitelister);
         $traverser->traverse($this->parsed_ast);
     }
     $traverser = new NodeTraverser();
     $validator = new ValidatorVisitor($this);
     $traverser->addVisitor($validator);
     $this->prepared_ast = $traverser->traverse($this->parsed_ast);
     $this->prepared_code = $prettyPrinter->prettyPrint($this->prepared_ast);
     return $this;
 }
Beispiel #19
0
}, HelpCommand::class => function (ContainerInterface $c) {
    return new HelpCommand($c->get('appName'), $c->get(OutputInterface::class), $c->get(Color::class));
}, PrepareSolutionListener::class => object(), CodePatchListener::class => function (ContainerInterface $c) {
    return new CodePatchListener($c->get(CodePatcher::class));
}, SelfCheckListener::class => function (ContainerInterface $c) {
    return new SelfCheckListener($c->get(ResultAggregator::class));
}, CheckExerciseAssignedListener::class => function (ContainerInterface $c) {
    return new CheckExerciseAssignedListener($c->get(UserState::class));
}, ConfigureCommandListener::class => function (ContainerInterface $c) {
    return new ConfigureCommandListener($c->get(UserState::class), $c->get(ExerciseRepository::class), $c->get(RunnerManager::class));
}, RealPathListener::class => object(), FileExistsCheck::class => object(), PhpLintCheck::class => object(), CodeParseCheck::class => function (ContainerInterface $c) {
    return new CodeParseCheck($c->get(Parser::class));
}, FunctionRequirementsCheck::class => function (ContainerInterface $c) {
    return new FunctionRequirementsCheck($c->get(Parser::class));
}, DatabaseCheck::class => object(), ComposerCheck::class => object(), Filesystem::class => object(), Parser::class => function () {
    $parserFactory = new ParserFactory();
    return $parserFactory->create(ParserFactory::PREFER_PHP7);
}, CodePatcher::class => function (ContainerInterface $c) {
    $patch = (new Patch())->withInsertion(new Insertion(Insertion::TYPE_BEFORE, 'ini_set("display_errors", 1);'))->withInsertion(new Insertion(Insertion::TYPE_BEFORE, 'error_reporting(E_ALL);'))->withInsertion(new Insertion(Insertion::TYPE_BEFORE, 'date_default_timezone_set("Europe/London");'));
    return new CodePatcher($c->get(Parser::class), new Standard(), $patch);
}, FakerGenerator::class => function () {
    return FakerFactory::create();
}, RequestRenderer::class => object(), TerminalInterface::class => factory([TerminalFactory::class, 'fromSystem']), 'menu' => factory(MenuFactory::class), MenuFactory::class => object(), ExerciseRenderer::class => function (ContainerInterface $c) {
    return new ExerciseRenderer($c->get('appName'), $c->get(ExerciseRepository::class), $c->get(UserState::class), $c->get(UserStateSerializer::class), $c->get(MarkdownRenderer::class), $c->get(Color::class), $c->get(OutputInterface::class));
}, MarkdownRenderer::class => function (ContainerInterface $c) {
    $docParser = new DocParser(Environment::createCommonMarkEnvironment());
    $cliRenderer = (new MarkdownCliRendererFactory())->__invoke($c);
    return new MarkdownRenderer($docParser, $cliRenderer);
}, UserStateSerializer::class => function (ContainerInterface $c) {
    return new UserStateSerializer(getenv('HOME'), $c->get('workshopTitle'), $c->get(ExerciseRepository::class));
}, UserState::class => function (ContainerInterface $c) {
 /**
  * @return \PhpParser\Parser
  */
 protected function createParser()
 {
     $factory = new ParserFactory();
     return $factory->create(ParserFactory::PREFER_PHP7);
 }
Beispiel #21
0
foreach ([__DIR__ . '/../../../autoload.php', __DIR__ . '/../vendor/autoload.php'] as $file) {
    if (file_exists($file)) {
        require $file;
        break;
    }
}
ini_set('xdebug.max_nesting_level', 3000);
use Benoth\StaticReflection\Parser\ParsingContext;
use Benoth\StaticReflection\Parser\ReflectorNodeVisitor;
use Benoth\StaticReflection\Reflection\ReflectionClassLike;
use Benoth\StaticReflection\ReflectionsIndex;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\ParserFactory;
$fixturesPath = __DIR__ . '/../tests/Fixtures';
$phpParserFactory = new ParserFactory();
$phpParser = $phpParserFactory->create(ParserFactory::PREFER_PHP7);
$traverser = new NodeTraverser();
$index = new ReflectionsIndex();
$context = new ParsingContext($phpParser, $traverser, $index);
$traverser->addVisitor(new NameResolver());
$traverser->addVisitor(new ReflectorNodeVisitor($context));
$argc = $argc - 1;
array_shift($argv);
if ($argc <= 0) {
    exit('You need to provide one or more pathes');
}
foreach ($argv as $arg) {
    if (!file_exists($arg)) {
        exit('Not a file or directory: ' . $arg);
    } elseif (is_file($arg)) {