4 * Automatically adds external style-sheet inclusions based on file
6 * @todo Extend this to also glob CSS files into one file for better
9 class XHTMLCompiler_DOMFilter_AutoStyle
extends XHTMLCompiler_DOMFilter
12 protected $name = 'AutoStyle';
14 public function process(DOMDocument
$dom, $page, $manager) {
16 $head = $this->query("//html:head")->item(0);
17 $links = $this->query('link', $head);
20 $prefix = $page->getDirSName();
21 foreach ($links as $link) {
22 // ensure the link is importing CSS stylesheets
23 if ($link->getAttribute('rel') != 'stylesheet') continue;
24 if ($link->getAttribute('type') != 'text/css') continue;
25 $path = $link->getAttribute('href');
26 if (empty($path) ||
$path[0] === '/' ||
$path[0] === '.') {
27 // do not attempt to manage special paths
30 $preloaded[$prefix . $path] = true;
33 $dir = $page->getDir();
34 $css_files = $dir->scanFlat('.css');
35 $base = $page->getPathStem();
37 foreach ($css_files as $file) {
38 // determine whether or not it should be included
39 // TODO: extend this algorithm to allow different media
40 // types in form pagename.mediatype.css
41 if (strpos($file, $base) === 0) {
42 // if already included, don't re-include
43 if (isset($preloaded[$file])) continue;
44 $link = $dom->createElement('link');
45 $link->setAttribute('rel', 'stylesheet');
46 $link->setAttribute('type', 'text/css');
47 // because scanFlat() prepends the directory name to
48 // each of the files, in a web-context we need to remove
50 $link->setAttribute('href', basename($file));
51 $head->appendChild($link);