Inheritance: extends PhpParser\PrettyPrinterAbstract
Exemplo n.º 1
0
 /**
  * @param $code
  * @param bool $autoFix - In case of true - pretty code will be generated (avaiable by getPrettyCode method)
  * @return Logger
  */
 public function lint($code, $autoFix = false)
 {
     $this->autoFix = $autoFix;
     $this->prettyCode = '';
     $this->logger = new Logger();
     try {
         $stmts = $this->parser->parse($code);
     } catch (Error $e) {
         $this->logger->addRecord(new LogRecord('', '', Logger::LOGLEVEL_ERROR, $e->getMessage(), ''));
         return $this->logger;
     }
     $traverser = new NodeTraverser();
     $rulesVisitor = new RulesVisitor($this->rules, $this->autoFix);
     $traverser->addVisitor($rulesVisitor);
     $traverser->traverse($stmts);
     $messages = $rulesVisitor->getLog();
     foreach ($messages as $message) {
         $this->logger->addRecord(new LogRecord($message['line'], $message['column'], $message['level'], $message['message'], $message['name']));
     }
     if ($autoFix) {
         $prettyPrinter = new PrettyPrinter\Standard();
         $this->prettyCode = $prettyPrinter->prettyPrint($stmts);
     }
     $sideEffectVisitor = new SideEffectsVisitor();
     $traverser->addVisitor($sideEffectVisitor);
     $traverser->traverse($stmts);
     if ($sideEffectVisitor->isMixed()) {
         $this->logger->addRecord(new LogRecord('', '', Logger::LOGLEVEL_ERROR, 'A file SHOULD declare new symbols (classes, functions, constants, etc.) and cause no other side' . 'effects, or it SHOULD execute logic with side effects, but SHOULD NOT do both.', ''));
     }
     return $this->logger;
 }
Exemplo n.º 2
0
Arquivo: Jane.php Projeto: stof/jane
 public function generate($schemaFilePath, $name, $namespace, $directory)
 {
     $context = $this->createContext($schemaFilePath, $name, $namespace, $directory);
     if (!file_exists($directory . DIRECTORY_SEPARATOR . 'Model')) {
         mkdir($directory . DIRECTORY_SEPARATOR . 'Model', 0755, true);
     }
     if (!file_exists($directory . DIRECTORY_SEPARATOR . 'Normalizer')) {
         mkdir($directory . DIRECTORY_SEPARATOR . 'Normalizer', 0755, true);
     }
     $prettyPrinter = new Standard();
     $modelFiles = $this->modelGenerator->generate($context->getRootReference(), $name, $context);
     $normalizerFiles = $this->normalizerGenerator->generate($context->getRootReference(), $name, $context);
     $generated = [];
     foreach ($modelFiles as $file) {
         $generated[] = $file->getFilename();
         file_put_contents($file->getFilename(), $prettyPrinter->prettyPrintFile([$file->getNode()]));
     }
     foreach ($normalizerFiles as $file) {
         $generated[] = $file->getFilename();
         file_put_contents($file->getFilename(), $prettyPrinter->prettyPrintFile([$file->getNode()]));
     }
     if ($this->fixer !== null) {
         $config = Config::create()->setRiskyAllowed(true)->setRules(array('@Symfony' => true, 'empty_return' => false, 'concat_without_spaces' => false, 'double_arrow_multiline_whitespaces' => false, 'unalign_equals' => false, 'unalign_double_arrow' => false, 'align_double_arrow' => true, 'align_equals' => true, 'concat_with_spaces' => true, 'newline_after_open_tag' => true, 'ordered_use' => true, 'phpdoc_order' => true, 'short_array_syntax' => true))->finder(DefaultFinder::create()->in($directory));
         $resolver = new ConfigurationResolver();
         $resolver->setDefaultConfig($config);
         $resolver->resolve();
         $this->fixer->fix($config);
     }
     return $generated;
 }
