1: <?php
2:
3: class CssShell extends Shell {
4:
5: 6: 7: 8: 9:
10: public function getOptionParser() {
11: $parser = parent::getOptionParser();
12: return $parser;
13: }
14:
15: public function main() {
16: $cssFile = $this->args[0];
17: $css = file_get_contents($cssFile);
18: $colors = $this->_getColorsCodes($css);
19: $vars = $this->_variables($colors);
20:
21: file_put_contents('out.css', $this->_buildCss($css, $colors, $vars));
22: file_put_contents('variables.ini', $this->_buildVariables($vars));
23: }
24:
25: private function _variables($colors) {
26: $index = 0;
27: $vars = array();
28: foreach (array_unique($colors) as $color) {
29: $vars['color' . ($index + 1)] = $color;
30: $index++;
31: }
32: return $vars;
33: }
34:
35: private function _buildVariables($vars) {
36: $b = '';
37: foreach ($vars as $name => $value) {
38: $b .= "$name=#$value\n";
39: }
40: return $b;
41: }
42:
43: private function _buildCss($css, $colors, $vars) {
44: foreach ($colors as $orig => $canonized) {
45: $var = array_search($canonized, $vars);
46: $css = preg_replace('/#' . $orig . '(?![0-9a-fA-F])/', '$' . $var, $css);
47: }
48: return $css;
49: }
50:
51: private function _getColorsCodes($css) {
52: if (preg_match_all('/#([0-9a-fA-F]{3,6})(?![0-9a-fA-F])/', $css, $colors)) {
53: $uniq = array();
54: foreach ($colors[1] as $c) {
55: $uniq[$c] = $this->_canonicalColor($c);
56: }
57: return $uniq;
58: } else {
59: return array();
60: }
61: }
62:
63: private function _canonicalColor($color) {
64: if (strlen($color) == 3) {
65: $six = '';
66: for ($k = 0; $k < strlen($color); ++$k) {
67: $six .=$color[$k] . $color[$k];
68: }
69: } else {
70: $six = $color;
71: }
72:
73: return strtolower($six);
74: }
75:
76: }