0

Lets say we have the following javascript snippets coming from two files. How do we build all.js with PHP?

a.js

var a = 20;
function foo() {
  console.warn('bar');
}
foo();
$(document).ready(function() {
  $(".someid").on("click", ".class", function() {
    do_stuff();
  });
});

b.js

var x = ['room', 'admin', 2];
$(document).ready(function() {
  $.post("url/", { n: 80}, function(j) {
    console.log(j);
  }, "json");
});

all.js

var a = 20;
function foo() {
  console.warn('bar');
}
foo();

var x = ['room', 'admin', 2];

$(document).ready(function() {
  $(".someid").on("click", ".class", function() {
    do_stuff();
  });
  $.post("url/", { n: 80}, function(j) {
    console.log(j);
  }, "json");
});
Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127
  • what do yo umean, "build with php"? Combine the two files? `$all = file_get_contents('a.js') . file_get_contents('b.js')`. – Marc B May 11 '14 at 05:11
  • @MarcB Not that part. Let's assume we already have the file contents in `$a` and `$b`. We want to end up with `$all` as in `all.js`. – Majid Fouladpour May 11 '14 at 05:13
  • you can't. not unless you want to build a JS parser for PHP. – Marc B May 11 '14 at 05:15
  • I think having more than one `document.ready()` callback is working. – Loïc May 11 '14 at 05:17
  • @MarcB I was thinking maybe I'd use `$parts = explode('$(document).ready(function() {', $a);` then use `strrchr` to find the last `});`. But thought there might be a better way. – Majid Fouladpour May 11 '14 at 05:18

1 Answers1

0

This is what I cooked at the end. It assumes some conventions are followed and would break if not. But it is good enough for my present needs.

$js_sources = array('
  var a = 20;
  function foo() {
    console.warn("bar");
  }
  foo();
  $(document).ready(function() {
    $(".someid").on("click", ".class", function() {
      do_stuff();
    });
  });','
  var x = ["room", "admin", 2];
    $(document).ready(function() {
      $.post("url/", { n: 80}, function(j) {
        console.log(j);
      }, "json");
    });
');   
$outjs = array();
$outready = array();
foreach($js_sources as $js) {
  $js = explode('$(document).ready(function() {', $js);
  $outjs[] = $js[0];
  $js = $js[1];
  $mark = strrpos($js , '});');
  $outjs[] = substr($js, $mark + 3);
  $outready[] = substr($js, 0, $mark);
}
$out = implode(PHP_EOL, $outjs) . 
  '$(document).ready(function() {' . implode(PHP_EOL, $outready) . '});';
Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127