Exemplo n.º 3
0
 public function transpile($srcPath, $dstPath)
 {
     // transpile based on target version
     $code = file_get_contents($srcPath);
     // Parse into statements
     $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
     $stmts = $parser->parse($code);
     if (!$stmts) {
         throw new ParseException(sprintf("Unable to parse PHP file '%s'\n", $srcPath));
     }
     // Custom traversal does the actual transpiling
     $traverser = self::getTraverser();
     $stmts = $traverser->traverse($stmts);
     $prettyPrinter = new Standard();
     if ($dstPath == '-') {
         // Output directly to stdout
         $this->getIo()->output($this->getStub() . $prettyPrinter->prettyPrint($stmts));
     } else {
         $dir = dirname($dstPath);
         if (!is_dir($dir) || !is_writeable($dir)) {
             @mkdir($dir, 0777, true);
             if (!is_dir($dir) || !is_writeable($dir)) {
                 throw new InvalidOptionException(sprintf('Destination directory "%s" does not exist or is not writable or could not be created.', $dir));
             }
         }
         file_put_contents($dstPath, $this->getStub() . $prettyPrinter->prettyPrint($stmts));
     }
 }
Exemplo n.º 4
0
 /**
  * @return string
  * @throws Exception\DomainException
  */
 public function compile()
 {
     $class = $this->compileClass();
     $node = $this->builderFactory->namespace($this->namespace)->addStmt($this->builderFactory->use('zdi\\Container'))->addStmt($this->builderFactory->use('zdi\\Container\\CompiledContainer'))->addStmt($class)->getNode();
     $prettyPrinter = new PrettyPrinter\Standard();
     return $prettyPrinter->prettyPrintFile(array($node));
 }
 /**
  * @param  EntityMapping $modelMapping
  * @param  string        $namespace
  * @param  string        $path
  * @param  bool          $override
  * @return void
  */
 public function generate(EntityMapping $modelMapping, $namespace, $path, $override = false)
 {
     $abstractNamespace = $namespace . '\\Base';
     if (!is_dir($path)) {
         mkdir($path, 0777, true);
     }
     $abstractPath = $path . DIRECTORY_SEPARATOR . 'Base';
     if (!is_dir($abstractPath)) {
         mkdir($abstractPath, 0777, true);
     }
     $abstracClassName = 'Abstract' . $modelMapping->getName();
     $classPath = $path . DIRECTORY_SEPARATOR . $modelMapping->getName() . '.php';
     $abstractClassPath = $abstractPath . DIRECTORY_SEPARATOR . $abstracClassName . '.php';
     $nodes = array();
     $nodes = array_merge($nodes, $this->generatePropertyNodes($modelMapping));
     $nodes = array_merge($nodes, $this->generateConstructNodes($modelMapping));
     $nodes = array_merge($nodes, $this->generateMethodNodes($modelMapping));
     $nodes = array_merge($nodes, $this->generateMetadataNodes($modelMapping));
     $nodes = array(new Node\Stmt\Namespace_(new Name($abstractNamespace), array(new Class_('Abstract' . $modelMapping->getName(), array('type' => 16, 'stmts' => $nodes)))));
     $abstractClassCode = $this->phpGenerator->prettyPrint($nodes);
     file_put_contents($abstractClassPath, '<?php' . PHP_EOL . PHP_EOL . $abstractClassCode);
     if (file_exists($classPath) && !$override) {
         return;
     }
     $nodes = array(new Node\Stmt\Namespace_(new Name($namespace), array(new Class_($modelMapping->getName(), array('extends' => new FullyQualified($abstractNamespace . '\\' . $abstracClassName))))));
     $classCode = $this->phpGenerator->prettyPrint($nodes);
     file_put_contents($classPath, '<?php' . PHP_EOL . PHP_EOL . $classCode);
 }
Exemplo n.º 6
0
 public function testPrettyPrintExpr()
 {
     $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(array('stmts' => array(new Stmt\Return_(new String_("a\nb")))));
     $this->assertEquals("function () {\n    return 'a\nb';\n}", $prettyPrinter->prettyPrintExpr($expr));
 }
 /**
  * @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));
 }
Exemplo n.º 8
0
 /**
  * @param Mapping $mapping
  * @param string  $path
  *
  * @return string
  */
 public function generate(Mapping $mapping, $path)
 {
     $nodes = array_merge($this->generatePropertyNodes(), $this->generateMethodNodes($mapping));
     $lazyNamespaceParts = explode('\\', $mapping->getLazyClass());
     $lazyClass = array_pop($lazyNamespaceParts);
     $classNode = new Namespace_(new Name(implode('\\', $lazyNamespaceParts)), array(new Class_($lazyClass, array('extends' => new Name('\\' . $mapping->getOriginalClass()), 'stmts' => $nodes))));
     $phpCode = '<?php' . "\n\n" . $this->phpGenerator->prettyPrint(array($classNode));
     file_put_contents($path . DIRECTORY_SEPARATOR . $lazyClass . '.php', $phpCode);
 }
