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