]> Raphaël G. Git Repositories - packbundle/blob - Filter/CPackFilter.php
Trim trailing equal in short
[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 /**
22 * Setup cpack filter
23 *
24 * @xxx compress can be minify or pretty
25 */
26 public function __construct(protected Source $fileName, protected int $line, protected string $bin = 'cpack', protected string $compress = 'minify') {
27 //Deal with compress
28 if (!empty($this->compress)) {
29 //Append minify parameter
30 if ($this->compress == 'minify') {
31 //TODO: protect binary call by converting bin to array ?
32 $this->bin .= ' --minify';
33 //Unknown compress type
34 //XXX: default compression is pretty
35 } elseif ($this->compress !== 'pretty') {
36 //Throw an error on unknown compress
37 throw new Error(sprintf('Got unexpected compress for %s: %s', $this->bin, $this->compress), $this->line, $this->fileName);
38 }
39 }
40 }
41
42 /**
43 * {@inheritdoc}
44 */
45 public function process(string $content): string {
46 //Create descriptors
47 $descriptorSpec = array(
48 0 => array('pipe', 'r'),
49 1 => array('pipe', 'w'),
50 2 => array('pipe', 'w')
51 );
52
53 //Open process
54 if (is_resource($proc = proc_open($this->bin, $descriptorSpec, $pipes))) {
55 //Set stderr as non blocking
56 stream_set_blocking($pipes[2], false);
57
58 //Send content to stdin
59 fwrite($pipes[0], $content);
60
61 //Close stdin
62 fclose($pipes[0]);
63
64 //Read content from stdout
65 if ($stdout = stream_get_contents($pipes[1])) {
66 $content = $stdout;
67 }
68
69 //Close stdout
70 fclose($pipes[1]);
71
72 //Read content from stderr
73 if (($stderr = stream_get_contents($pipes[2]))) {
74 throw new Error(sprintf('Got unexpected strerr for %s: %s', $this->bin, $stderr), $this->line, $this->fileName);
75 }
76
77 //Close stderr
78 fclose($pipes[2]);
79
80 //Close process
81 if (($ret = proc_close($proc))) {
82 throw new Error(sprintf('Got unexpected non zero return code %s: %d', $this->bin, $ret), $this->line, $this->fileName);
83 }
84 }
85
86 //Return content
87 return $content;
88 }
89 }