]> Raphaël G. Git Repositories - packbundle/blob - Filter/CPackFilter.php
Remove debug
[packbundle] / Filter / CPackFilter.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys PackBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\PackBundle\Filter;
13
14 use Twig\Error\Error;
15 use Twig\Source;
16
17 /**
18 * {@inheritdoc}
19 */
20 class CPackFilter implements FilterInterface {
21 //Default bin
22 private $bin;
23
24 //Default compress type
25 private $compress;
26
27 //Twig template filename
28 private $fileName;
29
30 //Twig template line
31 private $line;
32
33 /**
34 * Setup cpack filter
35 *
36 * @xxx compress can be minify or pretty
37 */
38 public function __construct(Source $fileName, int $line, string $bin = 'cpack', string $compress = 'minify') {
39 //Set fileName
40 $this->fileName = $fileName;
41
42 //Set line
43 $this->line = $line;
44
45 //Set bin
46 $this->bin = $bin;
47
48 //Set compress
49 $this->compress = $compress;
50
51 //Deal with compress
52 if (!empty($this->compress)) {
53 //Append minify parameter
54 if ($this->compress == 'minify') {
55 $this->bin .= ' --minify';
56 //Unknown compress type
57 //XXX: default compression is pretty
58 } elseif ($this->compress !== 'pretty') {
59 //Throw an error on unknown compress
60 throw new Error(sprintf('Got unexpected compress for %s: %s', $this->bin, $this->compress), $this->line, $this->fileName);
61 }
62 }
63 }
64
65 /**
66 * {@inheritdoc}
67 */
68 public function process(string $content): string {
69 //Create descriptors
70 $descriptorSpec = array(
71 0 => array('pipe', 'r'),
72 1 => array('pipe', 'w'),
73 2 => array('pipe', 'w')
74 );
75
76 //Open process
77 if (is_resource($proc = proc_open($this->bin, $descriptorSpec, $pipes))) {
78 //Set stderr as non blocking
79 stream_set_blocking($pipes[2], false);
80
81 //Send content to stdin
82 fwrite($pipes[0], $content);
83
84 //Close stdin
85 fclose($pipes[0]);
86
87 //Read content from stdout
88 if ($stdout = stream_get_contents($pipes[1])) {
89 $content = $stdout;
90 }
91
92 //Close stdout
93 fclose($pipes[1]);
94
95 //Read content from stderr
96 if (($stderr = stream_get_contents($pipes[2]))) {
97 throw new Error(sprintf('Got unexpected strerr for %s: %s', $this->bin, $stderr), $this->line, $this->fileName);
98 }
99
100 //Close stderr
101 fclose($pipes[2]);
102
103 //Close process
104 if (($ret = proc_close($proc))) {
105 throw new Error(sprintf('Got unexpected non zero return code %s: %d', $this->bin, $ret), $this->line, $this->fileName);
106 }
107 }
108
109 //Return content
110 return $content;
111 }
112 }