本文整理汇总了PHP中PhpParser\PrettyPrinter\Standard::prettyPrint方法的典型用法代码示例。如果您正苦于以下问题:PHP Standard::prettyPrint方法的具体用法?PHP Standard::prettyPrint怎么用?PHP Standard::prettyPrint使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PhpParser\PrettyPrinter\Standard
的用法示例。
在下文中一共展示了Standard::prettyPrint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: transpile
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));
}
}
示例2: generate
/**
* @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);
}
示例3: __invoke
/**
* @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));
}
示例4: generate
/**
* @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);
}
示例5: printContext
/**
* @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('');
}
示例6: formatMessage
/**
* @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);
}
示例7: printContext
/**
* {@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('');
}
示例8: updateCache
/**
* @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);
}
示例9: getCode
/**
* 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);
}
示例10: lint
/**
* @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;
}
示例11: extractMethod
/**
* Ищвлекает тело метода из текущего узла
*
* @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]));
}
}
示例12: createClass
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");
}
}
示例13: pp
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);
}
示例14: generate
/**
* @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);
}
示例15: obfuscateFileContents
/**
* 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;
}