Accueil > > > COMPRESSER (MINIMISER) UN FICHIER CSS
COMPRESSER (MINIMISER) UN FICHIER CSS
Information sur la source
Description
Cette classe vous permet de minimiser le contenu d'un fichier CSS afin de réduire la taille de vos fichiers.
Source
- <?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();
- ?>
<?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 ;)
Historique
- 23 août 2010 10:28:48 :
- 23-10-2010 : ajout d'un ZIP contenant un exemple d'utilisation complet
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
A propos des style CSS [ par adess00 ]
SalutBon voila j ai creer un style CSS et je voudrai savoir sai je doit remettre<link href="theme\style.css" rel="stylesheet" type="text/css"/>
Probleme de css [ par alex21 ]
Bonjour,G un petit probleme avec l'utilisation des feuilles de style. Mon site comporte une feuille de style qui definit les couleur
CSS et selecteur avec des chiffres [ par Marion0904 ]
Bonjour, J'ai fais un joli site en php avec une jolie feuille de style, je cherche maintenant à valider ma CSS.Le problème, c'est que je me
Style de menu css [ par CCJ ]
bonjour voila j'ai un petit probleme je veu que dans mon site dans une cellule d'un tableau il y ait une image et que quand je passe dessus l'image ch
Style CSS [ par CCJ ]
Bonjour je developpe actuellement un site et j'ai uun bleme voila la partie de ma source css foireuse: td.Menu { background-image: url("Images/MenuNeu
CSS paramétrable? [ par LaTatadu91 ]
Bonjour a tous, Voila je me pose une petite question pour faire évoluer mon "site" j'aimerais rendre ma feuille de style externe paramétrab
CSS et format paysage [ par sidf ]
salut à tousje commence à m'interesser aux feuilles de style (il est temps)et la ligne suivante ne fonctionne pas (la feuille de style est b
problème CSS ! [ par zut69 ]
Bonjour,Ca fait plusieurs années que je fais des sites internet, mais j'ai souvent un problème pour bien gérer les styles...Par exemple, aujourd'hui j
inclure CSS dans un plug in [ par jimdano ]
Bonjour, Je suis en train de créer un plug in, et j'aimerais inclure une feuille de style dans ce plug in, le probleme, c'est que je n'y arrive pas,
Feuille de style CSS [ par emma1006 ]
Salut !Come d'hab, j'ai un petit problème.... mais très énervant.Sur les pages web que je créé, il y a entre autres des table
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Forum
GOOGLE MAPGOOGLE MAP par fatmanajjar
Cliquez pour lire la suite par fatmanajjar
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|