|
| 1 | +#!/usr/bin/php |
| 2 | +<?php # minify.php - Nate Nasteff 2020 |
| 3 | + |
| 4 | +// A simple CSS minifier to be run from the command line. |
| 5 | + |
| 6 | +// If no args are received from CL or help is requested.. |
| 7 | + |
| 8 | +if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) { |
| 9 | + |
| 10 | +?> |
| 11 | + |
| 12 | +CSS command-line minifier. |
| 13 | +Takes an argument of .css file and outputs |
| 14 | +the minified CSS into a .min.css file, retaining |
| 15 | +the original name. |
| 16 | + |
| 17 | + Usage: |
| 18 | + minify <foo.css> |
| 19 | + |
| 20 | +<?php |
| 21 | +} |
| 22 | + |
| 23 | +else { |
| 24 | + // Define needles for stripping newlines and spaces |
| 25 | + |
| 26 | + $needles = ["\n", " "]; |
| 27 | + |
| 28 | + // Define regex patterns to strip comments |
| 29 | + |
| 30 | + $regex = array( |
| 31 | + "`^([\t\s]+)`ism"=>'', |
| 32 | + "`^\/\*(.+?)\*\/`ism"=>"", |
| 33 | + "`([\n\A;]+)\/\*(.+?)\*\/`ism"=>"$1", |
| 34 | + "`([\n\A;\s]+)//(.+?)[\n\r]`ism"=>"$1\n", |
| 35 | + "`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism"=>"\n" |
| 36 | + ); |
| 37 | + |
| 38 | + // Check that the file name is valid, and assign contents to css_str |
| 39 | + |
| 40 | + if (file_exists($argv[1])){ |
| 41 | + |
| 42 | + $css_str = file_get_contents($argv[1]); |
| 43 | + |
| 44 | + // Remove comments, strip whitespaces / newlines |
| 45 | + |
| 46 | + $css_str = preg_replace(array_keys($regex), $regex, $css_str); |
| 47 | + $css_str = str_replace($needles, "", $css_str); |
| 48 | + |
| 49 | + // Strip trailing semicolons at the end of css definitions |
| 50 | + |
| 51 | + $css_str = str_replace(";}", "}", $css_str); |
| 52 | + |
| 53 | + // Update filename |
| 54 | + |
| 55 | + $minified_filename = str_replace(".css", ".min.css", $argv[1]); |
| 56 | + |
| 57 | + // Attempt to save the new minified CSS |
| 58 | + try { |
| 59 | + file_put_contents($minified_filename, $css_str); |
| 60 | + } |
| 61 | + |
| 62 | + catch (Exception $e) { |
| 63 | + echo $e->getMessage(); |
| 64 | + } |
| 65 | + |
| 66 | + echo "Minified CSS file written to" . $minified_filename ."\n"; |
| 67 | +} |
| 68 | + |
| 69 | +// Make sure file is actually a valid CSS file.. |
| 70 | + |
| 71 | +else if (!strpos($argv[1], '.css')) { |
| 72 | + echo "Not a valid CSS file!"; |
| 73 | +} |
| 74 | + |
| 75 | +// If no file is found / incorrect filename.. |
| 76 | + |
| 77 | +else { |
| 78 | + echo "File not found or incorrect filename!"; |
| 79 | +} |
| 80 | + |
| 81 | +} |
| 82 | +?> |
0 commit comments