PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/src/QueryPath/CSS/DOMTraverser/PseudoClass.php

http://github.com/technosophos/querypath
PHP | 421 lines | 264 code | 25 blank | 132 comment | 64 complexity | 8006f645e4bbdb1fe869d474008c948b MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * @file
  4. *
  5. * PseudoClass class.
  6. *
  7. * This is the first pass in an experiment to break PseudoClass handling
  8. * out of the normal traversal. Eventually, this should become a
  9. * top-level pluggable registry that will allow custom pseudoclasses.
  10. * For now, though, we just handle the core pseudoclasses.
  11. */
  12. namespace QueryPath\CSS\DOMTraverser;
  13. use \QueryPath\CSS\NotImplementedException;
  14. use \QueryPath\CSS\EventHandler;
  15. /**
  16. * The PseudoClass handler.
  17. *
  18. */
  19. class PseudoClass {
  20. /**
  21. * Tests whether the given element matches the given pseudoclass.
  22. *
  23. * @param string $pseudoclass
  24. * The string name of the pseudoclass
  25. * @param resource $node
  26. * The DOMNode to be tested.
  27. * @param resource $scope
  28. * The DOMElement that is the active root for this node.
  29. * @param mixed $value
  30. * The optional value string provided with this class. This is
  31. * used, for example, in an+b psuedoclasses.
  32. * @retval boolean
  33. * TRUE if the node matches, FALSE otherwise.
  34. */
  35. public function elementMatches($pseudoclass, $node, $scope, $value = NULL) {
  36. $name = strtolower($pseudoclass);
  37. // Need to handle known pseudoclasses.
  38. switch($name) {
  39. case 'current':
  40. case 'past':
  41. case 'future':
  42. case 'visited':
  43. case 'hover':
  44. case 'active':
  45. case 'focus':
  46. case 'animated': // Last 3 are from jQuery
  47. case 'visible':
  48. case 'hidden':
  49. // These require a UA, which we don't have.
  50. case 'valid':
  51. case 'invalid':
  52. case 'required':
  53. case 'optional':
  54. case 'read-only':
  55. case 'read-write':
  56. // Since we don't know how to validate elements,
  57. // we can't supply these.
  58. case 'dir':
  59. // FIXME: I don't know how to get directionality info.
  60. case 'nth-column':
  61. case 'nth-last-column':
  62. // We don't know what a column is in most documents.
  63. // FIXME: Can we do this for HTML?
  64. case 'target':
  65. // This requires a location URL, which we don't have.
  66. return FALSE;
  67. case 'indeterminate':
  68. // Because sometimes screwing with people is fun.
  69. return (boolean) mt_rand(0, 1);
  70. case 'lang':
  71. // No value = exception.
  72. if (!isset($value)) {
  73. throw new NotImplementedException(":lang() requires a value.");
  74. }
  75. return $this->lang($node, $value);
  76. case 'any-link':
  77. return Util::matchesAttribute($node, 'href')
  78. || Util::matchesAttribute($node, 'src')
  79. || Util::matchesAttribute($node, 'link');
  80. case 'link':
  81. return Util::matchesAttribute($node, 'href');
  82. case 'local-link':
  83. return $this->isLocalLink($node);
  84. case 'root':
  85. return $node->isSameNode($node->ownerDocument->documentElement);
  86. // CSS 4 declares the :scope pseudo-class, which describes what was
  87. // the :x-root QueryPath extension.
  88. case 'x-root':
  89. case 'x-reset':
  90. case 'scope':
  91. return $node->isSameNode($scope);
  92. // NON-STANDARD extensions for simple support of even and odd. These
  93. // are supported by jQuery, FF, and other user agents.
  94. case 'even':
  95. return $this->isNthChild($node, 'even');
  96. case 'odd':
  97. return $this->isNthChild($node, 'odd');
  98. case 'nth-child':
  99. return $this->isNthChild($node, $value);
  100. case 'nth-last-child':
  101. return $this->isNthChild($node, $value, TRUE);
  102. case 'nth-of-type':
  103. return $this->isNthChild($node, $value, FALSE, TRUE);
  104. case 'nth-last-of-type':
  105. return $this->isNthChild($node, $value, TRUE, TRUE);
  106. case 'first-of-type':
  107. return $this->isFirstOfType($node);
  108. case 'last-of-type':
  109. return $this->isLastOfType($node);
  110. case 'only-of-type':
  111. return $this->isFirstOfType($node) && $this->isLastOfType($node);
  112. // Additional pseudo-classes defined in jQuery:
  113. case 'lt':
  114. // I'm treating this as "less than or equal to".
  115. $rule = sprintf('-n + %d', (int) $value);
  116. // $rule = '-n+15';
  117. return $this->isNthChild($node, $rule);
  118. case 'gt':
  119. // I'm treating this as "greater than"
  120. // return $this->nodePositionFromEnd($node) > (int) $value;
  121. return $this->nodePositionFromStart($node) > (int) $value;
  122. case 'nth':
  123. case 'eq':
  124. $rule = (int)$value;
  125. return $this->isNthChild($node, $rule);
  126. case 'first':
  127. return $this->isNthChild($node, 1);
  128. case 'first-child':
  129. return $this->isFirst($node);
  130. case 'last':
  131. case 'last-child':
  132. return $this->isLast($node);
  133. case 'only-child':
  134. return $this->isFirst($node) && $this->isLast($node);
  135. case 'empty':
  136. return $this->isEmpty($node);
  137. case 'parent':
  138. return !$this->isEmpty($node);
  139. case 'enabled':
  140. case 'disabled':
  141. case 'checked':
  142. return Util::matchesAttribute($node, $name);
  143. case 'text':
  144. case 'radio':
  145. case 'checkbox':
  146. case 'file':
  147. case 'password':
  148. case 'submit':
  149. case 'image':
  150. case 'reset':
  151. case 'button':
  152. return Util::matchesAttribute($node, 'type', $name);
  153. case 'header':
  154. return $this->header($node);
  155. case 'has':
  156. case 'matches':
  157. return $this->has($node, $value);
  158. break;
  159. case 'not':
  160. if (empty($value)) {
  161. throw new ParseException(":not() requires a value.");
  162. }
  163. return $this->isNot($node, $value);
  164. // Contains == text matches.
  165. // In QP 2.1, this was changed.
  166. case 'contains':
  167. return $this->contains($node, $value);
  168. // Since QP 2.1
  169. case 'contains-exactly':
  170. return $this->containsExactly($node, $value);
  171. default:
  172. throw new \QueryPath\CSS\ParseException("Unknown Pseudo-Class: " . $name);
  173. }
  174. $this->findAnyElement = FALSE;
  175. }
  176. /**
  177. * Pseudo-class handler for :lang
  178. *
  179. * Note that this does not implement the spec in its entirety because we do
  180. * not presume to "know the language" of the document. If anyone is interested
  181. * in making this more intelligent, please do so.
  182. */
  183. protected function lang($node, $value) {
  184. // TODO: This checks for cases where an explicit language is
  185. // set. The spec seems to indicate that an element should inherit
  186. // language from the parent... but this is unclear.
  187. $operator = (strpos($value, '-') !== FALSE) ? EventHandler::isExactly : EventHandler::containsWithHyphen;
  188. $match = TRUE;
  189. foreach ($node->attributes as $attrNode) {
  190. if ($attrNode->localName == 'lang') {
  191. if ($attrNode->nodeName == $attrNode->localName) {
  192. // fprintf(STDOUT, "%s in NS %s\n", $attrNode->name, $attrNode->nodeName);
  193. return Util::matchesAttribute($node, 'lang', $value, $operator);
  194. }
  195. else {
  196. $nsuri = $attrNode->namespaceURI;
  197. // fprintf(STDOUT, "%s in NS %s\n", $attrNode->name, $nsuri);
  198. return Util::matchesAttributeNS($node, 'lang', $nsuri, $value, $operator);
  199. }
  200. }
  201. }
  202. return FALSE;
  203. }
  204. /**
  205. * Provides jQuery pseudoclass ':header'.
  206. */
  207. protected function header($node) {
  208. return preg_match('/^h[1-9]$/i', $node->tagName) == 1;
  209. }
  210. /**
  211. * Provides pseudoclass :empty.
  212. */
  213. protected function isEmpty($node) {
  214. foreach ($node->childNodes as $kid) {
  215. // We don't want to count PIs and comments. From the spec, it
  216. // appears that CDATA is also not counted.
  217. if ($kid->nodeType == XML_ELEMENT_NODE || $kid->nodeType == XML_TEXT_NODE) {
  218. // As soon as we hit a FALSE, return.
  219. return FALSE;
  220. }
  221. }
  222. return TRUE;
  223. }
  224. /**
  225. * Provides jQuery pseudoclass :first.
  226. *
  227. * @todo
  228. * This can be replaced by isNthChild().
  229. */
  230. protected function isFirst($node) {
  231. while (isset($node->previousSibling)) {
  232. $node = $node->previousSibling;
  233. if ($node->nodeType == XML_ELEMENT_NODE) {
  234. return FALSE;
  235. }
  236. }
  237. return TRUE;
  238. }
  239. /**
  240. * Fast version of first-of-type.
  241. */
  242. protected function isFirstOfType($node) {
  243. $type = $node->tagName;
  244. while (isset($node->previousSibling)) {
  245. $node = $node->previousSibling;
  246. if ($node->nodeType == XML_ELEMENT_NODE && $node->tagName == $type) {
  247. return FALSE;
  248. }
  249. }
  250. return TRUE;
  251. }
  252. /**
  253. * Fast version of jQuery :last.
  254. */
  255. protected function isLast($node) {
  256. while (isset($node->nextSibling)) {
  257. $node = $node->nextSibling;
  258. if ($node->nodeType == XML_ELEMENT_NODE) {
  259. return FALSE;
  260. }
  261. }
  262. return TRUE;
  263. }
  264. /**
  265. * Provides last-of-type.
  266. */
  267. protected function isLastOfType($node) {
  268. $type = $node->tagName;
  269. while (isset($node->nextSibling)) {
  270. $node = $node->nextSibling;
  271. if ($node->nodeType == XML_ELEMENT_NODE && $node->tagName == $type) {
  272. return FALSE;
  273. }
  274. }
  275. return TRUE;
  276. }
  277. /**
  278. * Provides :contains() as the original spec called for.
  279. *
  280. * This is an INEXACT match.
  281. */
  282. protected function contains($node, $value) {
  283. $text = $node->textContent;
  284. $value = Util::removeQuotes($value);
  285. return isset($text) && (stripos($text, $value) !== FALSE);
  286. }
  287. /**
  288. * Provides :contains-exactly QueryPath pseudoclass.
  289. *
  290. * This is an EXACT match.
  291. */
  292. protected function containsExactly($node, $value) {
  293. $text = $node->textContent;
  294. $value = Util::removeQuotes($value);
  295. return isset($text) && $text == $value;
  296. }
  297. /**
  298. * Provides :has pseudoclass.
  299. */
  300. protected function has($node, $selector) {
  301. $splos = new \SPLObjectStorage();
  302. $splos->attach($node);
  303. $traverser = new \QueryPath\CSS\DOMTraverser($splos, TRUE);
  304. $results = $traverser->find($selector)->matches();
  305. return count($results) > 0;
  306. }
  307. /**
  308. * Provides :not pseudoclass.
  309. */
  310. protected function isNot($node, $selector) {
  311. return !$this->has($node, $selector);
  312. }
  313. /**
  314. * Get the relative position of a node in its sibling set.
  315. */
  316. protected function nodePositionFromStart($node, $byType = FALSE) {
  317. $i = 1;
  318. $tag = $node->tagName;
  319. while (isset($node->previousSibling)) {
  320. $node = $node->previousSibling;
  321. if ($node->nodeType == XML_ELEMENT_NODE && (!$byType || $node->tagName == $tag)) {
  322. ++$i;
  323. }
  324. }
  325. return $i;
  326. }
  327. /**
  328. * Get the relative position of a node in its sibling set.
  329. */
  330. protected function nodePositionFromEnd($node, $byType = FALSE) {
  331. $i = 1;
  332. $tag = $node->tagName;
  333. while (isset($node->nextSibling)) {
  334. $node = $node->nextSibling;
  335. if ($node->nodeType == XML_ELEMENT_NODE && (!$byType || $node->tagName == $tag)) {
  336. ++$i;
  337. }
  338. }
  339. return $i;
  340. }
  341. /**
  342. * Provides functionality for all "An+B" rules.
  343. * Provides nth-child and also the functionality required for:
  344. *
  345. *- nth-last-child
  346. *- even
  347. *- odd
  348. *- first
  349. *- last
  350. *- eq
  351. *- nth
  352. *- nth-of-type
  353. *- first-of-type
  354. *- last-of-type
  355. *- nth-last-of-type
  356. *
  357. * See also QueryPath::CSS::DOMTraverser::Util::parseAnB().
  358. */
  359. protected function isNthChild($node, $value, $reverse = FALSE, $byType = FALSE) {
  360. list($groupSize, $elementInGroup) = Util::parseAnB($value);
  361. $parent = $node->parentNode;
  362. if (empty($parent)
  363. || ($groupSize == 0 && $elementInGroup == 0)
  364. || ($groupSize > 0 && $elementInGroup > $groupSize)
  365. ) {
  366. return FALSE;
  367. }
  368. // First we need to find the position of $node in other elements.
  369. if ($reverse) {
  370. $pos = $this->nodePositionFromEnd($node, $byType);
  371. }
  372. else {
  373. $pos = $this->nodePositionFromStart($node, $byType);
  374. }
  375. // If group size is 0, we just check to see if this
  376. // is the nth element:
  377. if ($groupSize == 0) {
  378. return $pos == $elementInGroup;
  379. }
  380. // Next, we normalize $elementInGroup
  381. if ($elementInGroup < 0) {
  382. $elementInGroup = $groupSize + $elementInGroup;
  383. }
  384. $prod = ($pos - $elementInGroup) / $groupSize;
  385. // fprintf(STDOUT, "%d n + %d on %d is %3.5f\n", $groupSize, $elementInGroup, $pos, $prod);
  386. return is_int($prod) && $prod >= 0;
  387. }
  388. protected function isLocalLink($node) {
  389. if (!$node->hasAttribute('href')) {
  390. return FALSE;
  391. }
  392. $url = $node->getAttribute('href');
  393. $scheme = parse_url($url, PHP_URL_SCHEME);
  394. return empty($scheme) || $scheme == 'file';
  395. }
  396. }