1+ <?php
2+
3+ namespace MatTheCat \HtmlCompressorBundle \EventListener ;
4+
5+ use Symfony \Component \HttpKernel \HttpKernelInterface ;
6+ use Symfony \Component \HttpKernel \Event \FilterResponseEvent ;
7+ use Symfony \Component \Process \ProcessBuilder ;
8+
9+ class ResponseListener
10+ {
11+ protected $ javaPath ;
12+ protected $ htmlCompressorPath ;
13+ protected $ htmlCompressorOptions ;
14+
15+ public function __construct ($ javaPath , $ htmlCompressorPath , array $ htmlCompressorOptions )
16+ {
17+ $ this ->javaPath = $ javaPath ;
18+ $ this ->htmlCompressorPath = $ htmlCompressorPath ;
19+ $ this ->htmlCompressorOptions = $ htmlCompressorOptions ;
20+ }
21+
22+ public function onKernelResponse (FilterResponseEvent $ event ) {
23+ $ response = $ event ->getResponse ();
24+ $ contentType = $ response ->headers ->get ('Content-type ' );
25+ if (
26+ !$ response ->isCacheable () ||
27+ in_array (
28+ substr ($ contentType , strrpos ($ contentType , '/ ' )+1 ),
29+ array ('xml ' , 'html ' )
30+ )
31+ ) {
32+ return ;
33+ }
34+ $ pb = new ProcessBuilder (
35+ array (
36+ $ this ->javaPath ,
37+ '-jar ' ,
38+ $ this ->htmlCompressorPath
39+ )
40+ );
41+ foreach ($ this ->htmlCompressorOptions as $ option => $ value ) {
42+ if (!is_null ($ option )) {
43+ $ pb ->add ($ option );
44+
45+ if (!is_null ($ value )) {
46+ $ pb ->add ($ value );
47+ }
48+ }
49+ }
50+ $ pb ->add ($ input = tempnam (sys_get_temp_dir (), 'html_compressor ' ));
51+ file_put_contents ($ input , $ response ->getContent ());
52+ $ proc = $ pb ->getProcess ();
53+ $ code = $ proc ->run ();
54+ unlink ($ input );
55+
56+ if (!$ code ) {
57+ $ response ->setContent ($ proc ->getOutput ());
58+ }
59+ }
60+ }
0 commit comments