1<?php 2 3/* 4 * This file is part of the Assetic package, an OpenSky project. 5 * 6 * (c) 2010-2014 OpenSky Project Inc 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Assetic\Filter; 13 14use Assetic\Asset\AssetInterface; 15use Assetic\Exception\FilterException; 16use Assetic\Util\FilesystemUtils; 17 18/** 19 * UglifyCss filter. 20 * 21 * @link https://github.com/fmarcia/UglifyCSS 22 * @author Franck Marcia <franck.marcia@gmail.com> 23 */ 24class UglifyCssFilter extends BaseNodeFilter 25{ 26 private $uglifycssBin; 27 private $nodeBin; 28 29 private $expandVars; 30 private $uglyComments; 31 private $cuteComments; 32 33 /** 34 * @param string $uglifycssBin Absolute path to the uglifycss executable 35 * @param string $nodeBin Absolute path to the folder containg node.js executable 36 */ 37 public function __construct($uglifycssBin = '/usr/bin/uglifycss', $nodeBin = null) 38 { 39 $this->uglifycssBin = $uglifycssBin; 40 $this->nodeBin = $nodeBin; 41 } 42 43 /** 44 * Expand variables 45 * @param bool $expandVars True to enable 46 */ 47 public function setExpandVars($expandVars) 48 { 49 $this->expandVars = $expandVars; 50 } 51 52 /** 53 * Remove newlines within preserved comments 54 * @param bool $uglyComments True to enable 55 */ 56 public function setUglyComments($uglyComments) 57 { 58 $this->uglyComments = $uglyComments; 59 } 60 61 /** 62 * Preserve newlines within and around preserved comments 63 * @param bool $cuteComments True to enable 64 */ 65 public function setCuteComments($cuteComments) 66 { 67 $this->cuteComments = $cuteComments; 68 } 69 70 /** 71 * @see Assetic\Filter\FilterInterface::filterLoad() 72 */ 73 public function filterLoad(AssetInterface $asset) 74 { 75 } 76 77 /** 78 * Run the asset through UglifyJs 79 * 80 * @see Assetic\Filter\FilterInterface::filterDump() 81 */ 82 public function filterDump(AssetInterface $asset) 83 { 84 $pb = $this->createProcessBuilder($this->nodeBin 85 ? array($this->nodeBin, $this->uglifycssBin) 86 : array($this->uglifycssBin)); 87 88 if ($this->expandVars) { 89 $pb->add('--expand-vars'); 90 } 91 92 if ($this->uglyComments) { 93 $pb->add('--ugly-comments'); 94 } 95 96 if ($this->cuteComments) { 97 $pb->add('--cute-comments'); 98 } 99 100 // input and output files 101 $input = FilesystemUtils::createTemporaryFile('uglifycss'); 102 103 file_put_contents($input, $asset->getContent()); 104 $pb->add($input); 105 106 $proc = $pb->getProcess(); 107 $code = $proc->run(); 108 unlink($input); 109 110 if (127 === $code) { 111 throw new \RuntimeException('Path to node executable could not be resolved.'); 112 } 113 114 if (0 !== $code) { 115 throw FilterException::fromProcess($proc)->setInput($asset->getContent()); 116 } 117 118 $asset->setContent($proc->getOutput()); 119 } 120} 121