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; }
/** * @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 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); }
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; } }
/** * @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()]))); }
/** * 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; }
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"); } }
/** * @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])); }
/** * @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); }
/** @inheritdoc */ public function renameConflicts(array $conflicts) { $replacements = []; $this->traverser->addVisitor($this->reNamer); foreach ($conflicts as $package => $types) { foreach ($types as $type => $versions) { foreach ($versions as $version => $files) { $composer = $this->reader->setPackage($package)->setVersion($version)->getComposerObject(); if ($this->hasNs($type)) { $split = $this->splitNsandClass($type); $fromNs = $split['ns']; $psrNs = $this->getPsrNs($composer, $fromNs); $toNs = $psrNs . $this->sanitizeVersionNo($version); $diff = str_replace($psrNs, '', $fromNs); if ($psrNs != $diff . '\\') { $toNs = $toNs . '\\' . $diff; } $newFullyQualifiedType = $toNs . '\\' . $split['class']; } else { $fromNs = $type; $toNs = $type . '_' . $this->sanitizeVersionNo($version); $newFullyQualifiedType = $toNs; } $this->reNamer->rename($fromNs, $toNs); $replacements[] = ['package' => $package, 'version' => $version, 'originalFullyQualifiedType' => $type, 'originalNamespace' => $fromNs, 'newFullyQualifiedType' => $newFullyQualifiedType, 'newNamespace' => $toNs, 'replacedIn' => $files]; foreach ($files as $file) { $fullPath = $this->vendorDir . '/' . $package . '/' . $version . '/' . $file; $src = $this->filesystem->read($fullPath); $ast = $this->parser->parse($src); $newAst = $this->traverser->traverse($ast); $code = $this->prettyPrinter->prettyPrintFile($newAst); $this->filesystem->update($fullPath, $code); } } } } $this->traverser->removeVisitor($this->reNamer); return $replacements; }
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 $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"; }
/** * @param Patch $patch * @param string $code * @return string */ private function applyPatch(Patch $patch, $code) { $statements = $this->parser->parse($code); foreach ($patch->getModifiers() as $modifier) { if ($modifier instanceof CodeInsertion) { $statements = $this->applyCodeInsertion($modifier, $statements); continue; } if (is_callable($modifier)) { $statements = $modifier($statements); continue; } } return $this->printer->prettyPrintFile($statements); }
/** * 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); }
public function sample() { $factory = new BuilderFactory(); $node = $factory->namespace('name\\space')->addStmt($factory->class('Sample')->addStmt($factory->property('string')->makeProtected()->setDocComment('/** * @var string String */'))->addStmt($factory->method('get')->makePublic()->setDocComment('/** * Return string * * @return string String */')->addStmt(new Node\Stmt\Return_(new Node\Expr\Variable('this->string'))))->addStmt($factory->method('set')->makePublic()->setDocComment('/** * Set string * * @param string $string String * @return $this */')->addParam(new Node\Param('string'))->addStmt(new Node\Name('$this->string = $string;'))->addStmt(new Node\Stmt\Return_(new Node\Expr\Variable('this')))))->getNode(); $stmts = array($node); $prettyPrinter = new PrettyPrinter\Standard(); $code = $prettyPrinter->prettyPrintFile($stmts); file_put_contents('tmp/origin/PHPParser.php', (string) $code); }
public function testIntegration() { $factory = new BuilderFactory(); $node = $factory->namespace('Name\\Space')->addStmt($factory->use('Foo\\Bar\\SomeOtherClass'))->addStmt($factory->use('Foo\\Bar')->as('A'))->addStmt($factory->class('SomeClass')->extend('SomeOtherClass')->implement('A\\Few', '\\Interfaces')->makeAbstract()->addStmt($factory->method('firstMethod'))->addStmt($factory->method('someMethod')->makePublic()->makeAbstract()->addParam($factory->param('someParam')->setTypeHint('SomeClass'))->setDocComment('/** * This method does something. * * @param SomeClass And takes a parameter */'))->addStmt($factory->method('anotherMethod')->makeProtected()->addParam($factory->param('someParam')->setDefault('test'))->addStmt(new Expr\Print_(new Expr\Variable('someParam'))))->addStmt($factory->property('someProperty')->makeProtected())->addStmt($factory->property('anotherProperty')->makePrivate()->setDefault(array(1, 2, 3))))->getNode(); $expected = <<<'EOC' <?php namespace Name\Space; use Foo\Bar\SomeOtherClass; use Foo\Bar as A; abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces { protected $someProperty; private $anotherProperty = array(1, 2, 3); function firstMethod() { } /** * This method does something. * * @param SomeClass And takes a parameter */ public abstract function someMethod(SomeClass $someParam); protected function anotherMethod($someParam = 'test') { print $someParam; } } EOC; $stmts = array($node); $prettyPrinter = new PrettyPrinter\Standard(); $generated = $prettyPrinter->prettyPrintFile($stmts); $this->assertEquals(str_replace("\r\n", "\n", $expected), str_replace("\r\n", "\n", $generated)); }
public function format($stmts) { $prettyPrinter = new Standard(); return $prettyPrinter->prettyPrintFile($stmts); }
public function getCode() { $aResult = []; $oPrinter = new PhpParser\PrettyPrinter\Standard(); foreach ($this->aNodes as $aStmts) { $aResult[] = $oPrinter->prettyPrintFile($aStmts); } return $aResult; }
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)); }
/** * @param $output * @param $node */ private function saveGeneratedFile($output, $node) { $prettyPrinter = new PrettyPrinter\Standard(); @mkdir(dirname($output), 0777, true); file_put_contents($output, $prettyPrinter->prettyPrintFile([$node])); }
public function saveToFile() { $node = $this->generateNode(); $prettyPrinter = new PrettyPrinter\Standard(); file_put_contents(__DIR__ . '/Interfaces/' . $this->_interfaceApiDefinition->name . '.php', $prettyPrinter->prettyPrintFile(array($node)) . PHP_EOL); echo $this->_interfaceApiDefinition->name . PHP_EOL; }
public static function CreateTests($dir = null) { if (!is_dir($dir)) { throw new InvalidArgumentException('Output directory "' . $dir . '" does not exist!'); } $factory = new BuilderFactory(); $prettyPrinter = new StandardPrettyPrinter(); $lazySanitizer = function ($in) { return preg_replace('/[^a-z]/i', '', ucfirst($in)); }; $namespaceTests = 'VerbalExpressions\\PHPVerbalExpressions\\Tests'; $useVerbExp = 'VerbalExpressions\\PHPVerbalExpressions\\VerbalExpressions'; $variableOut = new Variable('out'); $variableRegex = new Variable('regex'); $variableThis = new Variable('this'); $nameVerbalExpressions = new Name('VerbalExpressions'); $constVerbExp = new ClassConstFetch(new Name('static'), 'VerbExpClassName'); $nameAssertInstanceOf = new Name('assertInstanceOf'); $nameAssertEquals = new Name('assertEquals'); $assignNewVerbExpToRegex = new Assign($variableRegex, new New_($nameVerbalExpressions)); $parseCallStackItem = function ($callStackItem, $method, $containsDesc) use($variableOut, $variableRegex, $variableThis, $nameAssertInstanceOf, $nameAssertEquals, $constVerbExp) { $method->setDocComment('/** * ' . $containsDesc->description . ' */'); if (count($callStackItem->arguments) > 0) { $methodCall = new MethodCall($variableRegex, new Name($callStackItem->method), array_map(array('static', 'CreateArg'), $callStackItem->arguments)); } else { $methodCall = new MethodCall($variableRegex, new Name($callStackItem->method)); } $method->addStmt(new Assign($variableOut, $methodCall)); if ($callStackItem->returnType === 'sameInstance') { $method->addStmt(new MethodCall($variableThis, $nameAssertInstanceOf, array($constVerbExp, $variableOut))); $method->addStmt(new Assign($variableRegex, $variableOut)); } else { $method->addStmt(new MethodCall($variableThis, $nameAssertEquals, array(new String_($callStackItem->returnType), new FuncCall(new Name('gettype'), array($variableOut))))); } }; foreach (static::GetTestFiles() as $testFile) { $data = json_decode(file_get_contents($testFile->getRealPath())); $className = $lazySanitizer(substr($testFile->getBasename(), 0, -4)) . 'DynamicallyGeneratedTest'; $class = $factory->class($className)->extend('PHPUnit_Framework_TestCase')->addStmt(new ClassConst(array(new Const_('VerbExpClassName', new String_($useVerbExp))))); if (isset($data->patterns)) { foreach ($data->patterns as $pattern) { $method = $factory->method('pattern' . $lazySanitizer($pattern->name))->makeProtected()->addStmt($assignNewVerbExpToRegex); foreach ($pattern->callStack as $callStackItem) { $parseCallStackItem($callStackItem, $method, $pattern); } $method->addStmt(new Return_($variableRegex)); $class->addStmt($method); } } $methods = array(); $methodIncrements = array(); foreach ($data->tests as $test) { $expectedOutputValue = $test->output->default; if (isset($test->output->php)) { $expectedOutputValue = $test->output->php; } $methodName = 'test' . $lazySanitizer($test->name); if (in_array($methodName, $methods)) { if (!isset($methodIncrements[$methodName])) { $methodIncrements[$methodName] = 1; } $methodName .= ++$methodIncrements[$methodName]; } $methods[] = $methodName; $method = $factory->method($methodName)->makePublic(); if (isset($test->pattern)) { $method->addStmt(new Assign($variableRegex, new StaticCall(new Name('static'), 'pattern' . $lazySanitizer($test->pattern)))); $method->addStmt(new MethodCall($variableThis, $nameAssertInstanceOf, array($constVerbExp, $variableRegex))); } else { $method->addStmt($assignNewVerbExpToRegex); } foreach ($test->callStack as $callStackItem) { $parseCallStackItem($callStackItem, $method, $test); } $method->addStmt(new MethodCall($variableThis, $nameAssertEquals, array(static::CreateArg($expectedOutputValue), $variableOut))); $class->addStmt($method); } file_put_contents($dir . '/' . $className . '.php', $prettyPrinter->prettyPrintFile(array($factory->namespace($namespaceTests)->addStmt($factory->use('PHPUnit_Framework_TestCase'))->addStmt($factory->use($useVerbExp))->addStmt($class)->getNode()))); } }
/** * Patches the oxid install so it works on the command line * * @param $target */ protected function patchOxSetup($target) { $parser = new \PhpParser\Parser(new PhpParser\Lexer\Emulative()); $traverser = new \PhpParser\NodeTraverser(); $prettyPrinter = new \PhpParser\PrettyPrinter\Standard(); file_put_contents($target . '/setup/oxrunsetup.php', ''); $traverser->addVisitor(new OxidSetupNodeVisitor($target . '/setup/')); try { $code = file_get_contents($target . '/setup/oxsetup.php'); $stmts = $parser->parse($code); $stmts = $traverser->traverse($stmts); $code = $prettyPrinter->prettyPrintFile($stmts); file_put_contents($target . '/setup/oxrunsetup.php', $code, FILE_APPEND); } catch (PhpParser\Error $e) { } }
/** * Generate code. * * @param $schemaFilePath * @param $name * @param $namespace * @param $directory * * @return array */ 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()])); } $this->fix($directory); return $generated; }
/** * Create a new class base on an existing class, and change some value * * @param string $sourceFile The path of the existing class * @param null|string $newNamespace The new namespace of the class (leave `null` to keep existing value) * @param null|string $newClassName The new class name of the class (leave `null` to keep existing value) * @param null|string $newExtends The new class to extends (leave `null` to keep existing value) * * @return string */ public function rebuildClass($sourceFile, $newNamespace = null, $newClassName = null, $newExtends = null) { $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); $traverser = new NodeTraverser(); $prettyPrinter = new Standard(); $traverser->addVisitor(new NameResolver()); $traverser->addVisitor(new Rewriter($newNamespace, $newClassName, $newExtends)); $stmts = $parser->parse(file_get_contents($sourceFile)); $stmts = $traverser->traverse($stmts); return $prettyPrinter->prettyPrintFile($stmts); }