default
[ class tree: default ] [ index: default ] [ all elements ]

Source for file CSSContentParser.php

Documentation is available at CSSContentParser.php

  1. <?php
  2.  
  3. /**
  4.  * CSSContentParser enables parsing & assertion running of HTML content via CSS selectors.
  5.  * 
  6.  * It works by converting the content to XHTML using tidy, rewriting the CSS selectors as XPath queries, and executing
  7.  * those using SimpeXML.
  8.  * 
  9.  * It was built to facilitate testing using PHPUnit and contains a number of assert methods that will throw PHPUnit
  10.  * assertion exception when applicable.
  11.  */
  12. class CSSContentParser extends Object {
  13.     protected $simpleXML = null;
  14.     
  15.     function __construct($content{
  16.         $CLI_content escapeshellarg($content);
  17.         $tidy = `echo $CLI_content | tidy -n -q -utf8 -asxhtml`;
  18.         $tidy str_replace('xmlns="http://www.w3.org/1999/xhtml"','',$tidy);
  19.         $tidy str_replace('&#160;','',$tidy);
  20.         $this->simpleXML = new SimpleXMLElement($tidy);
  21.     }
  22.         
  23.     /**
  24.      * Returns a number of SimpleXML elements that match the given CSS selector.
  25.      * Currently the selector engine only supports querying by tag, id, and classs
  26.      */
  27.     function getBySelector($selector{
  28.         $xpath $this->selector2xpath($selector);
  29.         return $this->simpleXML->xpath($xpath);
  30.     }
  31.     
  32.     /**
  33.      * Converts a CSS selector into an equivalent xpath expression.
  34.      * Currently the selector engine only supports querying by tag, id, and classs
  35.      */
  36.     function selector2xpath($selector{
  37.         $parts preg_split('/\\s+/'$selector);
  38.         $xpath "";
  39.         foreach($parts as $part{
  40.             if(preg_match('/^([A-Za-z][A-Za-z0-9]*)/'$part$matches)) {
  41.                 $xpath .= "//$matches[1]";
  42.             else {
  43.                 $xpath .= "//*";
  44.             }
  45.             $xfilters array();
  46.             if(preg_match('/#([^#.\[]+)/'$part$matches)) {
  47.                 $xfilters["@id='$matches[1]'";
  48.             }
  49.             if(preg_match('/\.([^#.\[]+)/'$part$matches)) {
  50.                 $xfilters["contains(@class,'$matches[1]')";
  51.             }
  52.             if($xfilters$xpath .= '[' implode(','$xfilters']';
  53.         }
  54.         return $xpath;        
  55.     }
  56.  
  57. }

blog comments powered by Disqus
Documentation generated on Fri, 13 Jun 2008 06:34:14 +1200 by phpDocumentor 1.3.2