]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/Filter/JPackFilter.php
Update to 4.x new path
[packbundle] / Twig / Filter / JPackFilter.php
1 <?php
2
3 // src/Rapsys/PackBundle/Twig/Filter/JPackFilter.php
4 namespace Rapsys\PackBundle\Twig\Filter;
5
6 use Rapsys\PackBundle\Twig\Filter\FilterInterface;
7
8 class JPackFilter implements FilterInterface {
9 //Default bin
10 private $bin;
11
12 //Default compress type
13 private $compress;
14
15 //Twig template filename
16 private $fileName;
17
18 //Twig template line
19 private $line;
20
21 //Configure the object
22 //XXX: can be clean, shrink, obfuscate or best
23 public function __construct($fileName, $line, $bin = 'jpack', $compress = 'best') {
24 //Set fileName
25 $this->fileName = $fileName;
26
27 //Set line
28 $this->line = $line;
29
30 //Set bin
31 $this->bin = $bin;
32
33 //Set compress
34 $this->compress = $compress;
35
36 //Deal with compress
37 if (!empty($this->compress)) {
38 //Append clean parameter
39 if ($this->compress == 'clean') {
40 $this->bin .= ' --clean';
41 //Append shrink parameter
42 } elseif ($this->compress == 'shrink') {
43 $this->bin .= ' --shrink';
44 //Append obfuscate parameter
45 } elseif ($this->compress == 'obfuscate') {
46 $this->bin .= ' --obfuscate';
47 //Unknown compress type
48 #XXX: default compression is best
49 } elseif ($this->compress !== 'best') {
50 //Throw an error on unknown compress
51 throw new \Twig_Error(sprintf('Got unexpected compress for %s: %s', $this->bin, $this->compress), $this->line, $this->fileName);
52 }
53 }
54 }
55
56 public function process($content) {
57 //Create descriptors
58 $descriptorSpec = array(
59 0 => array('pipe', 'r'),
60 1 => array('pipe', 'w'),
61 2 => array('pipe', 'w')
62 );
63
64 //Open process
65 if (is_resource($proc = proc_open($this->bin, $descriptorSpec, $pipes))) {
66 //Set stderr as non blocking
67 stream_set_blocking($pipes[2], 0);
68
69 //Send content to stdin
70 fwrite($pipes[0], $content);
71
72 //Close stdin
73 fclose($pipes[0]);
74
75 //Read content from stdout
76 if ($stdout = stream_get_contents($pipes[1])) {
77 $content = $stdout;
78 }
79
80 //Close stdout
81 fclose($pipes[1]);
82
83 //Read content from stderr
84 if (($stderr = stream_get_contents($pipes[2]))) {
85 throw new \Twig_Error(sprintf('Got unexpected strerr for %s: %s', $this->bin, $stderr), $this->line, $this->fileName);
86 }
87
88 //Close stderr
89 fclose($pipes[2]);
90
91 //Close process
92 if (($ret = proc_close($proc))) {
93 throw new \Twig_Error(sprintf('Got unexpected non zero return code %s: %d', $this->bin, $ret), $this->line, $this->fileName);
94 }
95 }
96
97 //Return content
98 return $content;
99 }
100 }