Update PHP scripts from their AST by using php-parser for reading and php-unparser for generating back the php.
You must include the module to your script and feed to it a php file string.
var fs = require('fs');
// Load the writer
var writer = require('php-writer');
// Read file content
var contents = fs.readFileSync('my-php-file.php', 'utf8');
// All the possible options
var options = {
writer: {
indent: true,
dontUseWhitespaces: false,
shortArray: true,
forceNamespaceBrackets: false
},
parser: {
debug: false,
locations: false,
extractDoc: false,
suppressErrors: false
},
lexer: {
all_tokens: false,
comment_tokens: false,
mode_eval: false,
asp_tags: false,
short_tags: false
},
ast: {
withPositions: true
}
};
// Init the writer
var myPhpFile = new writer(contents, options);
// Print the file AST object
console.log(myPhpFile);
You can pass to the writer an options object to customize your writer instance:
- writer: The same options you would pass to php-unparser
- parser: The same options you would pass to php-parser
- ast: The same options you would pass to php-parser
If you want to learn more about AST you can read the definitions.
All the examples assume that you have already loaded the file like in the example.
var myPhpFile = new writer(contents, options);
myPhpFile.findFunction('foo').setCode('return $a + $b');
var myPhpFile = new writer(contents, options);
myPhpFile.findClass('Foo_Class').setProperty('bar', 'foo-bar');