YUI javascript compressor and PHP tags

YUI compressor is very useful and powerful tool for javascript files compression. Many developers compress their static javascript files but what about files with PHP tags? With something like this:
var username = "<?php echo $username; ?>";
or like this
function() {
    var some_code_before; 
    <?php if (Acl::check("finance")) { ?>
    Ext.addShortcut('finance');
    <?php } ?>
    var some_code_after; 
}
First example will work, but YUI will throw an exception on second. And also this piece of javascript code does not pass validation. Lets wrap PHP tags into comments:
function() {
    var some_code_before; 
    /*<?php if (Acl::check("finance")) { ?>*/
    Ext.addShortcut('finance');
    /*<?php } ?>*/
    var some_code_after; 
}
Now this code is valid. But lets try to feed it to YUI:
# yui test.js 
function(){var b;Ext.addShortcut("finance");var a};
PHP tags are stripped away by YUI and our Acl check is missing.

YUI has a "Special comments" functionality. Page http://developer.yahoo.com/yui/compressor/css.html#min says that any comment that start with a /*! will be preserved. Lets try it:
function() {
    var some_code_before; 
    /*!<?php if (Acl::check("finance")) { ?>*/
    Ext.addShortcut('finance');
    /*!<?php } ?>*/
    var some_code_after; 
}
Result:
# yui test.js 
function(){var b;
/*!<?php if (Acl::check("finance")) { ?>*/
Ext.addShortcut("finance");
/*!<?php } ?>*/
var a};
Good, our acl checking code is preserved, but not perfect: YUI preserves comments and adds newlines before and after comments. Lets fix this:
# yui test.js | sed ':a;N;$!ba;s#\n/\*!##g' | sed ':a;N;$!ba;s#*/\n##g'
function(){var b;<?php if (Acl::check("finance")) { ?>Ext.addShortcut("finance");<?php } ?>var a}; 
Now is much better.
Also a version that preserves comments (and passes javascript validation):
# yui test.js | sed ':a;N;$!ba;s#\n/\*!#/*#g' | sed ':a;N;$!ba;s#*/\n#*/#g'
function(){var b;/*<?php if (Acl::check("finance")) { ?>*/Ext.addShortcut("finance");/*<?php } ?>*/var a};

Comments

Popular posts from this blog

Memory efficient array permutation in PHP 5.5 using generators

How to dump http request headers with PHP under CGI/FastCGI SAPI

Zend Framework 2 AJAX: return JSON response from controller action. The proper way.