XPathExpression.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Gt\CssXPath;
  3. class XPathExpression {
  4. /** @var array<int, string> */
  5. private array $parts;
  6. private bool $hasElement = false;
  7. public function __construct(string $prefix) {
  8. $this->parts = [$prefix];
  9. }
  10. public function appendElement(string $element, bool $htmlMode):void {
  11. $this->parts[] = $htmlMode ? strtolower($element) : $element;
  12. $this->hasElement = true;
  13. }
  14. public function ensureElement():void {
  15. if($this->hasElement) {
  16. return;
  17. }
  18. $this->parts[] = "*";
  19. $this->hasElement = true;
  20. }
  21. public function appendFragment(string $fragment):void {
  22. $this->parts[] = $fragment;
  23. }
  24. public function markElementMissing():void {
  25. $this->hasElement = false;
  26. }
  27. public function prependToLast(string $prefix):void {
  28. $index = count($this->parts) - 1;
  29. $this->parts[$index] = $prefix . $this->parts[$index];
  30. }
  31. public function replaceInLast(string $search, string $replace):void {
  32. $index = count($this->parts) - 1;
  33. $this->parts[$index] = str_replace($search, $replace, $this->parts[$index]);
  34. }
  35. public function lastPartEndsWith(string $suffix):bool {
  36. $index = count($this->parts) - 1;
  37. return substr($this->parts[$index], -strlen($suffix)) === $suffix;
  38. }
  39. public function toString():string {
  40. return implode("", $this->parts);
  41. }
  42. }