Path: blob/master/src/infrastructure/parser/PhutilPygmentizeParser.php
12241 views
<?php12/**3* Parser that converts `pygmetize` output or similar HTML blocks from "class"4* attributes to "style" attributes.5*/6final class PhutilPygmentizeParser extends Phobject {78private $map = array();910public function setMap(array $map) {11$this->map = $map;12return $this;13}1415public function getMap() {16return $this->map;17}1819public function parse($block) {20$class_look = 'class="';21$class_len = strlen($class_look);2223$class_start = null;2425$map = $this->map;2627$len = strlen($block);28$out = '';29$mode = 'text';30for ($ii = 0; $ii < $len; $ii++) {31$c = $block[$ii];32switch ($mode) {33case 'text':34// We're in general text between tags, and just passing characers35// through unmodified.36if ($c == '<') {37$mode = 'tag';38}39$out .= $c;40break;41case 'tag':42// We're inside a tag, and looking for `class="` so we can rewrite43// it.44if ($c == '>') {45$mode = 'text';46}47if ($c == 'c') {48if (!substr_compare($block, $class_look, $ii, $class_len)) {49$mode = 'class';50$ii += $class_len;51$class_start = $ii;52}53}5455if ($mode != 'class') {56$out .= $c;57}58break;59case 'class':60// We're inside a `class="..."` tag, and looking for the ending quote61// so we can replace it.62if ($c == '"') {63$class = substr($block, $class_start, $ii - $class_start);6465// If this class is present in the map, rewrite it into an inline66// style attribute.67if (isset($map[$class])) {68$out .= 'style="'.phutil_escape_html($map[$class]).'"';69} else {70$out .= 'class="'.$class.'"';71}7273$mode = 'tag';74}75break;76}77}7879return $out;80}8182}838485