Completed
Push — master ( 0cc554...fa9e93 )
by Josh
16:05
created

MinifyInlineCSS   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 1
dl 0
loc 46
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeAttribute() 0 10 2
A minify() 0 18 1
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2017 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Configurator\TemplateNormalizations;
9
10
use DOMAttr;
11
use s9e\TextFormatter\Configurator\Helpers\TemplateHelper;
12
13
class MinifyInlineCSS extends AbstractNormalization
14
{
15
	/**
16
	* {@inheritdoc}
17
	*/
18
	protected $queries = ['//*[namespace-uri() != $XSL]/@style'];
19
20
	/**
21
	* {@inheritdoc}
22
	*/
23
	protected function normalizeAttribute(DOMAttr $attribute)
24
	{
25
		$css = $attribute->nodeValue;
26
27
		// Only minify if the value does not contain any XPath expression that's not an attribute
28
		if (!preg_match('(\\{(?!@\\w+\\}))', $css))
29
		{
30
			$attribute->nodeValue = $this->minify($css);
31
		}
32
	}
33
34
	/**
35
	* Minify a CSS string
36
	*
37
	* @param  string $css Original CSS
38
	* @return string      Minified CSS
39
	*/
40
	protected function minify($css)
41
	{
42
		$css = trim($css, " \n\t;");
43
		$css = preg_replace('(\\s*([,:;])\\s*)', '$1', $css);
44
		$css = preg_replace_callback(
45
			'((?<=[\\s:])#[0-9a-f]{3,6})i',
46
			function ($m)
47
			{
48
				return strtolower($m[0]);
49
			},
50
			$css
51
		);
52
		$css = preg_replace('((?<=[\\s:])#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3)', '#$1$2$3', $css);
53
		$css = preg_replace('((?<=[\\s:])#f00\\b)', 'red', $css);
54
		$css = preg_replace('((?<=[\\s:])0px\\b)', '0', $css);
55
56
		return $css;
57
	}
58
}