]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/Filter/CPackFilter.php
Fix parameter naming
[packbundle] / Twig / Filter / CPackFilter.php
1 <?php
2
3 // src/Rapsys/PackBundle/Twig/Filter/CPackFilter.php
4 namespace Rapsys\PackBundle\Twig\Filter;
5
6 use Rapsys\PackBundle\Twig\Filter\FilterInterface;
7 use Symfony\Component\DependencyInjection\ContainerInterface;
8
9 class CPackFilter implements FilterInterface {
10 //Default bin
11 private $bin = 'cpack';
12
13 //Default compress type
14 //XXX: can be minify or pretty
15 private $compress = 'minify';
16
17 //Twig template filename
18 private $fileName;
19
20 //Twig template line
21 private $line;
22
23 //Configure the object
24 public function __construct(ContainerInterface $containerInterface, $fileName, $line) {
25 //Load configuration
26 if ($containerInterface->hasParameter('rapsys_pack_cpackfilter')) {
27 if ($parameters = $containerInterface->getParameter('rapsys_pack_cpackfilter')) {
28 foreach($parameters as $k => $v) {
29 if (isset($this->$k)) {
30 $this->$k = $v;
31 }
32 }
33 }
34 }
35
36 //Set fileName
37 $this->fileName = $fileName;
38
39 //Set line
40 $this->line = $line;
41
42 //Deal with compress
43 if (!empty($this->compress)) {
44 //Append minify parameter
45 if ($this->compress == 'minify') {
46 $this->bin .= ' --minify';
47 //Unknown compress type
48 #XXX: default compression is pretty
49 } elseif ($this->compress !== 'pretty') {
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 }