-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.php
92 lines (75 loc) · 2.41 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Name: Combine Scripts
* Description: A simple PHP script to combine script assets
* Version: 0.2.0
* Author: Daniel M. Hendricks
* GitHub: https://github.com/dmhendricks/php-combine-scripts
*/
use MatthiasMullie\Minify;
$version = '0.2.0';
require( __DIR__ . '/vendor/autoload.php' );
// Load environmental configuration
if( file_exists( '.env' ) ) {
$dotenv = \Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
}
// Set variables
$basedir = rtrim( getenv( 'COMBINE_BASEDIR' ) ?: __DIR__, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR;
$disable_file_check = filter_var( getenv( 'COMBINE_DISABLE_FILE_EXISTS' ), FILTER_VALIDATE_BOOLEAN );
$disable_minify = filter_var( getenv( 'COMBINE_DISABLE_MINIFY' ), FILTER_VALIDATE_BOOLEAN );
// Get scripts from querystring
$scripts = isset( $_GET['scripts'] ) ? $_GET['scripts'] : false;
if( !$scripts ) {
header( 'HTTP/1.1 400 Bad Request', true, 400 );
die( '400 Bad Request' );
} else {
$scripts = explode( ',', $scripts );
}
// Sanitize input
$error = false;
$files = [];
$type = null;
foreach( $scripts as $script ) {
$script = trim( $script, './' );
$ext = explode( '.', strtolower( $script ) );
if( $type !== null && $type != end( $ext ) ) {
$error = true;
} else {
$type = end( $ext );
}
if( !$disable_file_check && !file_exists( $basedir . $script ) ) $error = true;
$files[] = $basedir . $script;
}
if( $error ) {
header( 'HTTP/1.1 400 Bad Request', true, 400 );
die( '400 Bad Request' );
}
// Combine scripts
$output = '';
foreach( $files as $file ) {
$output .= file_get_contents( $file ) . "\n";
}
// Minify output
if( !$disable_minify ) {
$minifier = null;
if( $type == 'js' ) {
$minifier = new Minify\JS();
} else if( $type == 'css' ) {
$minifier = new Minify\CSS();
}
if( $minifier ) {
$minifier->add( $output );
$output = $minifier->minify();
}
}
// Add header to result
$output = sprintf( "/**\n * %s by php-combine-scripts v%s.\n * More information: https://github.com/dmhendricks/php-combine-scripts\n */\n%s", $disable_minify ? 'Combined' : 'Minified', $version, $output );
// Set content type
$content_type = 'text/plain';
if( in_array( $type, [ 'js', 'css' ] ) ) {
$content_type = $type == 'js' ? 'text/javascript' : 'text/css';
}
// Output to browser
header( "Content-Type: {$content_type}" );
echo $output;