Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prettyprinter renders Embedded \n in " strings is into a newline #71

Closed
kelfink opened this issue Sep 5, 2013 · 2 comments
Closed

Prettyprinter renders Embedded \n in " strings is into a newline #71

kelfink opened this issue Sep 5, 2013 · 2 comments

Comments

@kelfink
Copy link

kelfink commented Sep 5, 2013

Is there an option to preserver the embedded new-line char? Either the parser or the pretty-printer is processing them into the real thing, which corrupts my code.
thanks, (observed in 0.9.3

<?php>
require '../lib/bootstrap.php';
$parser        = new PHPParser_Parser(new PHPParser_Lexer);
$prettyPrinter = new PHPParser_PrettyPrinter_Default;
$filenames = array('testfiles/BarClass.php');
try {
    foreach ($filenames as $filename) {

        $code = file_get_contents($filename);
        // parse
        $stmts = $parser->parse($code);
        // pretty print
        $code = "<?php \n" . $prettyPrinter->prettyPrint($stmts) . "\n";
        file_put_contents($filename . '.f.php', $code);
    }
} catch (PHPParser_Error $e) {
    echo 'Parse Error: ', $e->getMessage();
}

File:

<?php
input file BarClass.php
class BarClass {
 // sample
    public function bar2() {
        echo "foo bar";
        echo "foo\nbar";
        echo 'baz\nmo';
        echo "happy birthday";
    }
}

Output file BarClass.php.f.php

<?php 
class BarClass
{
    // sample
    public function bar2()
    {
        echo 'foo bar';
        echo 'foo
bar';
        echo 'baz\\nmo';
        echo 'happy birthday';
    }
}

thanks

@nikic
Copy link
Owner

nikic commented Sep 6, 2013

The parser provides strings "as seen by PHP", i.e. in already parsed form. It does not retain the formatting of the string. Pretty printing with support for retaining formatting is discussed in #41.

In #26 you can find a solution for your particular issue with strings. The custom lexer will provide an originalValue attribute for constant encapsed strings, which you can then use in the pretty printer via:

public function pScalar_String(PHPParser_Node_Scalar_String $node) {
    return $this->pNoIndent($node->getAttribute('originalValue'));
}

This approach will not work for non-constant (interpolated) strings though.

@popstikle2
Copy link

@nikic I followed your steps on #41 and #26. But now if I have HEREDOC string it will exclude it from the pretty printer. Can you check it and tell me what I can do to keep the HEREDOC?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants