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