PageRenderTime 198ms CodeModel.GetById 34ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full 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 stat

Large files files are truncated, but you can click here to view the full file