Have filters add self as dependencies, rm whitespace.
[xhtml-compiler.git] / XHTMLCompiler / DOMFilter / AutoStyle.php
blob5fce17d5d1cfe42dd381c3da5522e4399f6ac44e
1 <?php
3 /**
4 * Automatically adds external style-sheet inclusions based on file
5 * naming conventions.
6 * @todo Extend this to also glob CSS files into one file for better
7 * downloads
8 */
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);
19 $manager->addDependency(__FILE__);
21 $preloaded = array();
22 $prefix = $page->getDirSName();
23 foreach ($links as $link) {
24 // ensure the link is importing CSS stylesheets
25 if ($link->getAttribute('rel') != 'stylesheet') continue;
26 if ($link->getAttribute('type') != 'text/css') continue;
27 $path = $link->getAttribute('href');
28 if (empty($path) || $path[0] === '/' || $path[0] === '.') {
29 // do not attempt to manage special paths
30 continue;
32 $preloaded[$prefix . $path] = true;
35 $dir = $page->getDir();
36 $css_files = $dir->scanFlat('.css');
37 $base = $page->getPathStem();
39 foreach ($css_files as $file) {
40 // determine whether or not it should be included
41 // TODO: extend this algorithm to allow different media
42 // types in form pagename.mediatype.css
43 if (strpos($file, $base) === 0) {
44 // if already included, don't re-include
45 if (isset($preloaded[$file])) continue;
46 $link = $dom->createElement('link');
47 $link->setAttribute('rel', 'stylesheet');
48 $link->setAttribute('type', 'text/css');
49 // because scanFlat() prepends the directory name to
50 // each of the files, in a web-context we need to remove
51 // it
52 $link->setAttribute('href', basename($file));
53 $head->appendChild($link);