/php-writer

Update PHP scripts from their AST

Primary LanguageJavaScriptBSD 3-Clause "New" or "Revised" LicenseBSD-3-Clause

php-writer

Build Status Coverage Status npm version Gitter

Update PHP scripts from their AST by using php-parser for reading and php-unparser for generating back the php.

How does it works?

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);

Options

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.

Examples

All the examples assume that you have already loaded the file like in the example.

Find a function and set its body value:
var myPhpFile = new writer(contents, options);
myPhpFile.findFunction('foo').setCode('return $a + $b');
Find a class and set a property value:
var myPhpFile = new writer(contents, options);
myPhpFile.findClass('Foo_Class').setProperty('bar', 'foo-bar');