Finder.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace PHPHtmlParser;
  3. use PHPHtmlParser\Dom\AbstractNode;
  4. use PHPHtmlParser\Dom\InnerNode;
  5. class Finder
  6. {
  7. private $id;
  8. /**
  9. * Finder constructor.
  10. * @param $id
  11. */
  12. public function __construct($id)
  13. {
  14. $this->id = $id;
  15. }
  16. /**
  17. *
  18. * Find node in tree by id
  19. *
  20. * @param AbstractNode $node
  21. * @return bool|AbstractNode
  22. */
  23. public function find(AbstractNode $node)
  24. {
  25. if (!$node->id() && $node instanceof InnerNode) {
  26. return $this->find($node->firstChild());
  27. }
  28. if ($node->id() == $this->id) {
  29. return $node;
  30. }
  31. if ($node->hasNextSibling()) {
  32. $nextSibling = $node->nextSibling();
  33. if ($nextSibling->id() == $this->id) {
  34. return $nextSibling;
  35. }
  36. if ($nextSibling->id() > $this->id) {
  37. return $this->find($node->firstChild());
  38. }
  39. if ($nextSibling->id() < $this->id) {
  40. return $this->find($nextSibling);
  41. }
  42. } else if (!$node->isTextNode()) {
  43. return $this->find($node->firstChild());
  44. }
  45. return false;
  46. }
  47. }