Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
56.00% covered (warning)
56.00%
56 / 100
66.67% covered (warning)
66.67%
8 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
Cli
56.00% covered (warning)
56.00%
56 / 100
66.67% covered (warning)
66.67%
8 / 12
146.40
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 run
75.86% covered (warning)
75.86%
22 / 29
0.00% covered (danger)
0.00%
0 / 1
12.70
 runCss
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 runCssRemap
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
2.09
 runJs
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 runJsDebug
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
56
 runJsMapWeb
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 runJsMapRaw
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 help
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 error
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 output
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getExitCode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php declare( strict_types=1 );
2/**
3 * Copyright 2021 Timo Tijhof
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * @file
18 * @license Apache-2.0
19 */
20
21namespace Wikimedia\Minify;
22
23/**
24 * Implementation of `minify` CLI.
25 *
26 * @internal For use by `bin/minify` only.
27 */
28final class Cli {
29    /** @var int $exitCode */
30    private $exitCode = 0;
31    /** @var resource $in */
32    private $in;
33    /** @var resource $out */
34    private $out;
35    /** @var string $self */
36    private $self;
37    /** @var string $command */
38    private $command;
39    /** @var string[] $params */
40    private $params;
41
42    /**
43     * @param resource $in An open stream for reading input with `fgets()`
44     * @param resource $out An open stream for writing output with `fwrite()`
45     * @param string[] $argv
46     */
47    public function __construct( $in, $out, array $argv ) {
48        $this->in = $in;
49        $this->out = $out;
50        $this->self = basename( $argv[0] ?? '/minify' );
51        $this->command = $argv[1] ?? '';
52        $this->params = array_slice( $argv, 2 );
53    }
54
55    /** Perform the specified command. */
56    public function run(): void {
57        try {
58            switch ( $this->command ) {
59                case 'css':
60                    $this->runCss( ...$this->params );
61                    break;
62                case 'css-remap':
63                    $this->runCssRemap( ...$this->params );
64                    break;
65                case 'js':
66                    $this->runJs( ...$this->params );
67                    break;
68                case 'jsdebug':
69                    $this->runJsDebug( ...$this->params );
70                    break;
71                case 'jsmap-web':
72                    $this->runJsMapWeb( ...$this->params );
73                    break;
74                case 'jsmap-raw':
75                    $this->runJsMapRaw( ...$this->params );
76                    break;
77                case '':
78                case 'help':
79                    $this->exitCode = 1;
80                    $this->help();
81                    break;
82                default:
83                    $this->error( 'Unknown command' );
84                    break;
85            }
86        } catch ( \Throwable $e ) {
87            $this->exitCode = 1;
88            $this->output( (string)$e );
89        }
90    }
91
92    private function runCss( ?string $file = null ): void {
93        $data = $file === null ? stream_get_contents( $this->in ) : file_get_contents( $file );
94        $this->output( CSSMin::minify( $data ) );
95    }
96
97    private function runCssRemap( ?string $file = null ): void {
98        if ( $file === null ) {
99            $this->error( 'Remapping requires a filepath' );
100            return;
101        }
102        $fulldir = dirname( realpath( $file ) );
103        $data = file_get_contents( $file );
104        $data = CSSMin::remap( $data, $fulldir, $fulldir );
105        $this->output( CSSMin::minify( $data ) );
106    }
107
108    private function runJs( ?string $file = null ): void {
109        $data = $file === null ? stream_get_contents( $this->in ) : file_get_contents( $file );
110        $onError = function ( ParseError $error ) {
111            $this->output( 'ParseError: ' . $error->getMessage() . ' at position ' . $error->getOffset() );
112            $this->exitCode = 1;
113        };
114        $ret = JavaScriptMinifier::minify( $data, $onError );
115        if ( !$this->exitCode ) {
116            $this->output( $ret );
117        }
118    }
119
120    private function runJsDebug( ?string $file = null ): void {
121        $data = $file === null ? stream_get_contents( $this->in ) : file_get_contents( $file );
122        $onError = function ( ParseError $error ) {
123            $this->output( 'ParseError: ' . $error->getMessage() . ' at position ' . $error->getOffset() );
124            $this->exitCode = 1;
125        };
126
127        $first = true;
128        $onDebug = static function ( array $frame ) use ( &$first ) {
129            if ( $first ) {
130                print sprintf( "| %-45s | %-4s | %-22s | %-17s | %-16s\n",
131                    'stack', 'last', 'state', 'token', 'type' );
132                print sprintf( "| %'-45s | %'-4s | %'-22s | %'-17s | %'-16s\n",
133                    '', '', '', '', '' );
134                $first = false;
135            }
136            $stackStrLen = 0;
137            $stackPieces = [];
138            $stackOverflow = 0;
139            foreach ( array_reverse( $frame['stack'] ) as $i => $state ) {
140                $stackStrLen += strlen( $state ) + 2;
141                if ( $stackStrLen < 40 ) {
142                    $stackPieces[] = $state;
143                } else {
144                    $stackOverflow++;
145                }
146            }
147            if ( $stackOverflow ) {
148                $stackPieces[] = "$stackOverflow ...";
149            }
150            $stack = implode( ', ', array_reverse( $stackPieces ) );
151            print sprintf( "| %-45s | %-4s | %-22s | @%-3s %-12s | %-16s\n",
152                $stack, $frame['last'], $frame['state'], $frame['pos'], $frame['token'], $frame['type'] );
153        };
154        $ret = JavaScriptMinifier::minifyInternal( $data, null, $onError, $onDebug );
155        if ( !$this->exitCode ) {
156            $this->output( $ret );
157        }
158    }
159
160    private function runJsMapWeb( ?string $file = null ): void {
161        $data = $file === null ? stream_get_contents( $this->in ) : file_get_contents( $file );
162        $sourceName = $file === null ? 'file.js' : basename( $file );
163        $mapper = JavaScriptMinifier::createSourceMapState();
164        $mapper->addSourceFile( $sourceName, $data, true );
165        $this->output( rtrim( $mapper->getSourceMap(), "\n" ) );
166    }
167
168    private function runJsMapRaw( ?string $file = null ): void {
169        $data = $file === null ? stream_get_contents( $this->in ) : file_get_contents( $file );
170        $sourceName = $file === null ? 'file.js' : basename( $file );
171        $mapper = JavaScriptMinifier::createSourceMapState();
172        $mapper->addSourceFile( $sourceName, $data, true );
173        $this->output( rtrim( $mapper->getRawSourceMap(), "\n" ) );
174    }
175
176    private function help(): void {
177        $this->output( <<<TEXT
178usage: {$this->self} <command>
179
180commands:
181   css [<file>]        Minify input data as CSS code, and write to output.
182                       Reads from stdin by default, or can read from a file.
183   css-remap <file>    Remap and process any "@embed" comments in a CSS file,
184                       and write the minified code to output.
185   js  [<file>]        Minify input data as JavaScript code, write to output.
186                       Reads from stdin by default, or can read from a file.
187   jsmap-raw [<file>]  Minify JavaScript code and write a raw source map to
188                       output. Such a source map should not be delivered over
189                       HTTP due to XSSI concerns.
190   jsmap-web [<file>]  Minify JavaScript code and write a source map with XSSI
191                       prefix.
192TEXT
193        );
194    }
195
196    private function error( string $text ): void {
197        $this->exitCode = 1;
198        $this->output( "\n{$this->self} error: $text\n\n------\n" );
199        $this->help();
200    }
201
202    private function output( string $text ): void {
203        fwrite( $this->out, $text . "\n" );
204    }
205
206    /** @return int */
207    public function getExitCode(): int {
208        return $this->exitCode;
209    }
210}