Exemplo n.º 9
0
 /**
  * @inheritDoc
  */
 public function printContext(ContextInterface $context)
 {
     $this->output->writeln('');
     $this->output->writeln(sprintf('File: %s', $context->getCheckedResourceName()));
     foreach ($context->getMessages() as $message) {
         $nodes = $this->nodeStatementsRemover->removeInnerStatements($message->getNodes());
         $this->output->writeln(sprintf('Line %d. %s: %s', $message->getLine(), $message->getText(), $this->prettyPrinter->prettyPrint($nodes)));
     }
     $this->output->writeln('');
 }
Exemplo n.º 10
0
 /**
  * @dataProvider resourceProvider
  */
 public function testRessources($expected, $swaggerSpec, $name)
 {
     $swagger = JaneSwagger::build();
     $printer = new Standard();
     $files = $swagger->generate($swaggerSpec, 'Joli\\Jane\\Swagger\\Tests\\Expected', 'dummy');
     // Resource + NormalizerFactory
     $this->assertCount(2, $files);
     $resource = $files[1];
     $this->assertEquals($resource->getFilename(), 'dummy/Resource/TestResource.php');
     $this->assertEquals(trim($expected), trim($printer->prettyPrintFile([$resource->getNode()])));
 }
Exemplo n.º 11
0
 /**
  * Compile the view with devise code in it
  *
  * @param  string $view
  * @return string
  */
 public function compile($view)
 {
     ini_set('xdebug.max_nesting_level', env('XDEBUG_MAX_NESTING_LEVEL', 3000));
     $this->parser = new DeviseParser();
     $prettyPrinter = new Standard();
     $pristine = $this->pristine($view);
     $modified = $this->modified($view);
     $pristine[0]->stmts = $modified;
     $result = $prettyPrinter->prettyPrintFile($pristine);
     return $result;
 }
Exemplo n.º 12
0
 /**
  * @param Message $message
  *
  * @return string
  */
 private function formatMessage(Message $message)
 {
     $nodes = $this->nodeStatementsRemover->removeInnerStatements($message->getNodes());
     $prettyPrintedNodes = str_replace("\n", "\n    ", $this->prettyPrinter->prettyPrint($nodes));
     $text = $message->getRawText();
     $color = self::$colors[$message->getLevel()];
     if ($color) {
         $text = sprintf('<fg=%s>%s</fg=%s>', $color, $text, $color);
     }
     return sprintf("> Line <fg=cyan>%s</fg=cyan>: %s\n    %s", $message->getLine(), $text, $prettyPrintedNodes);
 }
Exemplo n.º 13
0
 private function createClass($commande, $description)
 {
     $output = $this->_output;
     $root = ROOT . DS;
     $app = $root . 'app' . DS . "Application";
     $lib = $root . 'library' . DS . "commands.php";
     // create command name
     $name = S::create($commande)->replace(':', ' ')->toTitleCase()->replace(' ', '')->append("Command")->__toString();
     // create FQN
     $fqn = "Application\\Commands\\" . $name;
     // check avaibality
     // load commands.php file
     $code = file_get_contents($lib);
     $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP5);
     $prettyPrinter = new PrettyPrinter\Standard();
     $stmts = $parser->parse($code);
     foreach ($stmts[0]->expr as $express) {
         $tmp = $express[0]->value->value;
         if (S::create($tmp)->humanize()->__toString() == S::create($fqn)->humanize()->__toString()) {
             $output->writeln("This command already exists in commands.php");
             die;
         }
     }
     // commands not exists add it to commands.php
     $nb = count($stmts[0]->expr->items);
     $ligne = 4 + $nb;
     $attributes = array("startLine" => $ligne, "endLine" => $ligne, "kind" => 2);
     $obj = new \PhpParser\Node\Expr\ArrayItem(new \PhpParser\Node\Scalar\String_($fqn, $attributes), null, false, $attributes);
     array_push($stmts[0]->expr->items, $obj);
     $code = $prettyPrinter->prettyPrint($stmts);
     $code = "<?php \r\n" . $code;
     $output->writeln("Create FQN commande " . $fqn);
     $path = $app . DS . "Commands" . DS . $name . ".php";
     $arg1 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($commande));
     $arg2 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($description));
     $arg3 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('Start process'));
     $arg4 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('Finished'));
     $factory = new BuilderFactory();
     $node = $factory->namespace('Application\\Commands')->addStmt($factory->use('Symfony\\Component\\Console\\Command\\Command'))->addStmt($factory->use('Symfony\\Component\\Console\\Input\\InputArgument'))->addStmt($factory->use('Symfony\\Component\\Console\\Input\\InputInterface'))->addStmt($factory->use('Symfony\\Component\\Console\\Input\\InputOption'))->addStmt($factory->use('Symfony\\Component\\Console\\Output\\OutputInterface'))->addStmt($factory->class($name)->extend('Command')->addStmt($factory->method('configure')->makeProtected()->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('this'), "setName", array($arg1)))->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('this'), "setDescription", array($arg2))))->addStmt($factory->method('execute')->makeProtected()->addParam($factory->param('input')->setTypeHint('InputInterface'))->addParam($factory->param('output')->setTypeHint('OutputInterface'))->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('output'), "writeln", array($arg3)))->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('output'), "writeln", array($arg4)))))->getNode();
     $stmts = array($node);
     $prettyPrinter = new PrettyPrinter\Standard();
     $php = $prettyPrinter->prettyPrintFile($stmts);
     file_put_contents($path, $php);
     $fs = new Filesystem();
     // if file exists add command to commands.php
     if ($fs->exists($path)) {
         $output->writeln("File saved in " . $path);
         $output->writeln("Register command to console");
         file_put_contents($lib, $code);
     } else {
         $output->writeln("File not created");
     }
 }
