Compresser (minimiser) un fichier css

Description

Cette classe vous permet de minimiser le contenu d'un fichier CSS afin de réduire la taille de vos fichiers.

Source / Exemple :

<?php

/**
 * CSSSkrinker class
 * 
 * Compress your css files
 *
 * @author ShevAbam
 * @version 1.0 - 22 Sept 2009
 */
class CSSShrinker
{
    private $_file_original;
    private $_file_minimized;
    private $_file_content_original;
    private $_file_content_shrink;
    
    private $_config = array(
        'suffix'        => '.min', 
        'comments'      => true,    // remove /* */ comments
        'fontweight'    => true,    // font-weight: bold ==> font-weight: 700
        'zerodotvalues' => true,    // 0.2 ==> .2
        'zerounits'     => true,    // 0px ==> 0
        'quotes'        => true,    // background-url: url('test.png') ==> background-url: url(test.png)
        'hex'           => true     // #ffffff ==> #fff
    );
    
    
    
    /**
     * Constructor
     * 
     * @access public
     * @param   string  $file_original
     * @param   array   $config
     * @return void
     */
    public function __construct($file_original, $config = array())
    {
        $this->_setConfig($config);
        
        if (empty($file_original))
            throw new Exception('CSSShrinker::__construct - First parameter must be filled');
        else
            $this->_file_original = $file_original;
        
        
        // Generate minimized filename
        $this->_file_minimized = $this->_generateMinimizedFileName();
        
        // Run compression
        $this->_shrinkFile();
    }
    
    
    
    /**
     * Sets configuration
     * 
     * @access   private
     * @param    array    $array  Configuration array
     * @return   void
     */
    private function _setConfig($array)
    {
        if (!empty($array))
            $this->_config = array_merge($this->_config, $array);
    }
    
    
    
    /**
     * Generate minimized filename
     * 
     * @access   private
     * @return   string
     */
    private function _generateMinimizedFileName()
    {
        $extAndDot = strrchr($this->_file_original, '.');
        
        return substr($this->_file_original, 0, -strlen($extAndDot)).$this->_config['suffix'].$extAndDot;
    }
    
    
    /**
     * Read file
     * 
     * @access   private
     * @param    string    $file
     * @return   string
     */
    private function _readFile($file)
    {
        if (!file_exists($file) || filesize($file) == 0)
            throw new Exception('CSSShrinker::_readFile - $file doesn\'t exists');
        else
            return file_get_contents($file);
    }
    
    /**
     * Write into minimized file
     * 
     * @access   private
     * @return   bool
     */
    private function _writeFile()
    {
        if (!empty($this->_file_content_shrink))
        {
            $fput = file_put_contents($this->_file_minimized, $this->_file_content_shrink);
            
            if (!$fput)
                throw new Exception('CSSShrinker::_writeFile - file_put_contents error');
            else
                return true;
        }
    }
    
    
    /**
     * Compress file
     * 
     * @access    private
     * @return    bool
     */
    private function _shrinkFile()
    {
        // If minimized file already exists or if original file is newer than the minimized
        if (!file_exists($this->_file_minimized) || filemtime($this->_file_minimized) < filemtime($this->_file_original))
        {
            $this->_file_content_original = $this->_readFile($this->_file_original);
            
            $this->_shrinkString();
            
            return $this->_writeFile() ? true : false;
        }
        else
            return false;
    }
    
    
    
    
    /**
     * Removes comments
     * 
     * @access   private
     * @param    string    $str
     * @return   string
     */
    private function _strip_comments($str)
    {
        return preg_replace('#/\*.*?\*/#s', '', $str);
    }
    
    
    /**
     * Sets font-weight
     * 
     * @access   private
     * @param    string    $str
     * @return   string
     */
    private function _strip_fontWeight($str)
    {
        $one = array('lighter' , 'normal' , 'bold' , 'bolder' );
        $two = array('100'     , '400'    , '700'  , '900'    );
        
        return str_replace($one, $two, $str);
    }
    
    
    /**
     * Removes unnecessary zeros : 0.2 ==> .2
     * 
     * @access   private
     * @param    string    $str
     * @return   string
     */
    private function _strip_zerodotValues($str)
    {
        return trim(eregi_replace('([^0-9])0\.([0-9]+)em', '\\1.\\2em', ' '.$str));
    }
    
    
    /**
     * Removes unnecessary units : 0px ==> 0
     * 
     * @access   private
     * @param    string    $str
     * @return   string
     */
    private function _strip_zeroUnits($str)
    {
        return trim(eregi_replace('([^0-9])0(px|em|\%)', '\\10', ' '.$str));
    }
    
    
    /**
     * Removes the quotes before and after the parentheses
     * 
     * @access   private
     * @param    string    $str
     * @return   string
     */
    private function _strip_quotes($str)
    {
        $one = array('("' , '(\'' , '")' , '\')' );
        $two = array('('  , '('   , ')'  , ')'   );
        
        return str_replace($one, $two, $str);
    }
    
    
    /**
     * Changes the color hex : #ffffff ==> #fff
     * 
     * @access    private
     * @param    string   $str
     * @return    string
     */
    private function _strip_hexColors($str)
    {
        return preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i', '$1#$2$3$4$5', $str);
    }
    
    
    
    /**
     * Main execution
     * 
     * @access    private
     * @param    none
     * @return    void
     */
    private function _shrinkString()
    {
        $content = $this->_file_content_original;
        
        $content = preg_replace('#\s+#', ' ', $content);    // Removes spaces
        
        $content = str_replace('; ' , ';' , $content);
        $content = str_replace(': ' , ':' , $content);
        $content = str_replace(' {' , '{' , $content);
        $content = str_replace('{ ' , '{' , $content);
        $content = str_replace(', ' , ',' , $content);
        $content = str_replace('} ' , '}' , $content);
        $content = str_replace(';}' , '}' , $content);
        
        $content = str_replace(array("\n", "\r", "\t"), '', $content);
        
        
        if ($this->_config['comments'])
            $content = $this->_strip_comments($content);
        
        if ($this->_config['fontweight'])
            $content = $this->_strip_fontWeight($content);
        
        if ($this->_config['zerodotvalues'])
            $content = $this->_strip_zerodotValues($content);
        
        if ($this->_config['zerounits'])
            $content = $this->_strip_zeroUnits($content);
        
        if ($this->_config['quotes'])
            $content = $this->_strip_quotes($content);
        
        if ($this->_config['hex'])
            $content = $this->_strip_hexColors($content);
        
        
        $this->_file_content_shrink = trim($content);
    }
    
    
    /**
     * Returns the name of the minimized file
     * 
     * @access   public
     * @param    none
     * @return   string
     */
    public function getMinimizedFilename()
    {
        return $this->_file_minimized;
    }
}



// -- Example
$oCSSShrinker = new CSSShrinker('style_original.css');

echo $oCSSShrinker->getMinimizedFilename();
?>

Conclusion :

Exemple complet dans le ZIP ;)

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.