Last active
February 29, 2020 08:28
-
-
Save ulcuber/7e8ddf27e94eef62fc4776157dd36bcb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use RuntimeException; | |
use Illuminate\Support\Str; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\Storage; | |
/** | |
* Warning: chrome coverage skips @keyframes, @font-face, @media | |
* So, need to bundle auto.css with media.css after this command | |
*/ | |
class OptimizeCssCommand extends Command | |
{ | |
protected $signature = 'css:optimize'; | |
protected $description = 'Optimize css using chrome coverage'; | |
public function handle() | |
{ | |
$this->optimize('public/css/app.css', 'resources/css/app-desktop-auto.css', 'Coverage-desktop.json'); | |
$this->optimize('public/css/app.css', 'resources/css/app-mobile-auto.css', 'Coverage-mobile.json'); | |
$this->info('OK'); | |
} | |
public function optimize(string $from, string $to, string $coverage) | |
{ | |
$disk = Storage::disk('root'); | |
$file = $disk->get($from); | |
$ranges = $this->getCoverageRanges($coverage); | |
$bar = $this->output->createProgressBar(count($ranges)); | |
$bar->start(); | |
$minified = ''; | |
$last = ''; | |
$start = 0; | |
while ($range = array_shift($ranges)) { | |
if ($range['start'] !== $start) { | |
$minified .= $last; | |
} | |
$start = $range['start']; | |
$length = $range['end'] - $start; | |
$last = mb_substr($file, $start, $length); | |
$bar->advance(); | |
} | |
$bar->finish(); | |
$this->info(''); | |
$disk->put($to, $minified); | |
} | |
protected function getCoverageRanges(string $file): array | |
{ | |
$coverageFile = Storage::disk('local')->get($file); | |
$coverage = json_decode($coverageFile, true); | |
if (!is_array($coverage)) { | |
throw new RuntimeException('Coverage not found'); | |
} | |
foreach ($coverage as $item) { | |
if (Str::contains($item['url'], '/css/app.css')) { | |
return $item['ranges']; | |
} | |
} | |
throw new RuntimeException('Css not found'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment