]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/Filter/CPackFilter.php
Add context supporting getBaseUrl feature
[packbundle] / Twig / Filter / CPackFilter.php
1 <?php
2
3 namespace Rapsys\PackBundle\Twig\Filter;
4
5 use Rapsys\PackBundle\Twig\Filter\FilterInterface;
6 use Twig\Error\Error;
7
8 class CPackFilter 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: compress can be minify or pretty
23 public function __construct($fileName, $line, $bin = 'cpack', $compress = 'minify') {
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 minify parameter
39 if ($this->compress == 'minify') {
40 $this->bin .= ' --minify';
41 //Unknown compress type
42 //XXX: default compression is pretty
43 } elseif ($this->compress !== 'pretty') {
44 //Throw an error on unknown compress
45 throw new Error(sprintf('Got unexpected compress for %s: %s', $this->bin, $this->compress), $this->line, $this->fileName);
46 }
47 }
48 }
49
50 public function process($content) {
51 //Create descriptors
52 $descriptorSpec = array(
53 0 => array('pipe', 'r'),
54 1 => array('pipe', 'w'),
55 2 => array('pipe', 'w')
56 );
57
58 //Open process
59 if (is_resource($proc = proc_open($this->bin, $descriptorSpec, $pipes))) {
60 //Set stderr as non blocking
61 stream_set_blocking($pipes[2], 0);
62
63 //Send content to stdin
64 fwrite($pipes[0], $content);
65
66 //Close stdin
67 fclose($pipes[0]);
68
69 //Read content from stdout
70 if ($stdout = stream_get_contents($pipes[1])) {
71 $content = $stdout;
72 }
73
74 //Close stdout
75 fclose($pipes[1]);
76
77 //Read content from stderr
78 if (($stderr = stream_get_contents($pipes[2]))) {
79 throw new Error(sprintf('Got unexpected strerr for %s: %s', $this->bin, $stderr), $this->line, $this->fileName);
80 }
81
82 //Close stderr
83 fclose($pipes[2]);
84
85 //Close process
86 if (($ret = proc_close($proc))) {
87 throw new Error(sprintf('Got unexpected non zero return code %s: %d', $this->bin, $ret), $this->line, $this->fileName);
88 }
89 }
90
91 //Return content
92 return $content;
93 }
94 }