Exemplo n.º 14
0
 function pp($nodes)
 {
     static $prettyPrinter;
     if (!$prettyPrinter) {
         $prettyPrinter = new PrettyPrinter\Standard();
     }
     if (!is_array($nodes)) {
         $nodes = func_get_args();
     }
     echo $prettyPrinter->prettyPrint($nodes) . "\n";
     die(1);
 }
Exemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function printContext(ContextInterface $context)
 {
     $this->output->writeln('');
     $this->output->writeln(sprintf('File: <fg=cyan>%s</fg=cyan>', $context->getCheckedResourceName()));
     foreach ($context->getMessages() as $message) {
         $nodes = $this->nodeStatementsRemover->removeInnerStatements($message->getNodes());
         $this->output->writeln(sprintf("> Line <fg=cyan>%s</fg=cyan>: <fg=yellow>%s</fg=yellow>\n    %s", $message->getLine(), $message->getRawText(), str_replace("\n", "\n    ", $this->prettyPrinter->prettyPrint($nodes))));
     }
     foreach ($context->getErrors() as $error) {
         $this->output->writeln(sprintf('> <fg=red>%s</fg=red>', $error->getText()));
     }
     $this->output->writeln('');
 }
Exemplo n.º 16
0
 /**
  * @param array $items
  * @return string
  */
 private function generateFileContentForArray(array $items)
 {
     $nodes = [];
     foreach ($items as $key => $value) {
         $key = is_int($key) ? new LNumber($key) : new String_($key);
         $value = new String_($value);
         $node = new ArrayItem($value, $key);
         array_push($nodes, $node);
     }
     $statements = [new Return_(new Array_($nodes))];
     $printer = new Standard();
     return $printer->prettyPrintFile($statements);
 }
Exemplo n.º 17
0
 /**
  * @param string $path
  */
 public function generateFromNeonFile($path)
 {
     $definition = Neon::decode(file_get_contents($path));
     assert(isset($definition['class']));
     assert(isset($definition['type']));
     assert($definition['type'] === 'in-place');
     $data = $definition['data'];
     $output = $this->configuration->getDir() . DIRECTORY_SEPARATOR . $this->configuration->getOutputFolder() . DIRECTORY_SEPARATOR . $definition['class'] . '.php';
     $consts = Helper::createStringConstants($data);
     $node = $this->createClassFromData($definition['class'], $this->configuration->getNamespace(), $consts);
     $prettyPrinter = new PrettyPrinter\Standard();
     file_put_contents($output, $prettyPrinter->prettyPrintFile([$node]));
 }
