function test() { $stream = new CSSStreamString(file_get_contents(dirname(__FILE__) . '/test.parser.5.css')); $lexer = new CSSLexer($stream); $parser = new CSSParser($lexer); $result = $parser->parse_ruleset(); $this->assertTrue($result); }
function testParserImportUriMediumSeq() { $stream = new CSSStreamString('@import url("sample.css") screen, print;'); $lexer = new CSSLexer($stream); $parser = new CSSParser($lexer); $result = $parser->parse(); $this->assertTrue($result); }
/** * **/ public function testMergeDeclarations() { $sFile = __DIR__ . '/files/merge.css'; $oParser = new CSSParser(); $oDoc = $oParser->parseString(file_get_contents($sFile)); $aDeclarations = $oDoc->getAllDeclarationBlocks(); $oMerged = CSSDocument::mergeDeclarations($aDeclarations); $sExpected = "{color: rgb(255,0,0);background: rgb(0,255,255) none repeat-x 0% 0% scroll;margin: 0 0 1em;}"; $this->assertEquals(trim($oMerged->__toString()), $sExpected); }
function test() { $stream = new CSSStreamString(file_get_contents(dirname(__FILE__) . '/test.parser.error.1.css')); $lexer = new CSSLexer($stream); $parser = new CSSParser($lexer); $result = $parser->parse(); $this->assertTrue($result); $errors = $parser->get_errors(); $this->assertEquals(count($errors), 1); $this->assertEquals($errors[0]->get_line(), 1); $this->assertEquals($errors[0]->get_skipped_content(), ';'); }
function test() { $stream = new CSSStreamString(file_get_contents(dirname(__FILE__) . '/test.parser.12.css')); $lexer = new CSSLexer($stream); $parser = new CSSParser($lexer); $result = $parser->parse(); $this->assertTrue($result); $syntax_stylesheet = $parser->get_context(); $rulesets = $syntax_stylesheet->get_rulesets()->get(); $this->assertEquals(count($rulesets), 2); $this->assertEquals($rulesets[0]->get_selectors()->get(0)->get_selector(0)->get_element(), 'ol'); $this->assertEquals($rulesets[1]->get_selectors()->get(0)->get_selector(0)->get_element(), 'ul'); }
private function getFontCssRules() { if (is_null($this->fontCssRules)) { $this->fontCssRules = array(); $cssAssets = $this->epub->EpubSpine->getAssetsByType('text/css'); foreach ($cssAssets as $css) { try { $cssContent = $this->epub->getPageContent($css->relativePath); $cssParser = new CSSParser($cssContent); $objCss = $cssParser->parse(); $this->fonts = array(); foreach ($objCss->getAllRuleSets() as $cssRuleSet) { $font = array(); if (is_a($cssRuleSet, 'CSSAtRule')) { $selectorName = $cssRuleSet->getType(); if ($selectorName == 'font-face') { foreach ($cssRuleSet->getRules() as $cssRule) { $value = (string) $cssRule->getValue(); if (substr($value, 0, 1) == '"') { $value = substr($value, 1, -1); } $font[$cssRule->getRule()] = $value; } $this->fontCssRules[] = $font; } } } unset($objCss); unset($cssParser); } catch (Exception $e) { CakeLog::warning('[EpubProcessor::getFontCssRules] Error ' . $e->getMessage() . ' when parsing ' . $css->relativePath); } } } return $this->fontCssRules; }
/** * @dataProvider testMSFiltersProvider **/ public function testMSFilters($sCss, $sExpected) { $oParser = new CSSParser(); $oDoc = $oParser->parseString($sCss); $this->assertEquals((string) $oDoc, $sExpected); }
public function cssIncludes() { $view = $this->view; $includes = ''; if (isset($view->css_includes)) { foreach ($view->css_includes as $url) { if (is_array($url)) { if (!isset($url['rel'])) { $url['rel'] = 'stylesheet'; } if (isset($url['href'])) { //$url['href'] = appendMTime($url['href']); $ret = CSSParser::run($url['href']); if ($ret && isset($ret['mtime'])) { $file = basename($url['href']); $dir = dirname($url['href']); $url['href'] = $dir . '/' . $ret['mtime'] . '-' . $file; } $includes .= '<link ' . formatParams($url) . ' />'; } } else { if ($url) { //$url = appendMTime($url); $ret = CSSParser::run($url); if ($ret && isset($ret['mtime'])) { $file = basename($url); $dir = dirname($url); $url = $dir . '/' . $ret['mtime'] . '-' . $file; } $includes .= '<link rel="stylesheet" href="' . $url . '" />'; } } } } $view->css_includes = $includes; return $includes; }
<?php include '../CSSParser.php'; $parser = new CSSParser(file_get_contents('../sh_style.css')); /** Results Array ( [0] => black [1] => #000000 ) */ print_r($parser->getProperty('pre.sh_sourceCode', 'color'));
/** * @dataProvider expandCreateShorthandsProvider * * @depends testExpandBorderShorthand * @depends testExpandDimensionsShorthand * @depends testExpandBackgroundShorthand * @depends testExpandFontShorthand * @depends testCreateBorderShorthand * @depends testCreateDimensionsShorthand * @depends testCreateBackgroundShorthand * @depends testCreateFontShorthand **/ public function testExpandCreateShorthands($sCss, $sExpected) { $oParser = new CSSParser(); $oDoc = $oParser->parseString($sCss); $oDoc->expandShorthands(); $oDoc->createShorthands(); $this->assertEquals((string) $oDoc, $sExpected); }
/** * @dataProvider createBackgroundShorthandProvider **/ public function testCreateBackgroundShorthand($sCss, $sExpected) { $oParser = new CSSParser($sCss); $oDoc = $oParser->parse(); foreach ($oDoc->getAllDeclarationBlocks() as $oDeclaration) { $oDeclaration->createBackgroundShorthand(); } $this->assertEquals((string) $oDoc, $sExpected); }
private static function mhtmlCompatable() { if (!isset(self::$mhtml)) { $ua = @$_SERVER['HTTP_USER_AGENT']; $mhtml = false; $mhtml_compatable = "/MSIE [67]\\.0/"; preg_match($mhtml_compatable, $ua, $matches); if ($matches) { $mhtml = true; } self::$mhtml = $mhtml; } return self::$mhtml; }
<?php include '../CSSParser.php'; $parser = new CSSParser(' @charset "UTF-8"; @import url("example/1.css"); @import url("example/2.css"); @page { margin-top: 2cm; margin-bottom: 2cm; } '); /** Results Array ( [0] => UTF-8 ) */ print_r($parser->getAtRule('@charset')); /** Results Array ( [0] => example/1.css [1] => example/2.css ) */ print_r($parser->getAtRule('@import')); /** Results
function parsedStructureForFile($sFileName) { $sFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . "{$sFileName}.css"; $oParser = new CSSParser(file_get_contents($sFile)); return $oParser->parse(); }
pre.sh_sourceCode .sh_underline { color : #006400 ; text-decoration : underline } pre.sh_sourceCode .sh_url { color : #0000FF ; color : #A68500 ; font-family : monospace ; font-style : normal ; font-weight : normal ; text-decoration : underline } pre.sh_sourceCode .sh_usertype { color : #008080 } pre.sh_sourceCode .sh_value { color : #006400 ; color : #A68500 ; font-style : italic ; font-style : normal ; font-weight : normal } pre.sh_sourceCode .sh_variable { color : #006400 ; color : #0080C0 ; font-style : normal ; font-weight : normal } */ echo CSSParser::minify(file_get_contents('../sh_style.css'), null, CSSParser::OUTPUT_FORMAT_BEATIFUL | CSSParser::OPTION_OVERRIDE_PROPERTY | CSSParser::COLOR_RGB_TO_HEX | CSSParser::COLOR_NAME_TO_HEX | CSSParser::COLOR_HEX_TO_MINIFY | CSSParser::OUTPUT_WITHOUT_LAST_DELIM);
/** * Post processes the parsed CSSDocument object. * * Handles removal of ignored values and resolving of @import rules. * * @todo Should CSSIgnoredValue exist ? * Another solution would be to add values only if they are not === null, * i.e. in CSSList::append(), CSSRule::addValue() etc... **/ private function postParse($oDoc) { $aCharsets = array(); $aImports = array(); $aContents = $oDoc->getContents(); foreach ($aContents as $i => $oItem) { if ($oItem instanceof CSSIgnoredValue) { unset($aContents[$i]); } else { if ($oItem instanceof CSSCharset) { $aCharsets[] = $oItem; unset($aContents[$i]); } else { if ($oItem instanceof CSSImport) { $aImports[] = $oItem; unset($aContents[$i]); } } } } $aImportedItems = array(); $aImportOptions = array_merge($this->getOptions(), array('output_encoding' => $this->sCharset, 'base_url' => null)); foreach ($aImports as $oImport) { if ($this->getOption('resolve_imports')) { $parser = new CSSParser($aImportOptions); $sPath = $oImport->getLocation()->getURL()->getString(); $bIsAbsUrl = CSSUrlUtils::isAbsUrl($sPath); if ($this->sImportMode == self::IMPORT_URL || $bIsAbsUrl) { if (!in_array($sPath, $this->aLoadedFiles)) { $oImportedDoc = $parser->parseURL($sPath, $this->aLoadedFiles); $this->aLoadedFiles = $parser->getLoadedFiles(); $aImportedContents = $oImportedDoc->getContents(); } } else { if ($this->sImportMode == self::IMPORT_FILE) { $sPath = realpath($sPath); if (!in_array($sPath, $this->aLoadedFiles)) { $oImportedDoc = $parser->parseFile($sPath, $this->aLoadedFiles); $this->aLoadedFiles = $parser->getLoadedFiles(); $aImportedContents = $oImportedDoc->getContents(); } } } if ($oImport->getMediaQuery() !== null) { $sMediaQuery = $oImport->getMediaQuery(); $oMediaQuery = new CSSMediaQuery(); $oMediaQuery->setQuery($sMediaQuery); $oMediaQuery->setContents($aImportedContents); $aImportedContents = array($oMediaQuery); } } else { $aImportedContents = array($oImport); } $aImportedItems = array_merge($aImportedItems, $aImportedContents); } $aContents = array_merge($aImportedItems, $aContents); if (isset($aCharsets[0])) { array_unshift($aContents, $aCharsets[0]); } $oDoc->setContents($aContents); }
<?php require_once dirname(__FILE__) . '/../CSSParser.php'; $oParser = new CSSParser(file_get_contents('php://stdin')); $oDoc = $oParser->parse(); echo '#### Structure (`var_dump()`)' . "\n"; var_dump($oDoc); echo '#### Output (`__toString()`)' . "\n"; print $oDoc->__toString(); echo "\n";
$valid_extensions = array('css', 'js', 'jpg', 'jpeg', 'png', 'gif', 'txt', 'htc'); $root = $_SERVER['DOCUMENT_ROOT']; if (!isset($_GET['path'])) { $path = ltrim($_SERVER['REQUEST_URI'], '/'); } else { $path = ltrim($_GET['path'], '/'); } $path = $root . '/' . $path; $ext = ltrim(strrchr($path, '.'), '.'); if (file_exists($path) && in_array($ext, $valid_extensions)) { $mime = ""; switch ($ext) { case "css": $mime = "text/css"; require_once $root . '/php/http/cssparser.class.php'; $cachedPath = CSSParser::getBuiltCssFileName($path); if (file_exists($cachedPath)) { $path = $cachedPath; } break; case "js": $mime = "text/javascript"; break; case "txt": $mime = "text/plain"; break; case "htc": //ie htc behavior files $mime = "text/x-component"; default: if (is_executable('/usr/bin/file')) {
function import_source_ruleset($css, $url) { $this->push_base_url($url); $property_collection = new CSSPropertyCollection(); $stream = new CSSStreamString(sprintf('* { %s }', $css)); $lexer = new CSSLexer($stream); $parser = new CSSParser($lexer); $result = $parser->parse_ruleset(); if (!$result) { error_log(sprintf('Unrecoverable syntax error while parsing stylesheet at "%s"', $url)); } $ruleset = $parser->get_context(); return $this->import_ruleset_body($ruleset); }
/** * Strip HTML tags, inline styles and convert input src to semantic, styled HTML and add page breaks and chapter entries to table of contents * @param $src str input HTML to be processed * @param $all bool true/false to strip ALL HTML tags * @return $str str stripped HTML */ function stripTagsAddChapters($src, $all = false) { $dom = new DOMDocument(); @$dom->loadHTML('<?xml encoding="UTF-8">' . $src); $xPath = new DOMXPath($dom); $elements = $xPath->query('//p'); foreach ($elements as $element) { if (strstr($element->getAttribute('class'), 'Heading1') !== FALSE) { $newElement = $dom->createElement('h1', $element->nodeValue); $element->parentNode->replaceChild($newElement, $element); } if (strstr($element->getAttribute('class'), 'Heading2') !== FALSE) { $newElement = $dom->createElement('h2', $element->nodeValue); $element->parentNode->replaceChild($newElement, $element); } if (strstr($element->getAttribute('class'), 'Heading3') !== FALSE) { $newElement = $dom->createElement('h3', $element->nodeValue); $element->parentNode->replaceChild($newElement, $element); } if (strstr($element->getAttribute('class'), 'Heading4') !== FALSE) { $newElement = $dom->createElement('h4', $element->nodeValue); $element->parentNode->replaceChild($newElement, $element); } } $elements = $xPath->query('//p|//span'); foreach ($elements as $element) { $oParser = new CSSParser("p{" . $element->getAttribute('style') . "}"); $oCss = $oParser->parse(); foreach ($oCss->getAllRuleSets() as $oRuleSet) { $oRuleSet->removeRule('line-'); $oRuleSet->removeRule('margin-'); $oRuleSet->removeRule('font-family'); $oRuleSet->removeRule('font-size'); $oRuleSet->removeRule('color'); if (is_array($indent) && isset($indent['text-indent'])) { $value = $indent['text-indent']->getValue(); if ($value != null) { $value->setSize('4'); $value->setUnit('mm'); } } } $css = $oCss->__toString(); $css = substr_replace($css, '', 0, 3); $css = substr_replace($css, '', -1, 1); $element->setAttribute('style', $css); } $src = $dom->saveHTML(); $search = array('@<script[^>]*?>.*?</script>@si', '@<style[^>]*?>.*?</style>@siU', '@<![\\s\\S]*?--[ \\t\\n\\r]*>@', '/(?si)<span\\s+class\\s*=\\s*"-H"\\s* style="letter-spacing: 0pt;">(.*?)<\\/span>/'); $src = preg_replace($search, array('', '', '', '$1'), $src); if ($all == false) { $src = strip_tags($src, "<p><br><img><span><strong><em><h1><h2><h3><h4>"); } else { $allow = "<p>"; $src = strip_tags($src, $allow); $src = $this->clean_inside_tags($src, $allow); $src = preg_replace('#<p[^>]*>(\\s| ?)*</p>#', '', $src); } $src = str_replace("#", "<br />", $src); $src = str_replace("***", "<br /><br />", $src); $src = preg_replace(array('/(?si)<h1(.*?)\\s*>(.*?)<\\/h1>/', '/(?si)<h2(.*?)\\s*>(.*?)<\\/h2>/', '/(?si)<h3(.*?)\\s*>(.*?)<\\/h3>/', '/(?si)<h4(.*?)\\s*>(.*?)<\\/h4>/'), array("<pagebreak /><h1>\$2<tocentry content='\$2' level='0' /></h1>", "<h2>\$2<tocentry content='\$2' level='1' /></h2>", '<h3>$2</h3>', '<h4>$2</h4>'), $src); return $src; }
<?php include '../CSSParser.php'; $parser = new CSSParser(file_get_contents('../sh_style.css')); /** Results Array ( [border-width] => Array ( [0] => 10px ) [color] => Array ( [0] => black [1] => #000000 ) [font-style] => Array ( [0] => normal [1] => normal ) [font-weight] => Array ( [0] => normal [1] => normal )
foreach ($c as $d) { $val |= $d; } $ind = isset($_POST['e']) === false || is_array($_POST['e']) ? 4000 : (int) $_POST['e']; $ind = $ind < 4000 || $ind > 4001 ? 4000 : $ind; switch ($ind) { case 4000: $ind = CSSParser::OUTPUT_INDENT_SPACE; break; case 4001: $ind = CSSParser::OUTPUT_INDENT_TAB; break; } $indsize = isset($_POST['f']) === false || is_array($_POST['f']) ? 4 : (int) $_POST['f']; $indsize = $indsize < 1 || $indsize > 16 ? 1 : $indsize; $data = CSSParser::minify($_POST['css'], $indsize, $format | $merge | $delim | $or | $prop | $val | $ind); echo $data; } ?> </textarea></p> <div style="padding:10px;"> <?php if (sizeof($_POST) > 0 && isset($_POST['css']) === true) { ?> <?php $percent = strlen($data) / (strlen($_POST['css']) === 0 ? 1 : strlen($_POST['css'])) * 100; ?> <h2>最適化率</h2> <div style="padding:10px;"> <p>最適化前のサイズ:<strong><?php echo number_format(strlen($_POST['css']));
/** * @dataProvider testResolveImportsProvider **/ public function testResolveImports($sFile, $sExpected) { $oParser = new CSSParser(array('resolve_imports' => true)); $oDoc = $oParser->parseFile($sFile); $this->assertEquals((string) $oDoc, $sExpected); }