Skip to content

Instantly share code, notes, and snippets.

@itsbth
Created December 1, 2011 13:02
Show Gist options
  • Select an option

  • Save itsbth/1416573 to your computer and use it in GitHub Desktop.

Select an option

Save itsbth/1416573 to your computer and use it in GitHub Desktop.
Uploaded by UploadToGist for Sublime Text 2
<?php
namespace PHPacker
{
class CodePacker
{
private $file;
private $parser;
private $stmnts;
public static $SUPERGLOBALS = array('GLOBALS', '_SERVER', '_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_REQUEST', '_ENV');
public function __construct($proj, $fn)
{
$this->file = $fn;
$this->parser = new \PHPParser_Parser;
$this->stmnts = $this->parser->parse(new \PHPParser_Lexer(file_get_contents($fn)));
}
public function fixIncludes()
{
$traverser = new \PHPParser_NodeTraverser;
$traverser->addVisitor(new NodeVisitor_Include);
$this->stmnts = $traverser->traverse($this->stmnts);
}
public function extractCode()
{
$globals = array();
$fixed = array();
$loose = array();
foreach ($this->stmnts as $i => $stmnt) {
if ($stmnt instanceof \PHPParser_Node_Stmnt_Class ||
$stmnt instanceof \PHPParser_Node_Stmnt_Function) {
$fixed[] = $stmnt;
}
else {
$loose[] = $stmnt;
}
}
$traverser = new \PHPParser_NodeTraverser;
$traverser->addVisitor(new NodeVisitor_FixVariables);
$loose = $traverser->traverse($loose);
$fn = str_replace('/', '_', substr($this->file, 0, -4));
$fixed[] = new \PHPParser_Node_Stmt_Function("__{$fn}__file__",
array('stmts' => $loose));
$this->stmnts = $fixed;
}
public function contents()
{
$prettyPrinter = new \PHPParser_PrettyPrinter_Zend;
return $prettyPrinter->prettyPrint($this->stmnts);
}
}
class NodeVisitor_FixVariables extends \PHPParser_NodeVisitorAbstract
{
public function leaveNode(\PHPParser_Node $node) {
if ($node instanceof \PHPParser_Node_Expr_Variable &&
is_string($node->name) &&
!in_array($node->name, CodePacker::$SUPERGLOBALS)) {
return new \PHPParser_Node_Expr_ArrayDimFetch(
new \PHPParser_Node_Expr_Variable('GLOBALS'),
new \PHPParser_Node_Scalar_String($node->name));
}
}
}
class NodeVisitor_Include extends \PHPParser_NodeVisitorAbstract
{
public function leaveNode(\PHPParser_Node $node) {
if ($node instanceof \PHPParser_Node_Expr_Include) {
if ($node->expr instanceof \PHPParser_Node_Scalar_String) {
$fn = str_replace('/', '_', substr($node->expr->value, 0, -4));
return new \PHPParser_Node_Expr_FuncCall(new \PHPParser_Node_Name("__{$fn}__file__"));
}
else {
return new \PHPParser_Node_Expr_FuncCall(new \PHPParser_Node_Name('__include__'),
array($node->expr));
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment