PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/mkalkbrenner/querypath
PHP | 420 lines | 265 code | 25 blank | 130 comment | 64 complexity | b5da98e962990ebe6f7744cb015c02e2 MD5 | raw file
  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. case 'nth':
  122. case 'eq':
  123. $rule = (int)$value;
  124. return $this->isNthChild($node, $rule);
  125. case 'first':
  126. return $this->isNthChild($node, 1);
  127. case 'first-child':
  128. return $this->isFirst($node);
  129. case 'last':
  130. case 'last-child':
  131. return $this->isLast($node);
  132. case 'only-child':
  133. return $this->isFirst($node) && $this->isLast($node);
  134. case 'empty':
  135. return $this->isEmpty($node);
  136. case 'parent':
  137. return !$this->isEmpty($node);
  138. case 'enabled':
  139. case 'disabled':
  140. case 'checked':
  141. return Util::matchesAttribute($node, $name);
  142. case 'text':
  143. case 'radio':
  144. case 'checkbox':
  145. case 'file':
  146. case 'password':
  147. case 'submit':
  148. case 'image':
  149. case 'reset':
  150. case 'button':
  151. return Util::matchesAttribute($node, 'type', $name);
  152. case 'header':
  153. return $this->header($node);
  154. case 'has':
  155. case 'matches':
  156. return $this->has($node, $value);
  157. break;
  158. case 'not':
  159. if (empty($value)) {
  160. throw new ParseException(":not() requires a value.");
  161. }
  162. return $this->isNot($node, $value);
  163. // Contains == text matches.
  164. // In QP 2.1, this was changed.
  165. case 'contains':
  166. return $this->contains($node, $value);
  167. // Since QP 2.1
  168. case 'contains-exactly':
  169. return $this->containsExactly($node, $value);
  170. default:
  171. throw new \QueryPath\CSS\ParseException("Unknown Pseudo-Class: " . $name);
  172. }
  173. $this->findAnyElement = FALSE;
  174. }
  175. /**
  176. * Pseudo-class handler for :lang
  177. *
  178. * Note that this does not implement the spec in its entirety because we do
  179. * not presume to "know the language" of the document. If anyone is interested
  180. * in making this more intelligent, please do so.
  181. */
  182. protected function lang($node, $value) {
  183. // TODO: This checks for cases where an explicit language is
  184. // set. The spec seems to indicate that an element should inherit
  185. // language from the parent... but this is unclear.
  186. $operator = (strpos($value, '-') !== FALSE) ? EventHandler::isExactly : EventHandler::containsWithHyphen;
  187. $match = TRUE;
  188. foreach ($node->attributes as $attrNode) {
  189. if ($attrNode->localName == 'lang') {
  190. if ($attrNode->nodeName == $attrNode->localName) {
  191. // fprintf(STDOUT, "%s in NS %s\n", $attrNode->name, $attrNode->nodeName);
  192. return Util::matchesAttribute($node, 'lang', $value, $operator);
  193. }
  194. else {
  195. $nsuri = $attrNode->namespaceURI;
  196. // fprintf(STDOUT, "%s in NS %s\n", $attrNode->name, $nsuri);
  197. return Util::matchesAttributeNS($node, 'lang', $nsuri, $value, $operator);
  198. }
  199. }
  200. }
  201. return FALSE;
  202. }
  203. /**
  204. * Provides jQuery pseudoclass ':header'.
  205. */
  206. protected function header($node) {
  207. return preg_match('/^h[1-9]$/i', $node->tagName) == 1;
  208. }
  209. /**
  210. * Provides pseudoclass :empty.
  211. */
  212. protected function isEmpty($node) {
  213. foreach ($node->childNodes as $kid) {
  214. // We don't want to count PIs and comments. From the spec, it
  215. // appears that CDATA is also not counted.
  216. if ($kid->nodeType == XML_ELEMENT_NODE || $kid->nodeType == XML_TEXT_NODE) {
  217. // As soon as we hit a FALSE, return.
  218. return FALSE;
  219. }
  220. }
  221. return TRUE;
  222. }
  223. /**
  224. * Provides jQuery pseudoclass :first.
  225. *
  226. * @todo
  227. * This can be replaced by isNthChild().
  228. */
  229. protected function isFirst($node) {
  230. while (isset($node->previousSibling)) {
  231. $node = $node->previousSibling;
  232. if ($node->nodeType == XML_ELEMENT_NODE) {
  233. return FALSE;
  234. }
  235. }
  236. return TRUE;
  237. }
  238. /**
  239. * Fast version of first-of-type.
  240. */
  241. protected function isFirstOfType($node) {
  242. $type = $node->tagName;
  243. while (isset($node->previousSibling)) {
  244. $node = $node->previousSibling;
  245. if ($node->nodeType == XML_ELEMENT_NODE && $node->tagName == $type) {
  246. return FALSE;
  247. }
  248. }
  249. return TRUE;
  250. }
  251. /**
  252. * Fast version of jQuery :last.
  253. */
  254. protected function isLast($node) {
  255. while (isset($node->nextSibling)) {
  256. $node = $node->nextSibling;
  257. if ($node->nodeType == XML_ELEMENT_NODE) {
  258. return FALSE;
  259. }
  260. }
  261. return TRUE;
  262. }
  263. /**
  264. * Provides last-of-type.
  265. */
  266. protected function isLastOfType($node) {
  267. $type = $node->tagName;
  268. while (isset($node->nextSibling)) {
  269. $node = $node->nextSibling;
  270. if ($node->nodeType == XML_ELEMENT_NODE && $node->tagName == $type) {
  271. return FALSE;
  272. }
  273. }
  274. return TRUE;
  275. }
  276. /**
  277. * Provides :contains() as the original spec called for.
  278. *
  279. * This is an INEXACT match.
  280. */
  281. protected function contains($node, $value) {
  282. $text = $node->textContent;
  283. $value = Util::removeQuotes($value);
  284. return isset($text) && (stripos($text, $value) !== FALSE);
  285. }
  286. /**
  287. * Provides :contains-exactly QueryPath pseudoclass.
  288. *
  289. * This is an EXACT match.
  290. */
  291. protected function containsExactly($node, $value) {
  292. $text = $node->textContent;
  293. $value = Util::removeQuotes($value);
  294. return isset($text) && $text == $value;
  295. }
  296. /**
  297. * Provides :has pseudoclass.
  298. */
  299. protected function has($node, $selector) {
  300. $splos = new \SPLObjectStorage();
  301. $splos->attach($node);
  302. $traverser = new \QueryPath\CSS\DOMTraverser($splos, TRUE);
  303. $results = $traverser->find($selector)->matches();
  304. return count($results) > 0;
  305. }
  306. /**
  307. * Provides :not pseudoclass.
  308. */
  309. protected function isNot($node, $selector) {
  310. return !$this->has($node, $selector);
  311. }
  312. /**
  313. * Get the relative position of a node in its sibling set.
  314. */
  315. protected function nodePositionFromStart($node, $byType = FALSE) {
  316. $i = 1;
  317. $tag = $node->tagName;
  318. while (isset($node->previousSibling)) {
  319. $node = $node->previousSibling;
  320. if ($node->nodeType == XML_ELEMENT_NODE && (!$byType || $node->tagName == $tag)) {
  321. ++$i;
  322. }
  323. }
  324. return $i;
  325. }
  326. /**
  327. * Get the relative position of a node in its sibling set.
  328. */
  329. protected function nodePositionFromEnd($node, $byType = FALSE) {
  330. $i = 1;
  331. $tag = $node->tagName;
  332. while (isset($node->nextSibling)) {
  333. $node = $node->nextSibling;
  334. if ($node->nodeType == XML_ELEMENT_NODE && (!$byType || $node->tagName == $tag)) {
  335. ++$i;
  336. }
  337. }
  338. return $i;
  339. }
  340. /**
  341. * Provides functionality for all "An+B" rules.
  342. * Provides ntoh-child and also the functionality required for:
  343. *
  344. *- nth-last-child
  345. *- even
  346. *- odd
  347. *- first
  348. *- last
  349. *- eq
  350. *- nth
  351. *- nth-of-type
  352. *- first-of-type
  353. *- last-of-type
  354. *- nth-last-of-type
  355. *
  356. * See also QueryPath::CSS::DOMTraverser::Util::parseAnB().
  357. */
  358. protected function isNthChild($node, $value, $reverse = FALSE, $byType = FALSE) {
  359. list($groupSize, $elementInGroup) = Util::parseAnB($value);
  360. $parent = $node->parentNode;
  361. if (empty($parent)
  362. || ($groupSize == 0 && $elementInGroup == 0)
  363. || ($groupSize > 0 && $elementInGroup > $groupSize)
  364. ) {
  365. return FALSE;
  366. }
  367. // First we need to find the position of $node in other elements.
  368. if ($reverse) {
  369. $pos = $this->nodePositionFromEnd($node, $byType);
  370. }
  371. else {
  372. $pos = $this->nodePositionFromStart($node, $byType);
  373. }
  374. // If group size is 0, we just check to see if this
  375. // is the nth element:
  376. if ($groupSize == 0) {
  377. return $pos == $elementInGroup;
  378. }
  379. // Next, we normalize $elementInGroup
  380. if ($elementInGroup < 0) {
  381. $elementInGroup = $groupSize + $elementInGroup;
  382. }
  383. $prod = ($pos - $elementInGroup) / $groupSize;
  384. // fprintf(STDOUT, "%d n + %d on %d is %3.5f\n", $groupSize, $elementInGroup, $pos, $prod);
  385. return is_int($prod) && $prod >= 0;
  386. }
  387. protected function isLocalLink($node) {
  388. if (!$node->hasAttribute('href')) {
  389. return FALSE;
  390. }
  391. $url = $node->getAttribute('href');
  392. $scheme = parse_url($url, PHP_URL_SCHEME);
  393. return empty($scheme) || $scheme == 'file';
  394. }
  395. }