PageRenderTime 78ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/scss.inc.php

https://bitbucket.org/allanfreitas/yii-scss
PHP | 3939 lines | 3249 code | 578 blank | 112 comment | 678 complexity | affc4761530788ad048619a8b7985467 MD5 | raw file
  1. <?php
  2. class scssc {
  3. static public $VERSION = "v0.0.4";
  4. static protected $operatorNames = array(
  5. '+' => "add",
  6. '-' => "sub",
  7. '*' => "mul",
  8. '/' => "div",
  9. '%' => "mod",
  10. '==' => "eq",
  11. '!=' => "neq",
  12. '<' => "lt",
  13. '>' => "gt",
  14. '<=' => "lte",
  15. '>=' => "gte",
  16. );
  17. static protected $namespaces = array(
  18. "special" => "%",
  19. "mixin" => "@",
  20. "function" => "^",
  21. );
  22. static protected $numberPrecision = 3;
  23. static protected $unitTable = array(
  24. "in" => array(
  25. "in" => 1,
  26. "pt" => 72,
  27. "pc" => 6,
  28. "cm" => 2.54,
  29. "mm" => 25.4,
  30. "px" => 96,
  31. )
  32. );
  33. static public $true = array("keyword", "true");
  34. static public $false = array("keyword", "false");
  35. static public $defaultValue = array("keyword", "");
  36. static public $selfSelector = array("self");
  37. protected $importPaths = array("");
  38. protected $importCache = array();
  39. protected $userFunctions = array();
  40. protected $formatter = "scss_formatter_nested";
  41. function compile($code, $name=null) {
  42. $this->indentLevel = -1;
  43. $this->commentsSeen = array();
  44. $this->extends = array();
  45. $this->extendsMap = array();
  46. $locale = setlocale(LC_NUMERIC, 0);
  47. setlocale(LC_NUMERIC, "C");
  48. $this->parsedFiles = array();
  49. $this->parser = new scss_parser($name);
  50. $tree = $this->parser->parse($code);
  51. $this->formatter = new $this->formatter();
  52. $this->env = null;
  53. $this->scope = null;
  54. $this->compileRoot($tree);
  55. $this->flattenSelectors($this->scope);
  56. ob_start();
  57. $this->formatter->block($this->scope);
  58. $out = ob_get_clean();
  59. setlocale(LC_NUMERIC, $locale);
  60. return $out;
  61. }
  62. protected function pushExtends($target, $origin) {
  63. $i = count($this->extends);
  64. $this->extends[] = array($target, $origin);
  65. foreach ($target as $part) {
  66. if (isset($this->extendsMap[$part])) {
  67. $this->extendsMap[$part][] = $i;
  68. } else {
  69. $this->extendsMap[$part] = array($i);
  70. }
  71. }
  72. }
  73. protected function makeOutputBlock($type, $selectors = null) {
  74. $out = new stdClass;
  75. $out->type = $type;
  76. $out->lines = array();
  77. $out->children = array();
  78. $out->parent = $this->scope;
  79. $out->selectors = $selectors;
  80. $out->depth = $this->env->depth;
  81. return $out;
  82. }
  83. protected function matchExtendsSingle($single, &$out_origin, &$out_rem) {
  84. $counts = array();
  85. foreach ($single as $part) {
  86. if (!is_string($part)) return false; // hmm
  87. if (isset($this->extendsMap[$part])) {
  88. foreach ($this->extendsMap[$part] as $idx) {
  89. $counts[$idx] =
  90. isset($counts[$idx]) ? $counts[$idx] + 1 : 1;
  91. }
  92. }
  93. }
  94. foreach ($counts as $idx => $count) {
  95. list($target, $origin) = $this->extends[$idx];
  96. // check count
  97. if ($count != count($target)) continue;
  98. // check if target is subset of single
  99. if (array_diff(array_intersect($single, $target), $target)) continue;
  100. $out_origin = $origin;
  101. $out_rem = array_diff($single, $target);
  102. return true;
  103. }
  104. return false;
  105. }
  106. protected function combineSelectorSingle($base, $other) {
  107. $tag = null;
  108. $out = array();
  109. foreach (array($base, $other) as $single) {
  110. foreach ($single as $part) {
  111. if (preg_match('/^[^.#:]/', $part)) {
  112. $tag = $part;
  113. } else {
  114. $out[] = $part;
  115. }
  116. }
  117. }
  118. if ($tag) {
  119. array_unshift($out, $tag);
  120. }
  121. return $out;
  122. }
  123. protected function matchExtends($selector, &$out, $from = 0, $initial=true) {
  124. foreach ($selector as $i => $part) {
  125. if ($i < $from) continue;
  126. if ($this->matchExtendsSingle($part, $origin, $rem)) {
  127. $before = array_slice($selector, 0, $i);
  128. $after = array_slice($selector, $i + 1);
  129. foreach ($origin as $new) {
  130. $new[count($new) - 1] =
  131. $this->combineSelectorSingle(end($new), $rem);
  132. $k = 0;
  133. // remove shared parts
  134. if ($initial) {
  135. foreach ($before as $k => $val) {
  136. if (!isset($new[$k]) || $val != $new[$k]) {
  137. break;
  138. }
  139. }
  140. }
  141. $result = array_merge(
  142. $before,
  143. $k > 0 ? array_slice($new, $k) : $new,
  144. $after);
  145. if ($result == $selector) continue;
  146. $out[] = $result;
  147. // recursively check for more matches
  148. $this->matchExtends($result, $out, $i, false);
  149. // selector sequence merging
  150. if (!empty($before) && count($new) > 1) {
  151. $result2 = array_merge(
  152. array_slice($new, 0, -1),
  153. $k > 0 ? array_slice($before, $k) : $before,
  154. array_slice($new, -1),
  155. $after);
  156. $out[] = $result2;
  157. }
  158. }
  159. }
  160. }
  161. }
  162. protected function flattenSelectors($block, $parentKey = null) {
  163. if ($block->selectors) {
  164. $selectors = array();
  165. foreach ($block->selectors as $s) {
  166. $selectors[] = $s;
  167. if (!is_array($s)) continue;
  168. // check extends
  169. if (!empty($this->extendsMap)) {
  170. $this->matchExtends($s, $selectors);
  171. }
  172. }
  173. $block->selectors = array();
  174. $placeholderSelector = false;
  175. foreach ($selectors as $selector) {
  176. if ($this->hasSelectorPlaceholder($selector)) {
  177. $placeholderSelector = true;
  178. continue;
  179. }
  180. $block->selectors[] = $this->compileSelector($selector);
  181. }
  182. if ($placeholderSelector && 0 == count($block->selectors) && null !== $parentKey) {
  183. unset($block->parent->children[$parentKey]);
  184. return;
  185. }
  186. }
  187. foreach ($block->children as $key => $child) {
  188. $this->flattenSelectors($child, $key);
  189. }
  190. }
  191. protected function compileRoot($rootBlock) {
  192. $this->pushEnv($rootBlock);
  193. $this->scope = $this->makeOutputBlock("root");
  194. $this->compileChildren($rootBlock->children, $this->scope);
  195. $this->popEnv();
  196. }
  197. protected function compileMedia($media) {
  198. $this->pushEnv($media);
  199. $parentScope = $this->mediaParent($this->scope);
  200. $this->scope = $this->makeOutputBlock("media", array(
  201. $this->compileMediaQuery($this->multiplyMedia($this->env)))
  202. );
  203. $parentScope->children[] = $this->scope;
  204. $this->compileChildren($media->children, $this->scope);
  205. $this->scope = $this->scope->parent;
  206. $this->popEnv();
  207. }
  208. protected function mediaParent($scope) {
  209. while (!empty($scope->parent)) {
  210. if (!empty($scope->type) && $scope->type != "media") {
  211. break;
  212. }
  213. $scope = $scope->parent;
  214. }
  215. return $scope;
  216. }
  217. // TODO refactor compileNestedBlock and compileMedia into same thing
  218. protected function compileNestedBlock($block, $selectors) {
  219. $this->pushEnv($block);
  220. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  221. $this->scope->parent->children[] = $this->scope;
  222. $this->compileChildren($block->children, $this->scope);
  223. $this->scope = $this->scope->parent;
  224. $this->popEnv();
  225. }
  226. protected function compileBlock($block) {
  227. $env = $this->pushEnv($block);
  228. $env->selectors =
  229. array_map(array($this, "evalSelector"), $block->selectors);
  230. $out = $this->makeOutputBlock(null, $this->multiplySelectors($env));
  231. $this->scope->children[] = $out;
  232. $this->compileChildren($block->children, $out);
  233. $this->popEnv();
  234. }
  235. // joins together .classes and #ids
  236. protected function flattenSelectorSingle($single) {
  237. $joined = array();
  238. foreach ($single as $part) {
  239. if (empty($joined) ||
  240. !is_string($part) ||
  241. preg_match('/[.:#%]/', $part))
  242. {
  243. $joined[] = $part;
  244. continue;
  245. }
  246. if (is_array(end($joined))) {
  247. $joined[] = $part;
  248. } else {
  249. $joined[count($joined) - 1] .= $part;
  250. }
  251. }
  252. return $joined;
  253. }
  254. // replaces all the interpolates
  255. protected function evalSelector($selector) {
  256. return array_map(array($this, "evalSelectorPart"), $selector);
  257. }
  258. protected function evalSelectorPart($piece) {
  259. foreach ($piece as &$p) {
  260. if (!is_array($p)) continue;
  261. switch ($p[0]) {
  262. case "interpolate":
  263. $p = $this->compileValue($p);
  264. break;
  265. }
  266. }
  267. return $this->flattenSelectorSingle($piece);
  268. }
  269. // compiles to string
  270. // self(&) should have been replaced by now
  271. protected function compileSelector($selector) {
  272. if (!is_array($selector)) return $selector; // media and the like
  273. return implode(" ", array_map(
  274. array($this, "compileSelectorPart"), $selector));
  275. }
  276. protected function compileSelectorPart($piece) {
  277. foreach ($piece as &$p) {
  278. if (!is_array($p)) continue;
  279. switch ($p[0]) {
  280. case "self":
  281. $p = "&";
  282. break;
  283. default:
  284. $p = $this->compileValue($p);
  285. break;
  286. }
  287. }
  288. return implode($piece);
  289. }
  290. protected function hasSelectorPlaceholder($selector)
  291. {
  292. if (!is_array($selector)) return false;
  293. foreach ($selector as $parts) {
  294. foreach ($parts as $part) {
  295. if ('%' == $part[0]) {
  296. return true;
  297. }
  298. }
  299. }
  300. return false;
  301. }
  302. protected function compileChildren($stms, $out) {
  303. foreach ($stms as $stm) {
  304. $ret = $this->compileChild($stm, $out);
  305. if (!is_null($ret)) return $ret;
  306. }
  307. }
  308. protected function compileMediaQuery($queryList) {
  309. $out = "@media";
  310. $first = true;
  311. foreach ($queryList as $query){
  312. $parts = array();
  313. foreach ($query as $q) {
  314. switch ($q[0]) {
  315. case "mediaType":
  316. $parts[] = implode(" ", array_map(array($this, "compileValue"), array_slice($q, 1)));
  317. break;
  318. case "mediaExp":
  319. if (isset($q[2])) {
  320. $parts[] = "(". $this->compileValue($q[1]) . $this->formatter->assignSeparator . $this->compileValue($q[2]) . ")";
  321. } else {
  322. $parts[] = "(" . $this->compileValue($q[1]) . ")";
  323. }
  324. break;
  325. }
  326. }
  327. if (!empty($parts)) {
  328. if ($first) {
  329. $first = false;
  330. $out .= " ";
  331. } else {
  332. $out .= $this->formatter->tagSeparator;
  333. }
  334. $out .= implode(" and ", $parts);
  335. }
  336. }
  337. return $out;
  338. }
  339. // returns true if the value was something that could be imported
  340. protected function compileImport($rawPath, $out) {
  341. if ($rawPath[0] == "string") {
  342. $path = $this->compileStringContent($rawPath);
  343. if ($path = $this->findImport($path)) {
  344. $this->importFile($path, $out);
  345. return true;
  346. }
  347. return false;
  348. } if ($rawPath[0] == "list") {
  349. // handle a list of strings
  350. if (count($rawPath[2]) == 0) return false;
  351. foreach ($rawPath[2] as $path) {
  352. if ($path[0] != "string") return false;
  353. }
  354. foreach ($rawPath[2] as $path) {
  355. $this->compileImport($path, $out);
  356. }
  357. return true;
  358. }
  359. return false;
  360. }
  361. // return a value to halt execution
  362. protected function compileChild($child, $out) {
  363. switch ($child[0]) {
  364. case "import":
  365. list(,$rawPath) = $child;
  366. $rawPath = $this->reduce($rawPath);
  367. if (!$this->compileImport($rawPath, $out)) {
  368. $out->lines[] = "@import " . $this->compileValue($rawPath) . ";";
  369. }
  370. break;
  371. case "directive":
  372. list(, $directive) = $child;
  373. $s = "@" . $directive->name;
  374. if (!empty($directive->value)) {
  375. $s .= " " . $this->compileValue($directive->value);
  376. }
  377. $this->compileNestedBlock($directive, array($s));
  378. break;
  379. case "media":
  380. $this->compileMedia($child[1]);
  381. break;
  382. case "block":
  383. $this->compileBlock($child[1]);
  384. break;
  385. case "charset":
  386. $out->lines[] = "@charset ".$this->compileValue($child[1]).";";
  387. break;
  388. case "assign":
  389. list(,$name, $value) = $child;
  390. if ($name[0] == "var") {
  391. $isDefault = !empty($child[3]);
  392. if (!$isDefault || $this->get($name[1], true) === true) {
  393. $this->set($name[1], $this->reduce($value));
  394. }
  395. break;
  396. }
  397. $out->lines[] = $this->formatter->property(
  398. $this->compileValue($child[1]),
  399. $this->compileValue($child[2]));
  400. break;
  401. case "comment":
  402. $out->lines[] = $child[1];
  403. break;
  404. case "mixin":
  405. case "function":
  406. list(,$block) = $child;
  407. $this->set(self::$namespaces[$block->type] . $block->name, $block);
  408. break;
  409. case "extend":
  410. list(, $selectors) = $child;
  411. foreach ($selectors as $sel) {
  412. // only use the first one
  413. $sel = current($this->evalSelector($sel));
  414. $this->pushExtends($sel, $out->selectors);
  415. }
  416. break;
  417. case "if":
  418. list(, $if) = $child;
  419. if ($this->reduce($if->cond, true) != self::$false) {
  420. return $this->compileChildren($if->children, $out);
  421. } else {
  422. foreach ($if->cases as $case) {
  423. if ($case->type == "else" ||
  424. $case->type == "elseif" && ($this->reduce($case->cond) != self::$false))
  425. {
  426. return $this->compileChildren($case->children, $out);
  427. }
  428. }
  429. }
  430. break;
  431. case "return":
  432. return $this->reduce($child[1], true);
  433. case "each":
  434. list(,$each) = $child;
  435. $list = $this->coerceList($this->reduce($each->list));
  436. foreach ($list[2] as $item) {
  437. $this->pushEnv();
  438. $this->set($each->var, $item);
  439. // TODO: allow return from here
  440. $this->compileChildren($each->children, $out);
  441. $this->popEnv();
  442. }
  443. break;
  444. case "while":
  445. list(,$while) = $child;
  446. while ($this->reduce($while->cond, true) != self::$false) {
  447. $ret = $this->compileChildren($while->children, $out);
  448. if ($ret) return $ret;
  449. }
  450. break;
  451. case "for":
  452. list(,$for) = $child;
  453. $start = $this->reduce($for->start, true);
  454. $start = $start[1];
  455. $end = $this->reduce($for->end, true);
  456. $end = $end[1];
  457. $d = $start < $end ? 1 : -1;
  458. while (true) {
  459. if ((!$for->until && $start - $d == $end) ||
  460. ($for->until && $start == $end))
  461. {
  462. break;
  463. }
  464. $this->set($for->var, array("number", $start, ""));
  465. $start += $d;
  466. $ret = $this->compileChildren($for->children, $out);
  467. if ($ret) return $ret;
  468. }
  469. break;
  470. case "nestedprop":
  471. list(,$prop) = $child;
  472. $prefixed = array();
  473. $prefix = $this->compileValue($prop->prefix) . "-";
  474. foreach ($prop->children as $child) {
  475. if ($child[0] == "assign") {
  476. array_unshift($child[1][2], $prefix);
  477. }
  478. if ($child[0] == "nestedprop") {
  479. array_unshift($child[1]->prefix[2], $prefix);
  480. }
  481. $prefixed[] = $child;
  482. }
  483. $this->compileChildren($prefixed, $out);
  484. break;
  485. case "include": // including a mixin
  486. list(,$name, $argValues, $content) = $child;
  487. $mixin = $this->get(self::$namespaces["mixin"] . $name, false);
  488. if (!$mixin) {
  489. throw new Exception(sprintf('Undefined mixin "%s"', $name));
  490. }
  491. $callingScope = $this->env;
  492. // push scope, apply args
  493. $this->pushEnv();
  494. if ($this->env->depth > 0) {
  495. $this->env->depth--;
  496. }
  497. if (!is_null($content)) {
  498. $content->scope = $callingScope;
  499. $this->setRaw(self::$namespaces["special"] . "content", $content);
  500. }
  501. if (!is_null($mixin->args)) {
  502. $this->applyArguments($mixin->args, $argValues);
  503. }
  504. foreach ($mixin->children as $child) {
  505. $this->compileChild($child, $out);
  506. }
  507. $this->popEnv();
  508. break;
  509. case "mixin_content":
  510. $content = $this->get(self::$namespaces["special"] . "content");
  511. if (is_null($content)) {
  512. throw new Exception("Unexpected @content inside of mixin");
  513. }
  514. $this->storeEnv = $content->scope;
  515. foreach ($content->children as $child) {
  516. $this->compileChild($child, $out);
  517. }
  518. unset($this->storeEnv);
  519. break;
  520. case "debug":
  521. list(,$value, $pos) = $child;
  522. $line = $this->parser->getLineNo($pos);
  523. $value = $this->compileValue($this->reduce($value, true));
  524. fwrite(STDERR, "Line $line DEBUG: $value\n");
  525. break;
  526. default:
  527. throw new Exception("unknown child type: $child[0]");
  528. }
  529. }
  530. protected function expToString($exp) {
  531. list(, $op, $left, $right, $inParens, $whiteLeft, $whiteRight) = $exp;
  532. $content = array($left);
  533. if ($whiteLeft) $content[] = " ";
  534. $content[] = $op;
  535. if ($whiteRight) $content[] = " ";
  536. $content[] = $right;
  537. return array("string", "", $content);
  538. }
  539. // should $value cause its operand to eval
  540. protected function shouldEval($value) {
  541. switch ($value[0]) {
  542. case "exp":
  543. if ($value[1] == "/") {
  544. return $this->shouldEval($value[2], $value[3]);
  545. }
  546. case "var":
  547. case "fncall":
  548. return true;
  549. }
  550. return false;
  551. }
  552. protected function reduce($value, $inExp = false) {
  553. list($type) = $value;
  554. switch ($type) {
  555. case "exp":
  556. list(, $op, $left, $right, $inParens) = $value;
  557. $opName = isset(self::$operatorNames[$op]) ? self::$operatorNames[$op] : $op;
  558. $inExp = $inExp || $this->shouldEval($left) || $this->shouldEval($right);
  559. $left = $this->reduce($left, true);
  560. $right = $this->reduce($right, true);
  561. // only do division in special cases
  562. if ($opName == "div" && !$inParens && !$inExp) {
  563. if ($left[0] != "color" && $right[0] != "color") {
  564. return $this->expToString($value);
  565. }
  566. }
  567. $left = $this->coerceForExpression($left);
  568. $right = $this->coerceForExpression($right);
  569. $ltype = $left[0];
  570. $rtype = $right[0];
  571. // this tries:
  572. // 1. op_[op name]_[left type]_[right type]
  573. // 2. op_[left type]_[right type] (passing the op as first arg
  574. // 3. op_[op name]
  575. $fn = "op_${opName}_${ltype}_${rtype}";
  576. if (is_callable(array($this, $fn)) ||
  577. (($fn = "op_${ltype}_${rtype}") &&
  578. is_callable(array($this, $fn)) &&
  579. $passOp = true) ||
  580. (($fn = "op_${opName}") &&
  581. is_callable(array($this, $fn)) &&
  582. $genOp = true))
  583. {
  584. $unitChange = false;
  585. if (!isset($genOp) &&
  586. $left[0] == "number" && $right[0] == "number")
  587. {
  588. if ($opName == "mod" && $right[2] != "") {
  589. throw new Exception(sprintf('Cannot modulo by a number with units: %s%s.', $right[1], $right[2]));
  590. }
  591. $unitChange = true;
  592. $emptyUnit = $left[2] == "" || $right[2] == "";
  593. $targetUnit = "" != $left[2] ? $left[2] : $right[2];
  594. if ($opName != "mul") {
  595. $left[2] = "" != $left[2] ? $left[2] : $targetUnit;
  596. $right[2] = "" != $right[2] ? $right[2] : $targetUnit;
  597. }
  598. if ($opName != "mod") {
  599. $left = $this->normalizeNumber($left);
  600. $right = $this->normalizeNumber($right);
  601. }
  602. if ($opName == "div" && !$emptyUnit && $left[2] == $right[2]) {
  603. $targetUnit = "";
  604. }
  605. if ($opName == "mul") {
  606. $left[2] = "" != $left[2] ? $left[2] : $right[2];
  607. $right[2] = "" != $right[2] ? $right[2] : $left[2];
  608. } elseif ($opName == "div" && $left[2] == $right[2]) {
  609. $left[2] = "";
  610. $right[2] = "";
  611. }
  612. }
  613. $shouldEval = $inParens || $inExp;
  614. if (isset($passOp)) {
  615. $out = $this->$fn($op, $left, $right, $shouldEval);
  616. } else {
  617. $out = $this->$fn($left, $right, $shouldEval);
  618. }
  619. if (!is_null($out)) {
  620. if ($unitChange && $out[0] == "number") {
  621. $out = $this->coerceUnit($out, $targetUnit);
  622. }
  623. return $out;
  624. }
  625. }
  626. return $this->expToString($value);
  627. case "unary":
  628. list(, $op, $exp, $inParens) = $value;
  629. $inExp = $inExp || $this->shouldEval($exp);
  630. $exp = $this->reduce($exp);
  631. if ($exp[0] == "number") {
  632. switch ($op) {
  633. case "+":
  634. return $exp;
  635. case "-":
  636. $exp[1] *= -1;
  637. return $exp;
  638. }
  639. }
  640. if ($op == "not") {
  641. if ($inExp || $inParens) {
  642. if ($exp == self::$false) {
  643. return self::$true;
  644. } else {
  645. return self::$false;
  646. }
  647. } else {
  648. $op = $op . " ";
  649. }
  650. }
  651. return array("string", "", array($op, $exp));
  652. case "var":
  653. list(, $name) = $value;
  654. return $this->reduce($this->get($name));
  655. case "list":
  656. foreach ($value[2] as &$item) {
  657. $item = $this->reduce($item);
  658. }
  659. return $value;
  660. case "string":
  661. foreach ($value[2] as &$item) {
  662. if (is_array($item)) {
  663. $item = $this->reduce($item);
  664. }
  665. }
  666. return $value;
  667. case "interpolate":
  668. $value[1] = $this->reduce($value[1]);
  669. return $value;
  670. case "fncall":
  671. list(,$name, $argValues) = $value;
  672. // user defined function?
  673. $func = $this->get(self::$namespaces["function"] . $name, false);
  674. if ($func) {
  675. $this->pushEnv();
  676. // set the args
  677. if (isset($func->args)) {
  678. $this->applyArguments($func->args, $argValues);
  679. }
  680. // throw away lines and children
  681. $tmp = (object)array(
  682. "lines" => array(),
  683. "children" => array()
  684. );
  685. $ret = $this->compileChildren($func->children, $tmp);
  686. $this->popEnv();
  687. return is_null($ret) ? self::$defaultValue : $ret;
  688. }
  689. // built in function
  690. if ($this->callBuiltin($name, $argValues, $returnValue)) {
  691. return $returnValue;
  692. }
  693. // need to flatten the arguments into a list
  694. $listArgs = array();
  695. foreach ((array)$argValues as $arg) {
  696. if (empty($arg[0])) {
  697. $listArgs[] = $this->reduce($arg[1]);
  698. }
  699. }
  700. return array("function", $name, array("list", ",", $listArgs));
  701. default:
  702. return $value;
  703. }
  704. }
  705. public function normalizeValue($value) {
  706. $value = $this->coerceForExpression($this->reduce($value));
  707. list($type) = $value;
  708. switch ($type) {
  709. case "list":
  710. $value = $this->extractInterpolation($value);
  711. if ($value[0] != "list") {
  712. return array("keyword", $this->compileValue($value));
  713. }
  714. foreach ($value[2] as $key => $item) {
  715. $value[2][$key] = $this->normalizeValue($item);
  716. }
  717. return $value;
  718. case "number":
  719. return $this->normalizeNumber($value);
  720. default:
  721. return $value;
  722. }
  723. }
  724. // just does physical lengths for now
  725. protected function normalizeNumber($number) {
  726. list(, $value, $unit) = $number;
  727. if (isset(self::$unitTable["in"][$unit])) {
  728. $conv = self::$unitTable["in"][$unit];
  729. return array("number", $value / $conv, "in");
  730. }
  731. return $number;
  732. }
  733. // $number should be normalized
  734. protected function coerceUnit($number, $unit) {
  735. list(, $value, $baseUnit) = $number;
  736. if (isset(self::$unitTable[$baseUnit][$unit])) {
  737. $value = $value * self::$unitTable[$baseUnit][$unit];
  738. }
  739. return array("number", $value, $unit);
  740. }
  741. protected function op_add_number_number($left, $right) {
  742. return array("number", $left[1] + $right[1], $left[2]);
  743. }
  744. protected function op_mul_number_number($left, $right) {
  745. return array("number", $left[1] * $right[1], $left[2]);
  746. }
  747. protected function op_sub_number_number($left, $right) {
  748. return array("number", $left[1] - $right[1], $left[2]);
  749. }
  750. protected function op_div_number_number($left, $right) {
  751. return array("number", $left[1] / $right[1], $left[2]);
  752. }
  753. protected function op_mod_number_number($left, $right) {
  754. return array("number", $left[1] % $right[1], $left[2]);
  755. }
  756. // adding strings
  757. protected function op_add($left, $right) {
  758. if ($strLeft = $this->coerceString($left)) {
  759. if ($right[0] == "string") {
  760. $right[1] = "";
  761. }
  762. $strLeft[2][] = $right;
  763. return $strLeft;
  764. }
  765. if ($strRight = $this->coerceString($right)) {
  766. if ($left[0] == "string") {
  767. $left[1] = "";
  768. }
  769. array_unshift($strRight[2], $left);
  770. return $strRight;
  771. }
  772. }
  773. protected function op_and($left, $right, $shouldEval) {
  774. if (!$shouldEval) return;
  775. if ($left != self::$false) return $right;
  776. return $left;
  777. }
  778. protected function op_or($left, $right, $shouldEval) {
  779. if (!$shouldEval) return;
  780. if ($left != self::$false) return $left;
  781. return $right;
  782. }
  783. protected function op_color_color($op, $left, $right) {
  784. $out = array('color');
  785. foreach (range(1, 3) as $i) {
  786. $lval = isset($left[$i]) ? $left[$i] : 0;
  787. $rval = isset($right[$i]) ? $right[$i] : 0;
  788. switch ($op) {
  789. case '+':
  790. $out[] = $lval + $rval;
  791. break;
  792. case '-':
  793. $out[] = $lval - $rval;
  794. break;
  795. case '*':
  796. $out[] = $lval * $rval;
  797. break;
  798. case '%':
  799. $out[] = $lval % $rval;
  800. break;
  801. case '/':
  802. if ($rval == 0) {
  803. throw new Exception("color: Can't divide by zero");
  804. }
  805. $out[] = $lval / $rval;
  806. break;
  807. default:
  808. throw new Exception("color: unknow op $op");
  809. }
  810. }
  811. if (isset($left[4])) $out[4] = $left[4];
  812. elseif (isset($right[4])) $out[4] = $right[4];
  813. return $this->fixColor($out);
  814. }
  815. protected function op_color_number($op, $left, $right) {
  816. $value = $right[1];
  817. return $this->op_color_color($op, $left,
  818. array("color", $value, $value, $value));
  819. }
  820. protected function op_number_color($op, $left, $right) {
  821. $value = $left[1];
  822. return $this->op_color_color($op,
  823. array("color", $value, $value, $value), $right);
  824. }
  825. protected function op_eq($left, $right) {
  826. if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
  827. $lStr[1] = "";
  828. $rStr[1] = "";
  829. return $this->toBool($this->compileValue($lStr) == $this->compileValue($rStr));
  830. }
  831. return $this->toBool($left == $right);
  832. }
  833. protected function op_neq($left, $right) {
  834. return $this->toBool($left != $right);
  835. }
  836. protected function op_gte_number_number($left, $right) {
  837. return $this->toBool($left[1] >= $right[1]);
  838. }
  839. protected function op_gt_number_number($left, $right) {
  840. return $this->toBool($left[1] > $right[1]);
  841. }
  842. protected function op_lte_number_number($left, $right) {
  843. return $this->toBool($left[1] <= $right[1]);
  844. }
  845. protected function op_lt_number_number($left, $right) {
  846. return $this->toBool($left[1] < $right[1]);
  847. }
  848. protected function toBool($thing) {
  849. return $thing ? self::$true : self::$false;
  850. }
  851. protected function compileValue($value) {
  852. $value = $this->reduce($value);
  853. list($type) = $value;
  854. switch ($type) {
  855. case "keyword":
  856. return $value[1];
  857. case "color":
  858. // [1] - red component (either number for a %)
  859. // [2] - green component
  860. // [3] - blue component
  861. // [4] - optional alpha component
  862. list(, $r, $g, $b) = $value;
  863. $r = round($r);
  864. $g = round($g);
  865. $b = round($b);
  866. if (count($value) == 5 && $value[4] != 1) { // rgba
  867. return 'rgba('.$r.', '.$g.', '.$b.', '.$value[4].')';
  868. }
  869. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  870. // Converting hex color to short notation (e.g. #003399 to #039)
  871. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  872. $h = '#' . $h[1] . $h[3] . $h[5];
  873. }
  874. return $h;
  875. case "number":
  876. return round($value[1], self::$numberPrecision) . $value[2];
  877. case "string":
  878. return $value[1] . $this->compileStringContent($value) . $value[1];
  879. case "function":
  880. $args = !empty($value[2]) ? $this->compileValue($value[2]) : "";
  881. return "$value[1]($args)";
  882. case "list":
  883. $value = $this->extractInterpolation($value);
  884. if ($value[0] != "list") return $this->compileValue($value);
  885. list(, $delim, $items) = $value;
  886. foreach ($items as &$item) {
  887. $item = $this->compileValue($item);
  888. }
  889. return implode("$delim ", $items);
  890. case "interpolated": # node created by extractInterpolation
  891. list(, $interpolate, $left, $right) = $value;
  892. list(,, $whiteLeft, $whiteRight) = $interpolate;
  893. $left = count($left[2]) > 0 ?
  894. $this->compileValue($left).$whiteLeft : "";
  895. $right = count($right[2]) > 0 ?
  896. $whiteRight.$this->compileValue($right) : "";
  897. return $left.$this->compileValue($interpolate).$right;
  898. case "interpolate": # raw parse node
  899. list(, $exp) = $value;
  900. // strip quotes if it's a string
  901. $reduced = $this->reduce($exp);
  902. if ($reduced[0] == "string") {
  903. $reduced = array("keyword",
  904. $this->compileStringContent($reduced));
  905. }
  906. return $this->compileValue($reduced);
  907. default:
  908. throw new Exception("unknown value type: $type");
  909. }
  910. }
  911. protected function compileStringContent($string) {
  912. $parts = array();
  913. foreach ($string[2] as $part) {
  914. if (is_array($part)) {
  915. $parts[] = $this->compileValue($part);
  916. } else {
  917. $parts[] = $part;
  918. }
  919. }
  920. return implode($parts);
  921. }
  922. // doesn't need to be recursive, compileValue will handle that
  923. protected function extractInterpolation($list) {
  924. $items = $list[2];
  925. foreach ($items as $i => $item) {
  926. if ($item[0] == "interpolate") {
  927. $before = array("list", $list[1], array_slice($items, 0, $i));
  928. $after = array("list", $list[1], array_slice($items, $i + 1));
  929. return array("interpolated", $item, $before, $after);
  930. }
  931. }
  932. return $list;
  933. }
  934. // find the final set of selectors
  935. protected function multiplySelectors($env) {
  936. $envs = array();
  937. while (null !== $env) {
  938. if (!empty($env->selectors)) {
  939. $envs[] = $env;
  940. }
  941. $env = $env->parent;
  942. };
  943. $selectors = array();
  944. $parentSelectors = array(array());
  945. while ($env = array_pop($envs)) {
  946. $selectors = array();
  947. foreach ($env->selectors as $selector) {
  948. foreach ($parentSelectors as $parent) {
  949. $selectors[] = $this->joinSelectors($parent, $selector);
  950. }
  951. }
  952. $parentSelectors = $selectors;
  953. }
  954. return $selectors;
  955. }
  956. // looks for & to replace, or append parent before child
  957. protected function joinSelectors($parent, $child) {
  958. $setSelf = false;
  959. $out = array();
  960. foreach ($child as $part) {
  961. $newPart = array();
  962. foreach ($part as $p) {
  963. if ($p == self::$selfSelector) {
  964. $setSelf = true;
  965. foreach ($parent as $i => $parentPart) {
  966. if ($i > 0) {
  967. $out[] = $newPart;
  968. $newPart = array();
  969. }
  970. foreach ($parentPart as $pp) {
  971. $newPart[] = $pp;
  972. }
  973. }
  974. } else {
  975. $newPart[] = $p;
  976. }
  977. }
  978. $out[] = $newPart;
  979. }
  980. return $setSelf ? $out : array_merge($parent, $child);
  981. }
  982. protected function multiplyMedia($env, $childQueries = null) {
  983. if (is_null($env) ||
  984. !empty($env->block->type) && $env->block->type != "media")
  985. {
  986. return $childQueries;
  987. }
  988. // plain old block, skip
  989. if (empty($env->block->type)) {
  990. return $this->multiplyMedia($env->parent, $childQueries);
  991. }
  992. $parentQueries = $env->block->queryList;
  993. if ($childQueries == null) {
  994. $childQueries = $parentQueries;
  995. } else {
  996. $originalQueries = $childQueries;
  997. $childQueries = array();
  998. foreach ($parentQueries as $parentQuery){
  999. foreach ($originalQueries as $childQuery) {
  1000. $childQueries []= array_merge($parentQuery, $childQuery);
  1001. }
  1002. }
  1003. }
  1004. return $this->multiplyMedia($env->parent, $childQueries);
  1005. }
  1006. // convert something to list
  1007. protected function coerceList($item, $delim = ",") {
  1008. if (!is_null($item) && $item[0] == "list") {
  1009. return $item;
  1010. }
  1011. return array("list", $delim, is_null($item) ? array(): array($item));
  1012. }
  1013. protected function applyArguments($argDef, $argValues) {
  1014. $args = array();
  1015. foreach ($argDef as $i => $arg) {
  1016. list($name, $default, $isVariable) = $argDef[$i];
  1017. $args[$name] = array($i, $name, $default, $isVariable);
  1018. }
  1019. $keywordArgs = array();
  1020. $remaining = array();
  1021. // assign the keyword args
  1022. foreach ((array) $argValues as $arg) {
  1023. if (!empty($arg[0])) {
  1024. if (!isset($args[$arg[0][1]])) {
  1025. throw new Exception(sprintf('Mixin or function doesn\'t have an argument named $%s.', $arg[0][1]));
  1026. } elseif ($args[$arg[0][1]][0] < count($remaining)) {
  1027. throw new Exception(sprintf('The argument $%s was passed both by position and by name.', $arg[0][1]));
  1028. }
  1029. $keywordArgs[$arg[0][1]] = $arg[1];
  1030. } elseif (count($keywordArgs)) {
  1031. throw new Exception('Positional arguments must come before keyword arguments.');
  1032. } elseif ($arg[2] == true) {
  1033. $val = $this->reduce($arg[1], true);
  1034. if ($val[0] == "list") {
  1035. foreach ($val[2] as $item) {
  1036. $remaining[] = $item;
  1037. }
  1038. } else {
  1039. $remaining[] = $val;
  1040. }
  1041. } else {
  1042. $remaining[] = $arg[1];
  1043. }
  1044. }
  1045. foreach ($args as $arg) {
  1046. list($i, $name, $default, $isVariable) = $arg;
  1047. if ($isVariable) {
  1048. $val = array("list", ",", array());
  1049. for ($count = count($remaining); $i < $count; $i++) {
  1050. $val[2][] = $remaining[$i];
  1051. }
  1052. } elseif (isset($remaining[$i])) {
  1053. $val = $remaining[$i];
  1054. } elseif (isset($keywordArgs[$name])) {
  1055. $val = $keywordArgs[$name];
  1056. } elseif (!empty($default)) {
  1057. $val = $default;
  1058. } else {
  1059. throw new Exception(sprintf('There is missing argument $%s', $name));
  1060. }
  1061. $this->set($name, $this->reduce($val, true), true);
  1062. }
  1063. }
  1064. protected function pushEnv($block=null) {
  1065. $env = new stdClass;
  1066. $env->parent = $this->env;
  1067. $env->store = array();
  1068. $env->block = $block;
  1069. $env->depth = isset($this->env->depth) ? $this->env->depth + 1 : 0;
  1070. $this->env = $env;
  1071. return $env;
  1072. }
  1073. protected function normalizeName($name) {
  1074. return str_replace("-", "_", $name);
  1075. }
  1076. protected function getStoreEnv() {
  1077. return isset($this->storeEnv) ? $this->storeEnv : $this->env;
  1078. }
  1079. protected function set($name, $value, $shadow=false) {
  1080. $name = $this->normalizeName($name);
  1081. if ($shadow) {
  1082. $this->setRaw($name, $value);
  1083. } else {
  1084. $this->setExisting($name, $value);
  1085. }
  1086. }
  1087. // todo: this is bugged?
  1088. protected function setExisting($name, $value, $env = null) {
  1089. if (is_null($env)) $env = $this->getStoreEnv();
  1090. if (isset($env->store[$name])) {
  1091. $env->store[$name] = $value;
  1092. } elseif (!is_null($env->parent)) {
  1093. $this->setExisting($name, $value, $env->parent);
  1094. } else {
  1095. $this->env->store[$name] = $value;
  1096. }
  1097. }
  1098. protected function setRaw($name, $value) {
  1099. $this->env->store[$name] = $value;
  1100. }
  1101. protected function get($name, $defaultValue = null, $env = null) {
  1102. $name = $this->normalizeName($name);
  1103. if (is_null($env)) $env = $this->getStoreEnv();
  1104. if (is_null($defaultValue)) $defaultValue = self::$defaultValue;
  1105. if (isset($env->store[$name])) {
  1106. return $env->store[$name];
  1107. } elseif (!is_null($env->parent)) {
  1108. return $this->get($name, $defaultValue, $env->parent);
  1109. }
  1110. return $defaultValue; // found nothing
  1111. }
  1112. protected function popEnv() {
  1113. $env = $this->env;
  1114. $this->env = $this->env->parent;
  1115. return $env;
  1116. }
  1117. public function getParsedFiles() {
  1118. return $this->parsedFiles;
  1119. }
  1120. public function addImportPath($path) {
  1121. $this->importPaths[] = $path;
  1122. }
  1123. public function setImportPaths($path) {
  1124. $this->importPaths = (array)$path;
  1125. }
  1126. public function setFormatter($formatterName) {
  1127. $this->formatter = $formatterName;
  1128. }
  1129. public function registerFunction($name, $func) {
  1130. $this->userFunctions[$this->normalizeName($name)] = $func;
  1131. }
  1132. public function unregisterFunction($name) {
  1133. unset($this->userFunctions[$this->normalizeName($name)]);
  1134. }
  1135. protected function importFile($path, $out) {
  1136. // see if tree is cached
  1137. $realPath = realpath($path);
  1138. if (isset($this->importCache[$realPath])) {
  1139. $tree = $this->importCache[$realPath];
  1140. } else {
  1141. $code = file_get_contents($path);
  1142. $parser = new scss_parser($path);
  1143. $tree = $parser->parse($code);
  1144. $this->parsedFiles[] = $path;
  1145. $this->importCache[$realPath] = $tree;
  1146. }
  1147. $pi = pathinfo($path);
  1148. array_unshift($this->importPaths, $pi['dirname']);
  1149. $this->compileChildren($tree->children, $out);
  1150. array_shift($this->importPaths);
  1151. }
  1152. // results the file path for an import url if it exists
  1153. protected function findImport($url) {
  1154. $urls = array();
  1155. // for "normal" scss imports (ignore vanilla css and external requests)
  1156. if (!preg_match('/\.css|^http:\/\/$/', $url)) {
  1157. // try both normal and the _partial filename
  1158. $urls = array($url, preg_replace('/[^\/]+$/', '_\0', $url));
  1159. }
  1160. foreach ($this->importPaths as $dir) {
  1161. if (is_string($dir)) {
  1162. // check urls for normal import paths
  1163. foreach ($urls as $full) {
  1164. $full = $dir .
  1165. (!empty($dir) && substr($dir, -1) != '/' ? '/' : '') .
  1166. $full;
  1167. if ($this->fileExists($file = $full.'.scss') ||
  1168. $this->fileExists($file = $full))
  1169. {
  1170. return $file;
  1171. }
  1172. }
  1173. } else {
  1174. // check custom callback for import path
  1175. $file = call_user_func($dir,$url,$this);
  1176. if ($file !== null) {
  1177. return $file;
  1178. }
  1179. }
  1180. }
  1181. return null;
  1182. }
  1183. protected function fileExists($name) {
  1184. return is_file($name);
  1185. }
  1186. protected function callBuiltin($name, $args, &$returnValue) {
  1187. // try a lib function
  1188. $name = $this->normalizeName($name);
  1189. $libName = "lib_".$name;
  1190. $f = array($this, $libName);
  1191. $prototype = isset(self::$$libName) ? self::$$libName : null;
  1192. if (is_callable($f)) {
  1193. $sorted = $this->sortArgs($prototype, $args);
  1194. foreach ($sorted as &$val) {
  1195. $val = $this->reduce($val, true);
  1196. }
  1197. $returnValue = call_user_func($f, $sorted, $this);
  1198. } else if (isset($this->userFunctions[$name])) {
  1199. // see if we can find a user function
  1200. $fn = $this->userFunctions[$name];
  1201. foreach ($args as &$val) {
  1202. $val = $this->reduce($val[1], true);
  1203. }
  1204. $returnValue = call_user_func($fn, $args, $this);
  1205. }
  1206. if (isset($returnValue)) {
  1207. // coerce a php value into a scss one
  1208. if (is_numeric($returnValue)) {
  1209. $returnValue = array('number', $returnValue, "");
  1210. } elseif (is_bool($returnValue)) {
  1211. $returnValue = $returnValue ? self::$true : self::$false;
  1212. } elseif (!is_array($returnValue)) {
  1213. $returnValue = array('keyword', $returnValue);
  1214. }
  1215. return true;
  1216. }
  1217. return false;
  1218. }
  1219. // sorts any keyword arguments
  1220. // TODO: merge with apply arguments
  1221. protected function sortArgs($prototype, $args) {
  1222. $keyArgs = array();
  1223. $posArgs = array();
  1224. foreach ($args as $arg) {
  1225. list($key, $value) = $arg;
  1226. $key = $key[1];
  1227. if (empty($key)) {
  1228. $posArgs[] = $value;
  1229. } else {
  1230. $keyArgs[$key] = $value;
  1231. }
  1232. }
  1233. if (is_null($prototype)) return $posArgs;
  1234. $finalArgs = array();
  1235. foreach ($prototype as $i => $names) {
  1236. if (isset($posArgs[$i])) {
  1237. $finalArgs[] = $posArgs[$i];
  1238. continue;
  1239. }
  1240. $set = false;
  1241. foreach ((array)$names as $name) {
  1242. if (isset($keyArgs[$name])) {
  1243. $finalArgs[] = $keyArgs[$name];
  1244. $set = true;
  1245. break;
  1246. }
  1247. }
  1248. if (!$set) {
  1249. $finalArgs[] = null;
  1250. }
  1251. }
  1252. return $finalArgs;
  1253. }
  1254. protected function coerceForExpression($value) {
  1255. if ($color = $this->coerceColor($value)) {
  1256. return $color;
  1257. }
  1258. return $value;
  1259. }
  1260. protected function coerceColor($value) {
  1261. switch ($value[0]) {
  1262. case "color": return $value;
  1263. case "keyword":
  1264. $name = $value[1];
  1265. if (isset(self::$cssColors[$name])) {
  1266. list($r, $g, $b) = explode(',', self::$cssColors[$name]);
  1267. return array('color', (int) $r, (int) $g, (int) $b);
  1268. }
  1269. return null;
  1270. }
  1271. return null;
  1272. }
  1273. protected function coerceString($value) {
  1274. switch ($value[0]) {
  1275. case "string":
  1276. return $value;
  1277. case "keyword":
  1278. return array("string", "", array($value[1]));
  1279. }
  1280. return null;
  1281. }
  1282. protected function assertList($value) {
  1283. if ($value[0] != "list")
  1284. throw new exception("expecting list");
  1285. return $value;
  1286. }
  1287. protected function assertColor($value) {
  1288. if ($color = $this->coerceColor($value)) return $color;
  1289. throw new Exception("expecting color");
  1290. }
  1291. protected function assertNumber($value) {
  1292. if ($value[0] != "number")
  1293. throw new Exception("expecting number");
  1294. return $value[1];
  1295. }
  1296. protected function coercePercent($value) {
  1297. if ($value[0] == "number") {
  1298. if ($value[2] == "%") {
  1299. return $value[1] / 100;
  1300. }
  1301. return $value[1];
  1302. }
  1303. return 0;
  1304. }
  1305. // make sure a color's components don't go out of bounds
  1306. protected function fixColor($c) {
  1307. foreach (range(1, 3) as $i) {
  1308. if ($c[$i] < 0) $c[$i] = 0;
  1309. if ($c[$i] > 255) $c[$i] = 255;
  1310. }
  1311. return $c;
  1312. }
  1313. function toHSL($r, $g, $b) {
  1314. $r = $r / 255;
  1315. $g = $g / 255;
  1316. $b = $b / 255;
  1317. $min = min($r, $g, $b);
  1318. $max = max($r, $g, $b);
  1319. $L = ($min + $max) / 2;
  1320. if ($min == $max) {
  1321. $S = $H = 0;
  1322. } else {
  1323. if ($L < 0.5)
  1324. $S = ($max - $min)/($max + $min);
  1325. else
  1326. $S = ($max - $min)/(2.0 - $max - $min);
  1327. if ($r == $max) $H = ($g - $b)/($max - $min);
  1328. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  1329. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  1330. }
  1331. return array('hsl',
  1332. ($H < 0 ? $H + 6 : $H)*60,
  1333. $S*100,
  1334. $L*100,
  1335. );
  1336. }
  1337. function toRGB_helper($comp, $temp1, $temp2) {
  1338. if ($comp < 0) $comp += 1.0;
  1339. elseif ($comp > 1) $comp -= 1.0;
  1340. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  1341. if (2 * $comp < 1) return $temp2;
  1342. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  1343. return $temp1;
  1344. }
  1345. // H from 0 to 360, S and L from 0 to 100
  1346. function toRGB($H, $S, $L) {
  1347. $H = $H % 360;
  1348. if ($H < 0) $H += 360;
  1349. $S = min(100, max(0, $S));
  1350. $L = min(100, max(0, $L));
  1351. $H = $H / 360;
  1352. $S = $S / 100;
  1353. $L = $L / 100;
  1354. if ($S == 0) {
  1355. $r = $g = $b = $L;
  1356. } else {
  1357. $temp2 = $L < 0.5 ?
  1358. $L*(1.0 + $S) :
  1359. $L + $S - $L * $S;
  1360. $temp1 = 2.0 * $L - $temp2;
  1361. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  1362. $g = $this->toRGB_helper($H, $temp1, $temp2);
  1363. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  1364. }
  1365. $out = array('color', $r*255, $g*255, $b*255);
  1366. return $out;
  1367. }
  1368. // Built in functions
  1369. protected static $lib_if = array("condition", "if-true", "if-false");
  1370. protected function lib_if($args) {
  1371. list($cond,$t, $f) = $args;
  1372. if ($cond == self::$false) return $f;
  1373. return $t;
  1374. }
  1375. protected static $lib_index = array("list", "value");
  1376. protected function lib_index($args) {
  1377. list($list, $value) = $args;
  1378. $list = $this->assertList($list);
  1379. $values = array();
  1380. foreach ($list[2] as $item) {
  1381. $values[] = $this->normalizeValue($item);
  1382. }
  1383. $key = array_search($this->normalizeValue($value), $values);
  1384. return false === $key ? false : $key + 1;
  1385. }
  1386. protected static $lib_rgb = array("red", "green", "blue");
  1387. protected function lib_rgb($args) {
  1388. list($r,$g,$b) = $args;
  1389. return array("color", $r[1], $g[1], $b[1]);
  1390. }
  1391. protected static $lib_rgba = array(
  1392. array("red", "color"),
  1393. "green", "blue", "alpha");
  1394. protected function lib_rgba($args) {
  1395. if ($color = $this->coerceColor($args[0])) {
  1396. $num = is_null($args[1]) ? $args[3] : $args[1];
  1397. $alpha = $this->assertNumber($num);
  1398. $color[4] = $alpha;
  1399. return $color;
  1400. }
  1401. list($r,$g,$b, $a) = $args;
  1402. return array("color", $r[1], $g[1], $b[1], $a[1]);
  1403. }
  1404. // helper function for adjust_color, change_color, and scale_color
  1405. protected function alter_color($args, $fn) {
  1406. $color = $this->assertColor($args[0]);
  1407. foreach (array(1,2,3,7) as $i) {
  1408. if (!is_null($args[$i])) {
  1409. $val = $this->assertNumber($args[$i]);
  1410. $ii = $i == 7 ? 4 : $i; // alpha
  1411. $color[$ii] =
  1412. $this->$fn(isset($color[$ii]) ? $color[$ii] : 0, $val, $i);
  1413. }
  1414. }
  1415. if (!is_null($args[4]) || !is_null($args[5]) || !is_null($args[6])) {
  1416. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1417. foreach (array(4,5,6) as $i) {
  1418. if (!is_null($args[$i])) {
  1419. $val = $this->assertNumber($args[$i]);
  1420. $hsl[$i - 3] = $this->$fn($hsl[$i - 3], $val, $i);
  1421. }
  1422. }
  1423. $rgb = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  1424. if (isset($color[4])) $rgb[4] = $color[4];
  1425. $color = $rgb;
  1426. }
  1427. return $color;
  1428. }
  1429. protected static $lib_adjust_color = array(
  1430. "color", "red", "green", "blue",
  1431. "hue", "saturation", "lightness", "alpha"
  1432. );
  1433. protected function adjust_color_helper($base, $alter, $i) {
  1434. return $base += $alter;
  1435. }
  1436. protected function lib_adjust_color($args) {
  1437. return $this->alter_color($args, "adjust_color_helper");
  1438. }
  1439. protected static $lib_change_color = array(
  1440. "color", "red", "green", "blue",
  1441. "hue", "saturation", "lightness", "alpha"
  1442. );
  1443. protected function change_color_helper($base, $alter, $i) {
  1444. return $alter;
  1445. }
  1446. protected function lib_change_color($args) {
  1447. return $this->alter_color($args, "change_color_helper");
  1448. }
  1449. protected static $lib_scale_color = array(
  1450. "color", "red", "green", "blue",
  1451. "hue", "saturation", "lightness", "alpha"
  1452. );
  1453. protected function scale_color_helper($base, $scale, $i) {
  1454. // 1,2,3 - rgb
  1455. // 4, 5, 6 - hsl
  1456. // 7 - a
  1457. switch ($i) {
  1458. case 1:
  1459. case 2:
  1460. case 3:
  1461. $max = 255; break;
  1462. case 4:
  1463. $max = 360; break;
  1464. case 7:
  1465. $max = 1; break;
  1466. default:
  1467. $max = 100;
  1468. }
  1469. $scale = $scale / 100;
  1470. if ($scale < 0) {
  1471. return $base * $scale + $base;
  1472. } else {
  1473. return ($max - $base) * $scale + $base;
  1474. }
  1475. }
  1476. protected function lib_scale_color($args) {
  1477. return $this->alter_color($args, "scale_color_helper");
  1478. }
  1479. protected static $lib_ie_hex_str = array("color");
  1480. protected function lib_ie_hex_str($args) {
  1481. $color = $this->coerceColor($args[0]);
  1482. $color[4] = isset($color[4]) ? round(255*$color[4]) : 255;
  1483. return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]);
  1484. }
  1485. protected static $lib_red = array("color");
  1486. protected function lib_red($args) {
  1487. list($color) = $args;
  1488. return $color[1];
  1489. }
  1490. protected static $lib_green = array("color");
  1491. protected function lib_green($args) {
  1492. list($color) = $args;
  1493. return $color[2];
  1494. }
  1495. protected static $lib_blue = array("color");
  1496. protected function lib_blue($args) {
  1497. list($color) = $args;
  1498. return $color[3];
  1499. }
  1500. protected static $lib_alpha = array("color");
  1501. protected function lib_alpha($args) {
  1502. if ($color = $this->coerceColor($args[0])) {
  1503. return isset($color[4]) ? $color[4] : 1;
  1504. }
  1505. // this might be the IE function, so return value unchanged
  1506. return array("function", "alpha", array("list", ",", $args));
  1507. }
  1508. protected static $lib_opacity = array("color");
  1509. protected function lib_opacity($args) {
  1510. return $this->lib_alpha($args);
  1511. }
  1512. // mix two colors
  1513. protected static $lib_mix = array("color-1", "color-2", "weight");
  1514. protected function lib_mix($args) {
  1515. list($first, $second, $weight) = $args;
  1516. $first = $this->assertColor($first);
  1517. $second = $this->assertColor($second);
  1518. if (is_null($weight)) {
  1519. $weight = 0.5;
  1520. } else {
  1521. $weight = $this->coercePercent($weight);
  1522. }
  1523. $first_a = isset($first[4]) ? $first[4] : 1;
  1524. $second_a = isset($second[4]) ? $second[4] : 1;
  1525. $w = $weight * 2 - 1;
  1526. $a = $first_a - $second_a;
  1527. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  1528. $w2 = 1.0 - $w1;
  1529. $new = array('color',
  1530. $w1 * $first[1] + $w2 * $second[1],
  1531. $w1 * $first[2] + $w2 * $second[2],
  1532. $w1 * $first[3] + $w2 * $second[3],
  1533. );
  1534. if ($first_a != 1.0 || $second_a != 1.0) {
  1535. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  1536. }
  1537. return $this->fixColor($new);
  1538. }
  1539. protected static $lib_hsl = array("hue", "saturation", "lightness");
  1540. protected function lib_hsl($args) {
  1541. list($h, $s, $l) = $args;
  1542. return $this->toRGB($h[1], $s[1], $l[1]);
  1543. }
  1544. protected static $lib_hsla = array("hue", "saturation",
  1545. "lightness", "alpha");
  1546. protected function lib_hsla($args) {
  1547. list($h, $s, $l, $a) = $args;
  1548. $color = $this->toRGB($h[1], $s[1], $l[1]);
  1549. $color[4] = $a[1];
  1550. return $color;
  1551. }
  1552. protected static $lib_hue = array("color");
  1553. protected function lib_hue($args) {
  1554. $color = $this->assertColor($args[0]);
  1555. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1556. return array("number", $hsl[1], "deg");
  1557. }
  1558. protected static $lib_saturation = array("color");
  1559. protected function lib_saturation($args) {
  1560. $color = $this->assertColor($args[0]);
  1561. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1562. return array("number", $hsl[2], "%");
  1563. }
  1564. protected static $lib_lightness = array("color");
  1565. protected function lib_lightness($args) {
  1566. $color = $this->assertColor($args[0]);
  1567. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1568. return array("number", $hsl[3], "%");
  1569. }
  1570. protected function adjustHsl($color, $idx, $amount) {
  1571. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1572. $hsl[$idx] += $amount;
  1573. $out = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  1574. if (isset($color[4])) $out[4] = $color[4];
  1575. return $out;
  1576. }
  1577. protected static $lib_adjust_hue = array("color", "degrees");
  1578. protected function lib_adjust_hue($args) {
  1579. $color = $this->assertColor($args[0]);
  1580. $degrees = $this->assertNumber($args[1]);
  1581. return $this->adjustHsl($color, 1, $degrees);
  1582. }
  1583. protected static $lib_lighten = array("color", "amount");
  1584. protected function lib_lighten($args) {
  1585. $color = $this->assertColor($args[0]);
  1586. $amount = 100*$this->coercePercent($args[1]);
  1587. return $this->adjustHsl($color, 3, $amount);
  1588. }
  1589. protected static $lib_darken = array("color", "amount");
  1590. protected function lib_darken($args) {
  1591. $color = $this->assertColor($args[0]);
  1592. $amount = 100*$this->coercePercent($args[1]);
  1593. return $this->adjustHsl($color, 3, -$amount);
  1594. }
  1595. protected static $lib_saturate = array("color", "amount");
  1596. protected function lib_saturate($args) {
  1597. $color = $this->assertColor($args[0]);
  1598. $amount = 100*$this->coercePercent($args[1]);
  1599. return $this->adjustHsl($color, 2, $amount);
  1600. }
  1601. protected static $lib_desaturate = array("color", "amount");
  1602. protected function lib_desaturate($args) {
  1603. $color = $this->assertColor($args[0]);
  1604. $amount = 100*$this->coercePercent($args[1]);
  1605. return $this->adjustHsl($color, 2, -$amount);
  1606. }
  1607. protected static $lib_grayscale = array("color");
  1608. protected function lib_grayscale($args) {
  1609. return $this->adjustHsl($this->assertColor($args[0]), 2, -100);
  1610. }
  1611. protected static $lib_complement = array("color");
  1612. protected function lib_complement($args) {
  1613. return $this->adjustHsl($this->assertColor($args[0]), 1, 180);
  1614. }
  1615. protected static $lib_invert = array("color");
  1616. protected function lib_invert($args) {
  1617. $color = $this->assertColor($args[0]);
  1618. $color[1] = 255 - $color[1];
  1619. $color[2] = 255 - $color[2];
  1620. $color[3] = 255 - $color[3];
  1621. return $color;
  1622. }
  1623. // increases opacity by amount
  1624. protected static $lib_opacify = array("color", "amount");
  1625. protected function lib_opacify($args) {
  1626. $color = $this->assertColor($args[0]);
  1627. $amount = $this->coercePercent($args[1]);
  1628. $color[4] = (isset($color[4]) ? $color[4] : 1) + $amount;
  1629. $color[4] = min(1, max(0, $color[4]));
  1630. return $color;
  1631. }
  1632. protected static $lib_fade_in = array("color", "amount");
  1633. protected function lib_fade_in($args) {
  1634. return $this->lib_opacify($args);
  1635. }
  1636. // decreases opacity by amount
  1637. protected static $lib_transparentize = array("color", "amount");
  1638. protected function lib_transparentize($args) {
  1639. $color = $this->assertColor($args[0]);
  1640. $amount = $this->coercePercent($args[1]);
  1641. $color[4] = (isset($color[4]) ? $color[4] : 1) - $amount;
  1642. $color[4] = min(1, max(0, $color[4]));
  1643. return $color;
  1644. }
  1645. protected static $lib_fade_out = array("color", "amount");
  1646. protected function lib_fade_out($args) {
  1647. return $this->lib_transparentize($args);
  1648. }
  1649. protected static $lib_unquote = array("string");
  1650. protected function lib_unquote($args) {
  1651. $str = $args[0];
  1652. if ($str[0] == "string") $str[1] = "";
  1653. return $str;
  1654. }
  1655. protected static $lib_quote = array("string");
  1656. protected function lib_quote($args) {
  1657. $value = $args[0];
  1658. if ($value[0] == "string" && !empty($value[1]))
  1659. return $value;
  1660. return array("string", '"', array($value));
  1661. }
  1662. protected static $lib_percentage = array("value");
  1663. protected function lib_percentage($args) {
  1664. return array("number",
  1665. $this->coercePercent($args[0]) * 100,
  1666. "%");
  1667. }
  1668. protected static $lib_round = array("value");
  1669. protected function lib_round($args) {
  1670. $num = $args[0];
  1671. $num[1] = round($num[1]);
  1672. return $num;
  1673. }
  1674. protected static $lib_floor = array("value");
  1675. protected function lib_floor($args) {
  1676. $num = $args[0];
  1677. $num[1] = floor($num[1]);
  1678. return $num;
  1679. }
  1680. protected static $lib_ceil = array("value");
  1681. protected function lib_ceil($args) {
  1682. $num = $args[0];
  1683. $num[1] = ceil($num[1]);
  1684. return $num;
  1685. }
  1686. protected static $lib_abs = array("value");
  1687. protected function lib_abs($args) {
  1688. $num = $args[0];
  1689. $num[1] = abs($num[1]);
  1690. return $num;
  1691. }
  1692. protected function lib_min($args) {
  1693. $numbers = $this->getNormalizedNumbers($args);
  1694. $min = null;
  1695. foreach ($numbers as $key => $number) {
  1696. if (null === $min || $number <= $min[1]) {
  1697. $min = array($key, $number);
  1698. }
  1699. }
  1700. return $args[$min[0]];
  1701. }
  1702. protected function lib_max($args) {
  1703. $numbers = $this->getNormalizedNumbers($args);
  1704. $max = null;
  1705. foreach ($numbers as $key => $number) {
  1706. if (null === $max || $number >= $max[1]) {
  1707. $max = array($key, $number);
  1708. }
  1709. }
  1710. return $args[$max[0]];
  1711. }
  1712. protected function getNormalizedNumbers($args) {
  1713. $unit = null;
  1714. $originalUnit = null;
  1715. $numbers = array();
  1716. foreach ($args as $key => $item) {
  1717. if ('number' != $item[0]) {
  1718. throw new Exception(sprintf('%s is not a number', $item[0]));
  1719. }
  1720. $number = $this->normalizeNumber($item);
  1721. if (null === $unit) {
  1722. $unit = $number[2];
  1723. } elseif ($unit !== $number[2]) {
  1724. throw new Exception(sprintf('Incompatible units: "%s" and "%s".', $originalUnit, $item[2]));
  1725. }
  1726. $originalUnit = $item[2];
  1727. $numbers[$key] = $number[1];
  1728. }
  1729. return $numbers;
  1730. }
  1731. protected static $lib_length = array("list");
  1732. protected function lib_length($args) {
  1733. $list = $this->coerceList($args[0]);
  1734. return count($list[2]);
  1735. }
  1736. protected static $lib_nth = array("list", "n");
  1737. protected function lib_nth($args) {
  1738. $list = $this->coerceList($args[0]);
  1739. $n = $this->assertNumber($args[1]) - 1;
  1740. return isset($list[2][$n]) ? $list[2][$n] : self::$defaultValue;
  1741. }
  1742. protected function listSeparatorForJoin($list1, $sep) {
  1743. if (is_null($sep)) return $list1[1];
  1744. switch ($this->compileValue($sep)) {
  1745. case "comma":
  1746. return ",";
  1747. case "space":
  1748. return "";
  1749. default:
  1750. return $list1[1];
  1751. }
  1752. }
  1753. protected static $lib_join = array("list1", "list2", "separator");
  1754. protected function lib_join($args) {
  1755. list($list1, $list2, $sep) = $args;
  1756. $list1 = $this->coerceList($list1, " ");
  1757. $list2 = $this->coerceList($list2, " ");
  1758. $sep = $this->listSeparatorForJoin($list1, $sep);
  1759. return array("list", $sep, array_merge($list1[2], $list2[2]));
  1760. }
  1761. protected static $lib_append = array("list", "val", "separator");
  1762. protected function lib_append($args) {
  1763. list($list1, $value, $sep) = $args;
  1764. $list1 = $this->coerceList($list1, " ");
  1765. $sep = $this->listSeparatorForJoin($list1, $sep);
  1766. return array("list", $sep, array_merge($list1[2], array($value)));
  1767. }
  1768. protected function lib_zip($args) {
  1769. foreach ($args as $arg) {
  1770. $this->assertList($arg);
  1771. }
  1772. $lists = array();
  1773. $firstList = array_shift($args);
  1774. foreach ($firstList[2] as $key => $item) {
  1775. $list = array("list", "", array($item));
  1776. foreach ($args as $arg) {
  1777. if (isset($arg[2][$key])) {
  1778. $list[2][] = $arg[2][$key];
  1779. } else {
  1780. break 2;
  1781. }
  1782. }
  1783. $lists[] = $list;
  1784. }
  1785. return array("list", ",", $lists);
  1786. }
  1787. protected static $lib_type_of = array("value");
  1788. protected function lib_type_of($args) {
  1789. $value = $args[0];
  1790. switch ($value[0]) {
  1791. case "keyword":
  1792. if ($value == self::$true || $value == self::$false) {
  1793. return "bool";
  1794. }
  1795. if ($this->coerceColor($value)) {
  1796. return "color";
  1797. }
  1798. return "string";
  1799. default:
  1800. return $value[0];
  1801. }
  1802. }
  1803. protected static $lib_unit = array("number");
  1804. protected function lib_unit($args) {
  1805. $num = $args[0];
  1806. if ($num[0] == "number") {
  1807. return array("string", '"', array($num[2]));
  1808. }
  1809. return "";
  1810. }
  1811. protected static $lib_unitless = array("number");
  1812. protected function lib_unitless($args) {
  1813. $value = $args[0];
  1814. return $value[0] == "number" && empty($value[2]);
  1815. }
  1816. protected static $lib_comparable = array("number-1", "number-2");
  1817. protected function lib_comparable($args) {
  1818. list($number1, $number2) = $args;
  1819. if (!isset($number1[0]) || $number1[0] != "number" || !isset($number2[0]) || $number2[0] != "number") {
  1820. throw new Exception('Invalid argument(s) for "comparable"');
  1821. }
  1822. $number1 = $this->normalizeNumber($number1);
  1823. $number2 = $this->normalizeNumber($number2);
  1824. return $number1[2] == $number2[2] || $number1[2] == "" || $number2[2] == "";
  1825. }
  1826. static protected $cssColors = array(
  1827. 'aliceblue' => '240,248,255',
  1828. 'antiquewhite' => '250,235,215',
  1829. 'aqua' => '0,255,255',
  1830. 'aquamarine' => '127,255,212',
  1831. 'azure' => '240,255,255',
  1832. 'beige' => '245,245,220',
  1833. 'bisque' => '255,228,196',
  1834. 'black' => '0,0,0',
  1835. 'blanchedalmond' => '255,235,205',
  1836. 'blue' => '0,0,255',
  1837. 'blueviolet' => '138,43,226',
  1838. 'brown' => '165,42,42',
  1839. 'burlywood' => '222,184,135',
  1840. 'cadetblue' => '95,158,160',
  1841. 'chartreuse' => '127,255,0',
  1842. 'chocolate' => '210,105,30',
  1843. 'coral' => '255,127,80',
  1844. 'cornflowerblue' => '100,149,237',
  1845. 'cornsilk' => '255,248,220',
  1846. 'crimson' => '220,20,60',
  1847. 'cyan' => '0,255,255',
  1848. 'darkblue' => '0,0,139',
  1849. 'darkcyan' => '0,139,139',
  1850. 'darkgoldenrod' => '184,134,11',
  1851. 'darkgray' => '169,169,169',
  1852. 'darkgreen' => '0,100,0',
  1853. 'darkgrey' => '169,169,169',
  1854. 'darkkhaki' => '189,183,107',
  1855. 'darkmagenta' => '139,0,139',
  1856. 'darkolivegreen' => '85,107,47',
  1857. 'darkorange' => '255,140,0',
  1858. 'darkorchid' => '153,50,204',
  1859. 'darkred' => '139,0,0',
  1860. 'darksalmon' => '233,150,122',
  1861. 'darkseagreen' => '143,188,143',
  1862. 'darkslateblue' => '72,61,139',
  1863. 'darkslategray' => '47,79,79',
  1864. 'darkslategrey' => '47,79,79',
  1865. 'darkturquoise' => '0,206,209',
  1866. 'darkviolet' => '148,0,211',
  1867. 'deeppink' => '255,20,147',
  1868. 'deepskyblue' => '0,191,255',
  1869. 'dimgray' => '105,105,105',
  1870. 'dimgrey' => '105,105,105',
  1871. 'dodgerblue' => '30,144,255',
  1872. 'firebrick' => '178,34,34',
  1873. 'floralwhite' => '255,250,240',
  1874. 'forestgreen' => '34,139,34',
  1875. 'fuchsia' => '255,0,255',
  1876. 'gainsboro' => '220,220,220',
  1877. 'ghostwhite' => '248,248,255',
  1878. 'gold' => '255,215,0',
  1879. 'goldenrod' => '218,165,32',
  1880. 'gray' => '128,128,128',
  1881. 'green' => '0,128,0',
  1882. 'greenyellow' => '173,255,47',
  1883. 'grey' => '128,128,128',
  1884. 'honeydew' => '240,255,240',
  1885. 'hotpink' => '255,105,180',
  1886. 'indianred' => '205,92,92',
  1887. 'indigo' => '75,0,130',
  1888. 'ivory' => '255,255,240',
  1889. 'khaki' => '240,230,140',
  1890. 'lavender' => '230,230,250',
  1891. 'lavenderblush' => '255,240,245',
  1892. 'lawngreen' => '124,252,0',
  1893. 'lemonchiffon' => '255,250,205',
  1894. 'lightblue' => '173,216,230',
  1895. 'lightcoral' => '240,128,128',
  1896. 'lightcyan' => '224,255,255',
  1897. 'lightgoldenrodyellow' => '250,250,210',
  1898. 'lightgray' => '211,211,211',
  1899. 'lightgreen' => '144,238,144',
  1900. 'lightgrey' => '211,211,211',
  1901. 'lightpink' => '255,182,193',
  1902. 'lightsalmon' => '255,160,122',
  1903. 'lightseagreen' => '32,178,170',
  1904. 'lightskyblue' => '135,206,250',
  1905. 'lightslategray' => '119,136,153',
  1906. 'lightslategrey' => '119,136,153',
  1907. 'lightsteelblue' => '176,196,222',
  1908. 'lightyellow' => '255,255,224',
  1909. 'lime' => '0,255,0',
  1910. 'limegreen' => '50,205,50',
  1911. 'linen' => '250,240,230',
  1912. 'magenta' => '255,0,255',
  1913. 'maroon' => '128,0,0',
  1914. 'mediumaquamarine' => '102,205,170',
  1915. 'mediumblue' => '0,0,205',
  1916. 'mediumorchid' => '186,85,211',
  1917. 'mediumpurple' => '147,112,219',
  1918. 'mediumseagreen' => '60,179,113',
  1919. 'mediumslateblue' => '123,104,238',
  1920. 'mediumspringgreen' => '0,250,154',
  1921. 'mediumturquoise' => '72,209,204',
  1922. 'mediumvioletred' => '199,21,133',
  1923. 'midnightblue' => '25,25,112',
  1924. 'mintcream' => '245,255,250',
  1925. 'mistyrose' => '255,228,225',
  1926. 'moccasin' => '255,228,181',
  1927. 'navajowhite' => '255,222,173',
  1928. 'navy' => '0,0,128',
  1929. 'oldlace' => '253,245,230',
  1930. 'olive' => '128,128,0',
  1931. 'olivedrab' => '107,142,35',
  1932. 'orange' => '255,165,0',
  1933. 'orangered' => '255,69,0',
  1934. 'orchid' => '218,112,214',
  1935. 'palegoldenrod' => '238,232,170',
  1936. 'palegreen' => '152,251,152',
  1937. 'paleturquoise' => '175,238,238',
  1938. 'palevioletred' => '219,112,147',
  1939. 'papayawhip' => '255,239,213',
  1940. 'peachpuff' => '255,218,185',
  1941. 'peru' => '205,133,63',
  1942. 'pink' => '255,192,203',
  1943. 'plum' => '221,160,221',
  1944. 'powderblue' => '176,224,230',
  1945. 'purple' => '128,0,128',
  1946. 'red' => '255,0,0',
  1947. 'rosybrown' => '188,143,143',
  1948. 'royalblue' => '65,105,225',
  1949. 'saddlebrown' => '139,69,19',
  1950. 'salmon' => '250,128,114',
  1951. 'sandybrown' => '244,164,96',
  1952. 'seagreen' => '46,139,87',
  1953. 'seashell' => '255,245,238',
  1954. 'sienna' => '160,82,45',
  1955. 'silver' => '192,192,192',
  1956. 'skyblue' => '135,206,235',
  1957. 'slateblue' => '106,90,205',
  1958. 'slategray' => '112,128,144',
  1959. 'slategrey' => '112,128,144',
  1960. 'snow' => '255,250,250',
  1961. 'springgreen' => '0,255,127',
  1962. 'steelblue' => '70,130,180',
  1963. 'tan' => '210,180,140',
  1964. 'teal' => '0,128,128',
  1965. 'thistle' => '216,191,216',
  1966. 'tomato' => '255,99,71',
  1967. 'turquoise' => '64,224,208',
  1968. 'violet' => '238,130,238',
  1969. 'wheat' => '245,222,179',
  1970. 'white' => '255,255,255',
  1971. 'whitesmoke' => '245,245,245',
  1972. 'yellow' => '255,255,0',
  1973. 'yellowgreen' => '154,205,50'
  1974. );
  1975. }
  1976. class scss_parser {
  1977. static protected $precedence = array(
  1978. "or" => 0,
  1979. "and" => 1,
  1980. '==' => 2,
  1981. '!=' => 2,
  1982. '<=' => 2,
  1983. '>=' => 2,
  1984. '=' => 2,
  1985. '<' => 3,
  1986. '>' => 2,
  1987. '+' => 3,
  1988. '-' => 3,
  1989. '*' => 4,
  1990. '/' => 4,
  1991. '%' => 4,
  1992. );
  1993. static protected $operators = array("+", "-", "*", "/", "%",
  1994. "==", "!=", "<=", ">=", "<", ">", "and", "or");
  1995. static protected $operatorStr;
  1996. static protected $whitePattern;
  1997. static protected $commentMulti;
  1998. static protected $commentSingle = "//";
  1999. static protected $commentMultiLeft = "/*";
  2000. static protected $commentMultiRight = "*/";
  2001. function __construct($sourceName = null) {
  2002. $this->sourceName = $sourceName;
  2003. if (empty(self::$operatorStr)) {
  2004. self::$operatorStr = $this->makeOperatorStr(self::$operators);
  2005. $commentSingle = $this->preg_quote(self::$commentSingle);
  2006. $commentMultiLeft = $this->preg_quote(self::$commentMultiLeft);
  2007. $commentMultiRight = $this->preg_quote(self::$commentMultiRight);
  2008. self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
  2009. self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
  2010. }
  2011. }
  2012. static protected function makeOperatorStr($operators) {
  2013. return '('.implode('|', array_map(array('scss_parser','preg_quote'),
  2014. $operators)).')';
  2015. }
  2016. function parse($buffer) {
  2017. $this->count = 0;
  2018. $this->env = null;
  2019. $this->inParens = false;
  2020. $this->pushBlock(null); // root block
  2021. $this->eatWhiteDefault = true;
  2022. $this->insertComments = true;
  2023. $this->buffer = $buffer;
  2024. $this->whitespace();
  2025. while (false !== $this->parseChunk());
  2026. if ($this->count != strlen($this->buffer))
  2027. $this->throwParseError();
  2028. if (!empty($this->env->parent)) {
  2029. $this->throwParseError("unclosed block");
  2030. }
  2031. $this->env->isRoot = true;
  2032. return $this->env;
  2033. }
  2034. protected function parseChunk() {
  2035. $s = $this->seek();
  2036. // the directives
  2037. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
  2038. if ($this->literal("@media") && $this->mediaQueryList($mediaQueryList) && $this->literal("{")) {
  2039. $media = $this->pushSpecialBlock("media");
  2040. $media->queryList = $mediaQueryList[2];
  2041. return true;
  2042. } else {
  2043. $this->seek($s);
  2044. }
  2045. if ($this->literal("@mixin") &&
  2046. $this->keyword($mixinName) &&
  2047. ($this->argumentDef($args) || true) &&
  2048. $this->literal("{"))
  2049. {
  2050. $mixin = $this->pushSpecialBlock("mixin");
  2051. $mixin->name = $mixinName;
  2052. $mixin->args = $args;
  2053. return true;
  2054. } else {
  2055. $this->seek($s);
  2056. }
  2057. if ($this->literal("@include") &&
  2058. $this->keyword($mixinName) &&
  2059. ($this->literal("(") &&
  2060. ($this->argValues($argValues) || true) &&
  2061. $this->literal(")") || true) &&
  2062. ($this->end() ||
  2063. $this->literal("{") && $hasBlock = true))
  2064. {
  2065. $child = array("include",
  2066. $mixinName, isset($argValues) ? $argValues : null, null);
  2067. if (!empty($hasBlock)) {
  2068. $include = $this->pushSpecialBlock("include");
  2069. $include->child = $child;
  2070. } else {
  2071. $this->append($child);
  2072. }
  2073. return true;
  2074. } else {
  2075. $this->seek($s);
  2076. }
  2077. if ($this->literal("@import") &&
  2078. $this->valueList($importPath) &&
  2079. $this->end())
  2080. {
  2081. $this->append(array("import", $importPath));
  2082. return true;
  2083. } else {
  2084. $this->seek($s);
  2085. }
  2086. if ($this->literal("@extend") &&
  2087. $this->selectors($selector) &&
  2088. $this->end())
  2089. {
  2090. $this->append(array("extend", $selector));
  2091. return true;
  2092. } else {
  2093. $this->seek($s);
  2094. }
  2095. if ($this->literal("@function") &&
  2096. $this->keyword($fn_name) &&
  2097. $this->argumentDef($args) &&
  2098. $this->literal("{"))
  2099. {
  2100. $func = $this->pushSpecialBlock("function");
  2101. $func->name = $fn_name;
  2102. $func->args = $args;
  2103. return true;
  2104. } else {
  2105. $this->seek($s);
  2106. }
  2107. if ($this->literal("@return") && $this->valueList($retVal) && $this->end()) {
  2108. $this->append(array("return", $retVal));
  2109. return true;
  2110. } else {
  2111. $this->seek($s);
  2112. }
  2113. if ($this->literal("@each") &&
  2114. $this->variable($varName) &&
  2115. $this->literal("in") &&
  2116. $this->valueList($list) &&
  2117. $this->literal("{"))
  2118. {
  2119. $each = $this->pushSpecialBlock("each");
  2120. $each->var = $varName[1];
  2121. $each->list = $list;
  2122. return true;
  2123. } else {
  2124. $this->seek($s);
  2125. }
  2126. if ($this->literal("@while") &&
  2127. $this->expression($cond) &&
  2128. $this->literal("{"))
  2129. {
  2130. $while = $this->pushSpecialBlock("while");
  2131. $while->cond = $cond;
  2132. return true;
  2133. } else {
  2134. $this->seek($s);
  2135. }
  2136. if ($this->literal("@for") &&
  2137. $this->variable($varName) &&
  2138. $this->literal("from") &&
  2139. $this->expression($start) &&
  2140. ($this->literal("through") ||
  2141. ($forUntil = true && $this->literal("to"))) &&
  2142. $this->expression($end) &&
  2143. $this->literal("{"))
  2144. {
  2145. $for = $this->pushSpecialBlock("for");
  2146. $for->var = $varName[1];
  2147. $for->start = $start;
  2148. $for->end = $end;
  2149. $for->until = isset($forUntil);
  2150. return true;
  2151. } else {
  2152. $this->seek($s);
  2153. }
  2154. if ($this->literal("@if") && $this->valueList($cond) && $this->literal("{")) {
  2155. $if = $this->pushSpecialBlock("if");
  2156. $if->cond = $cond;
  2157. $if->cases = array();
  2158. return true;
  2159. } else {
  2160. $this->seek($s);
  2161. }
  2162. if (($this->literal("@debug") || $this->literal("@warn")) &&
  2163. $this->valueList($value) &&
  2164. $this->end()) {
  2165. $this->append(array("debug", $value, $s));
  2166. return true;
  2167. } else {
  2168. $this->seek($s);
  2169. }
  2170. if ($this->literal("@content") && $this->end()) {
  2171. $this->append(array("mixin_content"));
  2172. return true;
  2173. } else {
  2174. $this->seek($s);
  2175. }
  2176. $last = $this->last();
  2177. if (!is_null($last) && $last[0] == "if") {
  2178. list(, $if) = $last;
  2179. if ($this->literal("@else")) {
  2180. if ($this->literal("{")) {
  2181. $else = $this->pushSpecialBlock("else");
  2182. } elseif ($this->literal("if") && $this->valueList($cond) && $this->literal("{")) {
  2183. $else = $this->pushSpecialBlock("elseif");
  2184. $else->cond = $cond;
  2185. }
  2186. if (isset($else)) {
  2187. $else->dontAppend = true;
  2188. $if->cases[] = $else;
  2189. return true;
  2190. }
  2191. }
  2192. $this->seek($s);
  2193. }
  2194. if ($this->literal("@charset") &&
  2195. $this->valueList($charset) && $this->end())
  2196. {
  2197. $this->append(array("charset", $charset));
  2198. return true;
  2199. } else {
  2200. $this->seek($s);
  2201. }
  2202. // doesn't match built in directive, do generic one
  2203. if ($this->literal("@", false) && $this->keyword($dirName) &&
  2204. ($this->openString("{", $dirValue) || true) &&
  2205. $this->literal("{"))
  2206. {
  2207. $directive = $this->pushSpecialBlock("directive");
  2208. $directive->name = $dirName;
  2209. if (isset($dirValue)) $directive->value = $dirValue;
  2210. return true;
  2211. }
  2212. $this->seek($s);
  2213. return false;
  2214. }
  2215. // property shortcut
  2216. // captures most properties before having to parse a selector
  2217. if ($this->keyword($name, false) &&
  2218. $this->literal(": ") &&
  2219. $this->valueList($value) &&
  2220. $this->end())
  2221. {
  2222. $name = array("string", "", array($name));
  2223. $this->append(array("assign", $name, $value));
  2224. return true;
  2225. } else {
  2226. $this->seek($s);
  2227. }
  2228. // variable assigns
  2229. if ($this->variable($name) &&
  2230. $this->literal(":") &&
  2231. $this->valueList($value) && $this->end())
  2232. {
  2233. $defaultVar = false;
  2234. // check for !default
  2235. if ($value[0] == "list") {
  2236. $def = end($value[2]);
  2237. if ($def[0] == "keyword" && $def[1] == "!default") {
  2238. array_pop($value[2]);
  2239. $value = $this->flattenList($value);
  2240. $defaultVar = true;
  2241. }
  2242. }
  2243. $this->append(array("assign", $name, $value, $defaultVar));
  2244. return true;
  2245. } else {
  2246. $this->seek($s);
  2247. }
  2248. // misc
  2249. if ($this->literal("-->")) {
  2250. return true;
  2251. }
  2252. // opening css block
  2253. $oldComments = $this->insertComments;
  2254. $this->insertComments = false;
  2255. if ($this->selectors($selectors) && $this->literal("{")) {
  2256. $this->pushBlock($selectors);
  2257. $this->insertComments = $oldComments;
  2258. return true;
  2259. } else {
  2260. $this->seek($s);
  2261. }
  2262. $this->insertComments = $oldComments;
  2263. // property assign, or nested assign
  2264. if ($this->propertyName($name) && $this->literal(":")) {
  2265. $foundSomething = false;
  2266. if ($this->valueList($value)) {
  2267. $this->append(array("assign", $name, $value));
  2268. $foundSomething = true;
  2269. }
  2270. if ($this->literal("{")) {
  2271. $propBlock = $this->pushSpecialBlock("nestedprop");
  2272. $propBlock->prefix = $name;
  2273. $foundSomething = true;
  2274. } elseif ($foundSomething) {
  2275. $foundSomething = $this->end();
  2276. }
  2277. if ($foundSomething) {
  2278. return true;
  2279. }
  2280. $this->seek($s);
  2281. } else {
  2282. $this->seek($s);
  2283. }
  2284. // closing a block
  2285. if ($this->literal("}")) {
  2286. $block = $this->popBlock();
  2287. if (isset($block->type) && $block->type == "include") {
  2288. $include = $block->child;
  2289. unset($block->child);
  2290. $include[3] = $block;
  2291. $this->append($include);
  2292. } else if (empty($block->dontAppend)) {
  2293. $type = isset($block->type) ? $block->type : "block";
  2294. $this->append(array($type, $block));
  2295. }
  2296. return true;
  2297. }
  2298. // extra stuff
  2299. if ($this->literal(";") ||
  2300. $this->literal("<!--"))
  2301. {
  2302. return true;
  2303. }
  2304. return false;
  2305. }
  2306. protected function literal($what, $eatWhitespace = null) {
  2307. if (is_null($eatWhitespace)) $eatWhitespace = $this->eatWhiteDefault;
  2308. // shortcut on single letter
  2309. if (!isset($what[1]) && isset($this->buffer[$this->count])) {
  2310. if ($this->buffer[$this->count] == $what) {
  2311. if (!$eatWhitespace) {
  2312. $this->count++;
  2313. return true;
  2314. }
  2315. // goes below...
  2316. } else {
  2317. return false;
  2318. }
  2319. }
  2320. return $this->match($this->preg_quote($what), $m, $eatWhitespace);
  2321. }
  2322. // tree builders
  2323. protected function pushBlock($selectors) {
  2324. $b = new stdClass;
  2325. $b->parent = $this->env; // not sure if we need this yet
  2326. $b->selectors = $selectors;
  2327. $b->children = array();
  2328. $this->env = $b;
  2329. return $b;
  2330. }
  2331. protected function pushSpecialBlock($type) {
  2332. $block = $this->pushBlock(null);
  2333. $block->type = $type;
  2334. return $block;
  2335. }
  2336. protected function popBlock() {
  2337. if (empty($this->env->parent)) {
  2338. $this->throwParseError("unexpected }");
  2339. }
  2340. $old = $this->env;
  2341. $this->env = $this->env->parent;
  2342. unset($old->parent);
  2343. return $old;
  2344. }
  2345. protected function append($statement) {
  2346. $this->env->children[] = $statement;
  2347. }
  2348. // last child that was appended
  2349. protected function last() {
  2350. $i = count($this->env->children) - 1;
  2351. if (isset($this->env->children[$i]))
  2352. return $this->env->children[$i];
  2353. }
  2354. // high level parsers (they return parts of ast)
  2355. protected function mediaQueryList(&$out) {
  2356. return $this->genericList($out, "mediaQuery", ",", false);
  2357. }
  2358. protected function mediaQuery(&$out) {
  2359. $s = $this->seek();
  2360. $expressions = null;
  2361. $parts = array();
  2362. if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->mixedKeyword($mediaType)) {
  2363. $prop = array("mediaType");
  2364. if (isset($only)) $prop[] = array("keyword", "only");
  2365. if (isset($not)) $prop[] = array("keyword", "not");
  2366. $media = array("list", "", array());
  2367. foreach ((array)$mediaType as $type) {
  2368. if (is_array($type)) {
  2369. $media[2][] = $type;
  2370. } else {
  2371. $media[2][] = array("keyword", $type);
  2372. }
  2373. }
  2374. $prop[] = $media;
  2375. $parts[] = $prop;
  2376. } else {
  2377. $this->seek($s);
  2378. }
  2379. if ($this->literal("and")) {
  2380. $this->genericList($expressions, "mediaExpression", "and", false);
  2381. if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
  2382. }
  2383. $out = $parts;
  2384. return true;
  2385. }
  2386. protected function mediaExpression(&$out) {
  2387. $s = $this->seek();
  2388. $value = null;
  2389. if ($this->literal("(") &&
  2390. $this->expression($feature) &&
  2391. ($this->literal(":") && $this->expression($value) || true) &&
  2392. $this->literal(")"))
  2393. {
  2394. $out = array("mediaExp", $feature);
  2395. if ($value) $out[] = $value;
  2396. return true;
  2397. }
  2398. $this->seek($s);
  2399. return false;
  2400. }
  2401. protected function argValues(&$out) {
  2402. if ($this->genericList($list, "argValue", ",", false)) {
  2403. $out = $list[2];
  2404. return true;
  2405. }
  2406. return false;
  2407. }
  2408. protected function argValue(&$out) {
  2409. $s = $this->seek();
  2410. $keyword = null;
  2411. if (!$this->variable($keyword) || !$this->literal(":")) {
  2412. $this->seek($s);
  2413. $keyword = null;
  2414. }
  2415. if ($this->genericList($value, "expression")) {
  2416. $out = array($keyword, $value, false);
  2417. $s = $this->seek();
  2418. if ($this->literal("...")) {
  2419. $out[2] = true;
  2420. } else {
  2421. $this->seek($s);
  2422. }
  2423. return true;
  2424. }
  2425. return false;
  2426. }
  2427. protected function valueList(&$out) {
  2428. return $this->genericList($out, "commaList");
  2429. }
  2430. protected function commaList(&$out) {
  2431. return $this->genericList($out, "expression", ",");
  2432. }
  2433. protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
  2434. $s = $this->seek();
  2435. $items = array();
  2436. while ($this->$parseItem($value)) {
  2437. $items[] = $value;
  2438. if ($delim) {
  2439. if (!$this->literal($delim)) break;
  2440. }
  2441. }
  2442. if (count($items) == 0) {
  2443. $this->seek($s);
  2444. return false;
  2445. }
  2446. if ($flatten && count($items) == 1) {
  2447. $out = $items[0];
  2448. } else {
  2449. $out = array("list", $delim, $items);
  2450. }
  2451. return true;
  2452. }
  2453. protected function expression(&$out) {
  2454. $s = $this->seek();
  2455. if ($this->literal("(")) {
  2456. if ($this->literal(")")) {
  2457. $out = array("list", "", array());
  2458. return true;
  2459. }
  2460. if ($this->valueList($out) && $this->literal(')') && $out[0] == "list") {
  2461. return true;
  2462. }
  2463. $this->seek($s);
  2464. }
  2465. if ($this->value($lhs)) {
  2466. $out = $this->expHelper($lhs, 0);
  2467. return true;
  2468. }
  2469. return false;
  2470. }
  2471. protected function expHelper($lhs, $minP) {
  2472. $opstr = self::$operatorStr;
  2473. $ss = $this->seek();
  2474. $whiteBefore = isset($this->buffer[$this->count - 1]) &&
  2475. ctype_space($this->buffer[$this->count - 1]);
  2476. while ($this->match($opstr, $m) && self::$precedence[$m[1]] >= $minP) {
  2477. $whiteAfter = isset($this->buffer[$this->count - 1]) &&
  2478. ctype_space($this->buffer[$this->count - 1]);
  2479. $op = $m[1];
  2480. // don't turn negative numbers into expressions
  2481. if ($op == "-" && $whiteBefore) {
  2482. if (!$whiteAfter) break;
  2483. }
  2484. if (!$this->value($rhs)) break;
  2485. // peek and see if rhs belongs to next operator
  2486. if ($this->peek($opstr, $next) && self::$precedence[$next[1]] > self::$precedence[$op]) {
  2487. $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
  2488. }
  2489. $lhs = array("exp", $op, $lhs, $rhs, $this->inParens, $whiteBefore, $whiteAfter);
  2490. $ss = $this->seek();
  2491. $whiteBefore = isset($this->buffer[$this->count - 1]) &&
  2492. ctype_space($this->buffer[$this->count - 1]);
  2493. }
  2494. $this->seek($ss);
  2495. return $lhs;
  2496. }
  2497. protected function value(&$out) {
  2498. $s = $this->seek();
  2499. if ($this->literal("not", false) && $this->whitespace() && $this->value($inner)) {
  2500. $out = array("unary", "not", $inner, $this->inParens);
  2501. return true;
  2502. } else {
  2503. $this->seek($s);
  2504. }
  2505. if ($this->literal("+") && $this->value($inner)) {
  2506. $out = array("unary", "+", $inner, $this->inParens);
  2507. return true;
  2508. } else {
  2509. $this->seek($s);
  2510. }
  2511. // negation
  2512. if ($this->literal("-", false) &&
  2513. ($this->variable($inner) ||
  2514. $this->unit($inner) ||
  2515. $this->parenValue($inner)))
  2516. {
  2517. $out = array("unary", "-", $inner, $this->inParens);
  2518. return true;
  2519. } else {
  2520. $this->seek($s);
  2521. }
  2522. if ($this->parenValue($out)) return true;
  2523. if ($this->interpolation($out)) return true;
  2524. if ($this->variable($out)) return true;
  2525. if ($this->color($out)) return true;
  2526. if ($this->unit($out)) return true;
  2527. if ($this->string($out)) return true;
  2528. if ($this->func($out)) return true;
  2529. if ($this->progid($out)) return true;
  2530. if ($this->keyword($keyword)) {
  2531. $out = array("keyword", $keyword);
  2532. return true;
  2533. }
  2534. return false;
  2535. }
  2536. // value wrappen in parentheses
  2537. protected function parenValue(&$out) {
  2538. $s = $this->seek();
  2539. $inParens = $this->inParens;
  2540. if ($this->literal("(") &&
  2541. ($this->inParens = true) && $this->expression($exp) &&
  2542. $this->literal(")"))
  2543. {
  2544. $out = $exp;
  2545. $this->inParens = $inParens;
  2546. return true;
  2547. } else {
  2548. $this->inParens = $inParens;
  2549. $this->seek($s);
  2550. }
  2551. return false;
  2552. }
  2553. protected function progid(&$out) {
  2554. $s = $this->seek();
  2555. if ($this->literal("progid:", false) &&
  2556. $this->openString("(", $fn) &&
  2557. $this->literal("("))
  2558. {
  2559. $this->openString(")", $args, "(");
  2560. if ($this->literal(")")) {
  2561. $out = array("string", "", array(
  2562. "progid:", $fn, "(", $args, ")"
  2563. ));
  2564. return true;
  2565. }
  2566. }
  2567. $this->seek($s);
  2568. return false;
  2569. }
  2570. protected function func(&$func) {
  2571. $s = $this->seek();
  2572. if ($this->keyword($name, false) &&
  2573. $this->literal("("))
  2574. {
  2575. if ($name != "expression" && false == preg_match("/^(-[a-z]+-)?calc$/", $name)) {
  2576. $ss = $this->seek();
  2577. if ($this->argValues($args) && $this->literal(")")) {
  2578. $func = array("fncall", $name, $args);
  2579. return true;
  2580. }
  2581. $this->seek($ss);
  2582. }
  2583. if (($this->openString(")", $str, "(") || true ) &&
  2584. $this->literal(")"))
  2585. {
  2586. $args = array();
  2587. if (!empty($str)) {
  2588. $args[] = array(null, array("string", "", array($str)));
  2589. }
  2590. $func = array("fncall", $name, $args);
  2591. return true;
  2592. }
  2593. }
  2594. $this->seek($s);
  2595. return false;
  2596. }
  2597. protected function argumentDef(&$out) {
  2598. $s = $this->seek();
  2599. $this->literal("(");
  2600. $args = array();
  2601. while ($this->variable($var)) {
  2602. $arg = array($var[1], null, false);
  2603. $ss = $this->seek();
  2604. if ($this->literal(":") && $this->genericList($defaultVal, "expression")) {
  2605. $arg[1] = $defaultVal;
  2606. } else {
  2607. $this->seek($ss);
  2608. }
  2609. $ss = $this->seek();
  2610. if ($this->literal("...")) {
  2611. $sss = $this->seek();
  2612. if (!$this->literal(")")) {
  2613. throw new Exception('... has to be after the final argument');
  2614. }
  2615. $arg[2] = true;
  2616. $this->seek($sss);
  2617. } else {
  2618. $this->seek($ss);
  2619. }
  2620. $args[] = $arg;
  2621. if (!$this->literal(",")) break;
  2622. }
  2623. if (!$this->literal(")")) {
  2624. $this->seek($s);
  2625. return false;
  2626. }
  2627. $out = $args;
  2628. return true;
  2629. }
  2630. protected function color(&$out) {
  2631. $color = array('color');
  2632. if ($this->match('(#([0-9a-f]{6})|#([0-9a-f]{3}))', $m)) {
  2633. if (isset($m[3])) {
  2634. $num = $m[3];
  2635. $width = 16;
  2636. } else {
  2637. $num = $m[2];
  2638. $width = 256;
  2639. }
  2640. $num = hexdec($num);
  2641. foreach (array(3,2,1) as $i) {
  2642. $t = $num % $width;
  2643. $num /= $width;
  2644. $color[$i] = $t * (256/$width) + $t * floor(16/$width);
  2645. }
  2646. $out = $color;
  2647. return true;
  2648. }
  2649. return false;
  2650. }
  2651. protected function unit(&$unit) {
  2652. if ($this->match('([0-9]*(\.)?[0-9]+)([%a-zA-Z]+)?', $m)) {
  2653. $unit = array("number", $m[1], empty($m[3]) ? "" : $m[3]);
  2654. return true;
  2655. }
  2656. return false;
  2657. }
  2658. protected function string(&$out) {
  2659. $s = $this->seek();
  2660. if ($this->literal('"', false)) {
  2661. $delim = '"';
  2662. } elseif ($this->literal("'", false)) {
  2663. $delim = "'";
  2664. } else {
  2665. return false;
  2666. }
  2667. $content = array();
  2668. // look for either ending delim , escape, or string interpolation
  2669. $patt = '([^\n]*?)(#\{|\\\\|' .
  2670. $this->preg_quote($delim).')';
  2671. $oldWhite = $this->eatWhiteDefault;
  2672. $this->eatWhiteDefault = false;
  2673. while ($this->match($patt, $m, false)) {
  2674. $content[] = $m[1];
  2675. if ($m[2] == "#{") {
  2676. $this->count -= strlen($m[2]);
  2677. if ($this->interpolation($inter, false)) {
  2678. $content[] = $inter;
  2679. } else {
  2680. $this->count += strlen($m[2]);
  2681. $content[] = "#{"; // ignore it
  2682. }
  2683. } elseif ($m[2] == '\\') {
  2684. $content[] = $m[2];
  2685. if ($this->literal($delim, false)) {
  2686. $content[] = $delim;
  2687. }
  2688. } else {
  2689. $this->count -= strlen($delim);
  2690. break; // delim
  2691. }
  2692. }
  2693. $this->eatWhiteDefault = $oldWhite;
  2694. if ($this->literal($delim)) {
  2695. $out = array("string", $delim, $content);
  2696. return true;
  2697. }
  2698. $this->seek($s);
  2699. return false;
  2700. }
  2701. protected function mixedKeyword(&$out) {
  2702. $s = $this->seek();
  2703. $parts = array();
  2704. $oldWhite = $this->eatWhiteDefault;
  2705. $this->eatWhiteDefault = false;
  2706. while (true) {
  2707. if ($this->keyword($key)) {
  2708. $parts[] = $key;
  2709. continue;
  2710. }
  2711. if ($this->interpolation($inter)) {
  2712. $parts[] = $inter;
  2713. continue;
  2714. }
  2715. break;
  2716. }
  2717. $this->eatWhiteDefault = $oldWhite;
  2718. if (count($parts) == 0) return false;
  2719. if ($this->eatWhiteDefault) {
  2720. $this->whitespace();
  2721. }
  2722. $out = $parts;
  2723. return true;
  2724. }
  2725. // an unbounded string stopped by $end
  2726. protected function openString($end, &$out, $nestingOpen=null) {
  2727. $oldWhite = $this->eatWhiteDefault;
  2728. $this->eatWhiteDefault = false;
  2729. $stop = array("'", '"', "#{", $end);
  2730. $stop = array_map(array($this, "preg_quote"), $stop);
  2731. $stop[] = self::$commentMulti;
  2732. $patt = '(.*?)('.implode("|", $stop).')';
  2733. $nestingLevel = 0;
  2734. $content = array();
  2735. while ($this->match($patt, $m, false)) {
  2736. if (!empty($m[1])) {
  2737. $content[] = $m[1];
  2738. if ($nestingOpen) {
  2739. $nestingLevel += substr_count($m[1], $nestingOpen);
  2740. }
  2741. }
  2742. $tok = $m[2];
  2743. $this->count-= strlen($tok);
  2744. if ($tok == $end) {
  2745. if ($nestingLevel == 0) {
  2746. break;
  2747. } else {
  2748. $nestingLevel--;
  2749. }
  2750. }
  2751. if (($tok == "'" || $tok == '"') && $this->string($str)) {
  2752. $content[] = $str;
  2753. continue;
  2754. }
  2755. if ($tok == "#{" && $this->interpolation($inter)) {
  2756. $content[] = $inter;
  2757. continue;
  2758. }
  2759. $content[] = $tok;
  2760. $this->count+= strlen($tok);
  2761. }
  2762. $this->eatWhiteDefault = $oldWhite;
  2763. if (count($content) == 0) return false;
  2764. // trim the end
  2765. if (is_string(end($content))) {
  2766. $content[count($content) - 1] = rtrim(end($content));
  2767. }
  2768. $out = array("string", "", $content);
  2769. return true;
  2770. }
  2771. // $lookWhite: save information about whitespace before and after
  2772. protected function interpolation(&$out, $lookWhite=true) {
  2773. $oldWhite = $this->eatWhiteDefault;
  2774. $this->eatWhiteDefault = true;
  2775. $s = $this->seek();
  2776. if ($this->literal("#{") && $this->valueList($value) && $this->literal("}", false)) {
  2777. // TODO: don't error if out of bounds
  2778. if ($lookWhite) {
  2779. $left = preg_match('/\s/', $this->buffer[$s - 1]) ? " " : "";
  2780. $right = preg_match('/\s/', $this->buffer[$this->count]) ? " ": "";
  2781. } else {
  2782. $left = $right = false;
  2783. }
  2784. $out = array("interpolate", $value, $left, $right);
  2785. $this->eatWhiteDefault = $oldWhite;
  2786. if ($this->eatWhiteDefault) $this->whitespace();
  2787. return true;
  2788. }
  2789. $this->seek($s);
  2790. $this->eatWhiteDefault = $oldWhite;
  2791. return false;
  2792. }
  2793. // low level parsers
  2794. // returns an array of parts or a string
  2795. protected function propertyName(&$out) {
  2796. $s = $this->seek();
  2797. $parts = array();
  2798. $oldWhite = $this->eatWhiteDefault;
  2799. $this->eatWhiteDefault = false;
  2800. while (true) {
  2801. if ($this->interpolation($inter)) {
  2802. $parts[] = $inter;
  2803. } elseif ($this->keyword($text)) {
  2804. $parts[] = $text;
  2805. } elseif (count($parts) == 0 && $this->match('[:.#]', $m, false)) {
  2806. // css hacks
  2807. $parts[] = $m[0];
  2808. } else {
  2809. break;
  2810. }
  2811. }
  2812. $this->eatWhiteDefault = $oldWhite;
  2813. if (count($parts) == 0) return false;
  2814. // match comment hack
  2815. if (preg_match(self::$whitePattern,
  2816. $this->buffer, $m, null, $this->count))
  2817. {
  2818. if (!empty($m[0])) {
  2819. $parts[] = $m[0];
  2820. $this->count += strlen($m[0]);
  2821. }
  2822. }
  2823. $this->whitespace(); // get any extra whitespace
  2824. $out = array("string", "", $parts);
  2825. return true;
  2826. }
  2827. // comma separated list of selectors
  2828. protected function selectors(&$out) {
  2829. $s = $this->seek();
  2830. $selectors = array();
  2831. while ($this->selector($sel)) {
  2832. $selectors[] = $sel;
  2833. if (!$this->literal(",")) break;
  2834. while ($this->literal(",")); // ignore extra
  2835. }
  2836. if (count($selectors) == 0) {
  2837. $this->seek($s);
  2838. return false;
  2839. }
  2840. $out = $selectors;
  2841. return true;
  2842. }
  2843. // whitespace separated list of selectorSingle
  2844. protected function selector(&$out) {
  2845. $selector = array();
  2846. while (true) {
  2847. if ($this->match('[>+~]+', $m)) {
  2848. $selector[] = array($m[0]);
  2849. } elseif ($this->selectorSingle($part)) {
  2850. $selector[] = $part;
  2851. $this->whitespace();
  2852. } else {
  2853. break;
  2854. }
  2855. }
  2856. if (count($selector) == 0) {
  2857. return false;
  2858. }
  2859. $out = $selector;
  2860. return true;
  2861. }
  2862. // the parts that make up
  2863. // div[yes=no]#something.hello.world:nth-child(-2n+1)%placeholder
  2864. protected function selectorSingle(&$out) {
  2865. $oldWhite = $this->eatWhiteDefault;
  2866. $this->eatWhiteDefault = false;
  2867. $parts = array();
  2868. if ($this->literal("*", false)) {
  2869. $parts[] = "*";
  2870. }
  2871. while (true) {
  2872. // see if we can stop early
  2873. if ($this->match("\s*[{,]", $m)) {
  2874. $this->count--;
  2875. break;
  2876. }
  2877. $s = $this->seek();
  2878. // self
  2879. if ($this->literal("&", false)) {
  2880. $parts[] = scssc::$selfSelector;
  2881. continue;
  2882. }
  2883. if ($this->literal(".", false)) {
  2884. $parts[] = ".";
  2885. continue;
  2886. }
  2887. if ($this->literal("|", false)) {
  2888. $parts[] = "|";
  2889. continue;
  2890. }
  2891. // for keyframes
  2892. if ($this->unit($unit)) {
  2893. $parts[] = $unit;
  2894. continue;
  2895. }
  2896. if ($this->keyword($name)) {
  2897. $parts[] = $name;
  2898. continue;
  2899. }
  2900. if ($this->interpolation($inter)) {
  2901. $parts[] = $inter;
  2902. continue;
  2903. }
  2904. if ($this->literal('%', false) && $this->placeholder($placeholder)) {
  2905. $parts[] = '%';
  2906. $parts[] = $placeholder;
  2907. continue;
  2908. }
  2909. if ($this->literal("#", false)) {
  2910. $parts[] = "#";
  2911. continue;
  2912. }
  2913. // a pseudo selector
  2914. if ($this->match("::?", $m) && $this->mixedKeyword($nameParts)) {
  2915. $parts[] = $m[0];
  2916. foreach ($nameParts as $sub) {
  2917. $parts[] = $sub;
  2918. }
  2919. $ss = $this->seek();
  2920. if ($this->literal("(") &&
  2921. ($this->openString(")", $str, "(") || true ) &&
  2922. $this->literal(")"))
  2923. {
  2924. $parts[] = "(";
  2925. if (!empty($str)) $parts[] = $str;
  2926. $parts[] = ")";
  2927. } else {
  2928. $this->seek($ss);
  2929. }
  2930. continue;
  2931. } else {
  2932. $this->seek($s);
  2933. }
  2934. // attribute selector
  2935. // TODO: replace with open string?
  2936. if ($this->literal("[", false)) {
  2937. $attrParts = array("[");
  2938. // keyword, string, operator
  2939. while (true) {
  2940. if ($this->literal("]", false)) {
  2941. $this->count--;
  2942. break; // get out early
  2943. }
  2944. if ($this->match('\s+', $m)) {
  2945. $attrParts[] = " ";
  2946. continue;
  2947. }
  2948. if ($this->string($str)) {
  2949. $attrParts[] = $str;
  2950. continue;
  2951. }
  2952. if ($this->keyword($word)) {
  2953. $attrParts[] = $word;
  2954. continue;
  2955. }
  2956. if ($this->interpolation($inter, false)) {
  2957. $attrParts[] = $inter;
  2958. continue;
  2959. }
  2960. // operator, handles attr namespace too
  2961. if ($this->match('[|-~\$\*\^=]+', $m)) {
  2962. $attrParts[] = $m[0];
  2963. continue;
  2964. }
  2965. break;
  2966. }
  2967. if ($this->literal("]", false)) {
  2968. $attrParts[] = "]";
  2969. foreach ($attrParts as $part) {
  2970. $parts[] = $part;
  2971. }
  2972. continue;
  2973. }
  2974. $this->seek($s);
  2975. // should just break here?
  2976. }
  2977. break;
  2978. }
  2979. $this->eatWhiteDefault = $oldWhite;
  2980. if (count($parts) == 0) return false;
  2981. $out = $parts;
  2982. return true;
  2983. }
  2984. protected function variable(&$out) {
  2985. $s = $this->seek();
  2986. if ($this->literal("$", false) && $this->keyword($name)) {
  2987. $out = array("var", $name);
  2988. return true;
  2989. }
  2990. $this->seek($s);
  2991. return false;
  2992. }
  2993. protected function keyword(&$word, $eatWhitespace = null) {
  2994. if ($this->match('([\w_\-\*!"\'\\\\][\w\-_"\'\\\\]*)',
  2995. $m, $eatWhitespace))
  2996. {
  2997. $word = $m[1];
  2998. return true;
  2999. }
  3000. return false;
  3001. }
  3002. protected function placeholder(&$placeholder) {
  3003. if ($this->match('([\w\-_]+)', $m)) {
  3004. $placeholder = $m[1];
  3005. return true;
  3006. }
  3007. return false;
  3008. }
  3009. // consume an end of statement delimiter
  3010. protected function end() {
  3011. if ($this->literal(';')) {
  3012. return true;
  3013. } elseif ($this->count == strlen($this->buffer) || $this->buffer{$this->count} == '}') {
  3014. // if there is end of file or a closing block next then we don't need a ;
  3015. return true;
  3016. }
  3017. return false;
  3018. }
  3019. // advance counter to next occurrence of $what
  3020. // $until - don't include $what in advance
  3021. // $allowNewline, if string, will be used as valid char set
  3022. protected function to($what, &$out, $until = false, $allowNewline = false) {
  3023. if (is_string($allowNewline)) {
  3024. $validChars = $allowNewline;
  3025. } else {
  3026. $validChars = $allowNewline ? "." : "[^\n]";
  3027. }
  3028. if (!$this->match('('.$validChars.'*?)'.$this->preg_quote($what), $m, !$until)) return false;
  3029. if ($until) $this->count -= strlen($what); // give back $what
  3030. $out = $m[1];
  3031. return true;
  3032. }
  3033. protected function throwParseError($msg = "parse error", $count = null) {
  3034. $count = is_null($count) ? $this->count : $count;
  3035. $line = $this->getLineNo($count);
  3036. if (!empty($this->sourceName)) {
  3037. $loc = "$this->sourceName on line $line";
  3038. } else {
  3039. $loc = "line: $line";
  3040. }
  3041. if ($this->peek("(.*?)(\n|$)", $m, $count)) {
  3042. throw new Exception("$msg: failed at `$m[1]` $loc");
  3043. } else {
  3044. throw new Exception("$msg: $loc");
  3045. }
  3046. }
  3047. public function getLineNo($pos) {
  3048. return 1 + substr_count(substr($this->buffer, 0, $pos), "\n");
  3049. }
  3050. // try to match something on head of buffer
  3051. protected function match($regex, &$out, $eatWhitespace = null) {
  3052. if (is_null($eatWhitespace)) $eatWhitespace = $this->eatWhiteDefault;
  3053. $r = '/'.$regex.'/Ais';
  3054. if (preg_match($r, $this->buffer, $out, null, $this->count)) {
  3055. $this->count += strlen($out[0]);
  3056. if ($eatWhitespace) $this->whitespace();
  3057. return true;
  3058. }
  3059. return false;
  3060. }
  3061. // match some whitespace
  3062. protected function whitespace() {
  3063. $gotWhite = false;
  3064. while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
  3065. if ($this->insertComments) {
  3066. if (isset($m[1]) && empty($this->commentsSeen[$this->count])) {
  3067. $this->append(array("comment", $m[1]));
  3068. $this->commentsSeen[$this->count] = true;
  3069. }
  3070. }
  3071. $this->count += strlen($m[0]);
  3072. $gotWhite = true;
  3073. }
  3074. return $gotWhite;
  3075. }
  3076. protected function peek($regex, &$out, $from=null) {
  3077. if (is_null($from)) $from = $this->count;
  3078. $r = '/'.$regex.'/Ais';
  3079. $result = preg_match($r, $this->buffer, $out, null, $from);
  3080. return $result;
  3081. }
  3082. protected function seek($where = null) {
  3083. if ($where === null) return $this->count;
  3084. else $this->count = $where;
  3085. return true;
  3086. }
  3087. static function preg_quote($what) {
  3088. return preg_quote($what, '/');
  3089. }
  3090. protected function show() {
  3091. if ($this->peek("(.*?)(\n|$)", $m, $this->count)) {
  3092. return $m[1];
  3093. }
  3094. return "";
  3095. }
  3096. // turn list of length 1 into value type
  3097. protected function flattenList($value) {
  3098. if ($value[0] == "list" && count($value[2]) == 1) {
  3099. return $this->flattenList($value[2][0]);
  3100. }
  3101. return $value;
  3102. }
  3103. }
  3104. class scss_formatter {
  3105. public $indentChar = " ";
  3106. public $break = "\n";
  3107. public $open = " {";
  3108. public $close = "}";
  3109. public $tagSeparator = ", ";
  3110. public $assignSeparator = ": ";
  3111. public function __construct() {
  3112. $this->indentLevel = 0;
  3113. }
  3114. public function indentStr($n = 0) {
  3115. return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
  3116. }
  3117. public function property($name, $value) {
  3118. return $name . $this->assignSeparator . $value . ";";
  3119. }
  3120. public function block($block) {
  3121. if (empty($block->lines) && empty($block->children)) return;
  3122. $inner = $pre = $this->indentStr();
  3123. if (!empty($block->selectors)) {
  3124. echo $pre .
  3125. implode($this->tagSeparator, $block->selectors) .
  3126. $this->open . $this->break;
  3127. $this->indentLevel++;
  3128. $inner = $this->indentStr();
  3129. }
  3130. if (!empty($block->lines)) {
  3131. $glue = $this->break.$inner;
  3132. echo $inner . implode($glue, $block->lines);
  3133. if (!empty($block->children)) {
  3134. echo $this->break;
  3135. }
  3136. }
  3137. foreach ($block->children as $child) {
  3138. $this->block($child);
  3139. }
  3140. if (!empty($block->selectors)) {
  3141. $this->indentLevel--;
  3142. if (empty($block->children)) echo $this->break;
  3143. echo $pre . $this->close . $this->break;
  3144. }
  3145. }
  3146. }
  3147. class scss_formatter_nested extends scss_formatter {
  3148. public $close = " }";
  3149. // adjust the depths of all children, depth first
  3150. public function adjustAllChildren($block) {
  3151. // flatten empty nested blocks
  3152. $children = array();
  3153. foreach ($block->children as $i => $child) {
  3154. if (empty($child->lines) && empty($child->children)) {
  3155. if (isset($block->children[$i + 1])) {
  3156. $block->children[$i + 1]->depth = $child->depth;
  3157. }
  3158. continue;
  3159. }
  3160. $children[] = $child;
  3161. }
  3162. $count = count($children);
  3163. for ($i = 0; $i < $count; $i++) {
  3164. $depth = $children[$i]->depth;
  3165. $j = $i + 1;
  3166. if (isset($children[$j]) && $depth < $children[$j]->depth) {
  3167. $childDepth = $children[$j]->depth;
  3168. for (; $j < $count; $j++) {
  3169. if ($depth < $children[$j]->depth && $childDepth >= $children[$j]->depth) {
  3170. $children[$j]->depth = $depth + 1;
  3171. }
  3172. }
  3173. }
  3174. }
  3175. $block->children = $children;
  3176. // make relative to parent
  3177. foreach ($block->children as $child) {
  3178. $this->adjustAllChildren($child);
  3179. $child->depth = $child->depth - $block->depth;
  3180. }
  3181. }
  3182. public function block($block) {
  3183. if ($block->type == "root") {
  3184. $this->adjustAllChildren($block);
  3185. }
  3186. $inner = $pre = $this->indentStr($block->depth - 1);
  3187. if (!empty($block->selectors)) {
  3188. echo $pre .
  3189. implode($this->tagSeparator, $block->selectors) .
  3190. $this->open . $this->break;
  3191. $this->indentLevel++;
  3192. $inner = $this->indentStr($block->depth - 1);
  3193. }
  3194. if (!empty($block->lines)) {
  3195. $glue = $this->break.$inner;
  3196. echo $inner . implode($glue, $block->lines);
  3197. if (!empty($block->children)) echo $this->break;
  3198. }
  3199. foreach ($block->children as $i => $child) {
  3200. // echo "*** block: ".$block->depth." child: ".$child->depth."\n";
  3201. $this->block($child);
  3202. if ($i < count($block->children) - 1) {
  3203. echo $this->break;
  3204. if (isset($block->children[$i + 1])) {
  3205. $next = $block->children[$i + 1];
  3206. if ($next->depth == max($block->depth, 1) && $child->depth >= $next->depth) {
  3207. echo $this->break;
  3208. }
  3209. }
  3210. }
  3211. }
  3212. if (!empty($block->selectors)) {
  3213. $this->indentLevel--;
  3214. echo $this->close;
  3215. }
  3216. if ($block->type == "root") {
  3217. echo $this->break;
  3218. }
  3219. }
  3220. }
  3221. class scss_formatter_compressed extends scss_formatter {
  3222. public $open = "{";
  3223. public $tagSeparator = ",";
  3224. public $assignSeparator = ":";
  3225. public $break = "";
  3226. public function indentStr($n = 0) {
  3227. return "";
  3228. }
  3229. }
  3230. class scss_server {
  3231. protected function join($left, $right) {
  3232. return rtrim($left, "/") . "/" . ltrim($right, "/");
  3233. }
  3234. protected function inputName() {
  3235. if (isset($_GET["p"])) return $_GET["p"];
  3236. if (isset($_SERVER["PATH_INFO"])) return $_SERVER["PATH_INFO"];
  3237. if (isset($_SERVER["DOCUMENT_URI"])) {
  3238. return substr($_SERVER["DOCUMENT_URI"], strlen($_SERVER["SCRIPT_NAME"]));
  3239. }
  3240. }
  3241. protected function findInput() {
  3242. if ($input = $this->inputName()) {
  3243. $name = $this->join($this->dir, $input);
  3244. if (is_readable($name)) return $name;
  3245. }
  3246. return false;
  3247. }
  3248. protected function cacheName($fname) {
  3249. return $this->join($this->cacheDir, md5($fname) . ".css");
  3250. }
  3251. protected function importsCacheName($out) {
  3252. return $out . ".imports";
  3253. }
  3254. protected function needsCompile($in, $out) {
  3255. if (!is_file($out)) return true;
  3256. $mtime = filemtime($out);
  3257. if (filemtime($in) > $mtime) return true;
  3258. // look for modified imports
  3259. $icache = $this->importsCacheName($out);
  3260. if (is_readable($icache)) {
  3261. $imports = unserialize(file_get_contents($icache));
  3262. foreach ($imports as $import) {
  3263. if (filemtime($import) > $mtime) return true;
  3264. }
  3265. }
  3266. return false;
  3267. }
  3268. protected function compile($in, $out) {
  3269. $start = microtime(true);
  3270. $css = $this->scss->compile(file_get_contents($in), $in);
  3271. $elapsed = round((microtime(true) - $start), 4);
  3272. $v = scssc::$VERSION;
  3273. $t = date("r");
  3274. $css = "/* compiled by scssphp $v on $t (${elapsed}s) */\n\n" . $css;
  3275. file_put_contents($out, $css);
  3276. file_put_contents($this->importsCacheName($out),
  3277. serialize($this->scss->getParsedFiles()));
  3278. return $css;
  3279. }
  3280. public function serve() {
  3281. if ($input = $this->findInput()) {
  3282. $output = $this->cacheName($input);
  3283. header("Content-type: text/css");
  3284. if ($this->needsCompile($input, $output)) {
  3285. try {
  3286. echo $this->compile($input, $output);
  3287. } catch (exception $e) {
  3288. header('HTTP/1.1 500 Internal Server Error');
  3289. echo "Parse error: " . $e->getMessage() . "\n";
  3290. }
  3291. } else {
  3292. header('X-SCSS-Cache: true');
  3293. echo file_get_contents($output);
  3294. }
  3295. return;
  3296. }
  3297. header('HTTP/1.0 404 Not Found');
  3298. header("Content-type: text");
  3299. $v = scssc::$VERSION;
  3300. echo "/* INPUT NOT FOUND scss $v */\n";
  3301. }
  3302. public function __construct($dir, $cacheDir=null, $scss=null) {
  3303. $this->dir = $dir;
  3304. if (is_null($cacheDir)) {
  3305. $cacheDir = $this->join($dir, "scss_cache");
  3306. }
  3307. $this->cacheDir = $cacheDir;
  3308. if (!is_dir($this->cacheDir)) mkdir($this->cacheDir);
  3309. if (is_null($scss)) {
  3310. $scss = new scssc();
  3311. $scss->setImportPaths($this->dir);
  3312. }
  3313. $this->scss = $scss;
  3314. }
  3315. static public function serveFrom($path) {
  3316. $server = new self($path);
  3317. $server->serve();
  3318. }
  3319. }