Exemplo n.º 18
0
 /**
  * @param ControllerSpec $spec
  */
 public function generate(ControllerSpec $spec)
 {
     $printer = new PrettyPrinter();
     $ast = $this->doGenerate($spec);
     $ast = $this->processorDispatcher->process($ast);
     $event = new ControllerGenerated($spec, $ast);
     $this->eventDispatcher->dispatch(ControllerGenerated::EVENT_NAME, $event);
     $code = $printer->prettyPrint($ast);
     $controllerFile = $spec->getBundle()->getPath() . '/Controller/' . $spec->getName() . 'Controller.php';
     file_put_contents($controllerFile, "<?php\n" . $code);
     $event = new ControllerSaved($spec, $controllerFile);
     $this->eventDispatcher->dispatch(ControllerSaved::EVENT_NAME, $event);
 }
Exemplo n.º 19
0
 public function saveCode($stmts)
 {
     $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
     $prettyPrinter = new PrettyPrinter\Standard();
     try {
         $code = $prettyPrinter->prettyPrintFile($stmts);
     } catch (Error $e) {
         echo 'Parse Error: ', $e->getMessage();
     }
     if (!file_exists('src\\' . $this->restDir)) {
         mkdir('src\\' . $this->restDir, '755', true);
     }
     file_put_contents($this->restPath, $code);
 }
 /**
  * @param AnnotationManager $annotationManager
  * @param ServiceManager    $serviceManager
  * @param RouteManager      $routeManager
  * @param Standard          $prettyPrinter
  */
 public function updateCache(AnnotationManager $annotationManager, ServiceManager $serviceManager, RouteManager $routeManager, Standard $prettyPrinter)
 {
     $classInfos = $annotationManager->buildClassInfosBasedOnPaths($this->paths);
     $code = "<?php\n\n";
     foreach ($classInfos as $classInfo) {
         $code .= $prettyPrinter->prettyPrint($serviceManager->generateCode($classInfo));
         $code .= "\n\n";
     }
     foreach ($classInfos as $classInfo) {
         $code .= $prettyPrinter->prettyPrint($routeManager->generateCode($classInfo));
         $code .= "\n\n";
     }
     file_put_contents($this->cacheFile, $code);
 }
Exemplo n.º 21
0
 /**
  * @param $content
  * @param $prefix
  *
  * @return string
  */
 public function addNamespacePrefix($content, $prefix)
 {
     $traverser = new NodeTraverser();
     $traverser->addVisitor(new NamespaceScoperNodeVisitor($prefix));
     $traverser->addVisitor(new UseNamespaceScoperNodeVisitor($prefix));
     $traverser->addVisitor(new FullyQualifiedNamespaceUseScoperNodeVisitor($prefix));
     try {
         $statements = $this->parser->parse($content);
     } catch (Error $error) {
         throw new ParsingException($error->getMessage());
     }
     $statements = $traverser->traverse($statements);
     $prettyPrinter = new Standard();
     return $prettyPrinter->prettyPrintFile($statements) . "\n";
 }
Exemplo n.º 22
0
 /**
  * Obfuscate a single file's contents
  *
  * @param  string $source
  * @return string obfuscated contents
  **/
 public function obfuscateFileContents($source, $file = false)
 {
     $traverser = new PhpParser\NodeTraverser();
     if (input::get('ReplaceVariables')) {
         /**
          * all $vars
          */
         $traverser->addVisitor(new \Controllers\Obfuscator\ScrambleVariable($this));
         $traverser->addVisitor(new \Controllers\Obfuscator\ScrambleString($this));
     }
     if (input::get('ReplaceFunctions')) {
         /**
          * all OOP functions
          */
         $traverser->addVisitor(new \Controllers\Obfuscator\ScrambleFunction($this));
         /**
          * all NONE OOP functions (NATIVE)
          */
         $traverser->addVisitor(new \Controllers\Obfuscator\ScrambleNativeFunction($this));
     }
     if (input::get('ReplaceVariables')) {
         /**
          * all OOP $this->vars
          */
         $traverser->addVisitor(new \Controllers\Obfuscator\ScrambleProperty($this));
     }
     //if( input::get('ReplaceSmart') ) {
     //$traverser->addVisitor(new \Controllers\Obfuscator\ScrambleSmart($this));
     //}
     $parser = new Parser(new Lexer());
     // traverse
     $stmts = $traverser->traverse($parser->parse($source));
     $prettyPrinter = new PrettyPrinter();
     $nodeDumper = new PhpParser\NodeDumper();
     Debugbar::debug($stmts);
     // pretty print
     $code = "<?php\n" . $prettyPrinter->prettyPrint($stmts);
     if (Input::has('test')) {
         @header("Content-Type:text/plain");
         print_r($this->getFuncPack());
         print_r($this->getVarPack());
         echo '<pre>';
         echo $nodeDumper->dump($stmts), "\n";
         echo htmlentities($code);
         echo '</pre>';
     }
     return $code;
 }
Exemplo n.º 23
0
 /**
  * @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);
 }
Exemplo n.º 24
0
 public function pScalar_String(Scalar\String $node)
 {
     if ($node->obfuscated) {
         return $this->pNoIndent(addcslashes($node->value, '\'\\'));
     }
     return parent::pScalar_String($node);
 }
Exemplo n.º 25
0
 /**
  * Get a pretty printed string of code from a file while applying visitors.
  *
  * @param string $file
  *
  * @throws \RuntimeException
  *
  * @return string
  */
 public function getCode($file, $comments = true)
 {
     if (!is_string($file) || empty($file)) {
         throw new RuntimeException('Invalid filename provided.');
     }
     if (!is_readable($file)) {
         throw new RuntimeException("Cannot open {$file} for reading.");
     }
     if ($comments) {
         $content = file_get_contents($file);
     } else {
         $content = php_strip_whitespace($file);
     }
     $parsed = $this->parser->parse($content);
     $stmts = $this->traverser->traverseFile($parsed, $file);
     $pretty = $this->printer->prettyPrint($stmts);
     if (substr($pretty, 30) === '<?php declare(strict_types=1);' || substr($pretty, 30) === "<?php\ndeclare(strict_types=1);") {
         $pretty = substr($pretty, 32);
     } elseif (substr($pretty, 31) === "<?php\r\ndeclare(strict_types=1);") {
         $pretty = substr($pretty, 33);
     } elseif (substr($pretty, 5) === '<?php') {
         $pretty = substr($pretty, 7);
     }
     return $this->getCodeWrappedIntoNamespace($parsed, $pretty);
 }
Exemplo n.º 26
0
 /**
  * Function to put routes in PHP Classes
  * @return type
  */
 private function createClass()
 {
     $fs = new Filesystem();
     $directory = $this->getPathPHP();
     $path = $this->getPathClass();
     if (!$fs->exists($directory)) {
         $fs->mkdir($directory);
     }
     $routes = $this->routes;
     $factory = new BuilderFactory();
     $node = $factory->namespace('Route')->addStmt($factory->class('RouteArray')->addStmt($factory->property('_routes')->makePrivate()->setDefault($routes))->addStmt($factory->method('getRoutes')->makePublic()->addStmt(new Node\Stmt\Return_(new Node\Expr\Variable('this->_routes')))))->getNode();
     $stmts = array($node);
     $prettyPrinter = new PrettyPrinter\Standard();
     $php = $prettyPrinter->prettyPrintFile($stmts);
     file_put_contents($path, $php);
 }
Exemplo n.º 27
0
 protected function assertResponse($file)
 {
     $parsed = $this->parser->parse('<?php' . PHP_EOL . (string) $this->body);
     $printed = $this->printer->prettyPrintFile($parsed) . PHP_EOL;
     $filename = sprintf('%s/resources/generation/%s.php', TEST_DIR, $file);
     if (!file_exists($filename)) {
         touch($filename);
     }
     $expected = file_get_contents($filename);
     try {
         $this->assertSame($expected, $printed);
     } catch (\Exception $e) {
         file_put_contents($filename, $printed);
         throw $e;
     }
 }
Exemplo n.º 28
0
 public function testCommentBeforeInlineHTML()
 {
     $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));
 }
Exemplo n.º 29
0
 public function pScalar_String(Scalar\String_ $node)
 {
     if (strpos($node->value, "\n") !== false) {
         if ($node->value === "\n") {
             return "'\\n'";
         }
         return '`' . $this->pNoIndent(addcslashes($node->value, '`\\')) . '`';
     }
     return parent::pScalar_String($node);
 }
Exemplo n.º 30
0
 /**
  * Ищвлекает тело метода из текущего узла
  *
  * @param Node|ClassMethod $stmt    Узел
  * @param Method[]         $methods Список методов
  *
  * @return void
  */
 private function extractMethod($stmt, array &$methods)
 {
     if (!$stmt instanceof ClassMethod) {
         return;
     }
     $skip = $this->isPublicOnly && $stmt->isPublic() === false;
     if (!$skip) {
         $methods[] = new Method(new MethodContext($this->context->namespace, $this->context->class), $stmt->name, $this->printer->prettyPrint([$stmt]));
     }
 }