StaticDom.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace PHPHtmlParser;
  3. use PHPHtmlParser\Exceptions\NotLoadedException;
  4. /**
  5. * Class StaticDom
  6. *
  7. * @package PHPHtmlParser
  8. */
  9. final class StaticDom
  10. {
  11. private static $dom = null;
  12. /**
  13. * Attempts to call the given method on the most recent created dom
  14. * from bellow.
  15. *
  16. * @param string $method
  17. * @param array $arguments
  18. * @throws NotLoadedException
  19. * @return mixed
  20. */
  21. public static function __callStatic(string $method, array $arguments)
  22. {
  23. if (self::$dom instanceof Dom) {
  24. return call_user_func_array([self::$dom, $method], $arguments);
  25. } else {
  26. throw new NotLoadedException('The dom is not loaded. Can not call a dom method.');
  27. }
  28. }
  29. /**
  30. * Call this to mount the static facade. The facade allows you to use
  31. * this object as a $className.
  32. *
  33. * @param string $className
  34. * @param Dom $dom
  35. * @return bool
  36. */
  37. public static function mount(string $className = 'Dom', Dom $dom = null): bool
  38. {
  39. if (class_exists($className)) {
  40. return false;
  41. }
  42. class_alias(__CLASS__, $className);
  43. if ($dom instanceof Dom) {
  44. self::$dom = $dom;
  45. }
  46. return true;
  47. }
  48. /**
  49. * Creates a new dom object and calls load() on the
  50. * new object.
  51. *
  52. * @param string $str
  53. * @return Dom
  54. */
  55. public static function load(string $str): Dom
  56. {
  57. $dom = new Dom;
  58. self::$dom = $dom;
  59. return $dom->load($str);
  60. }
  61. /**
  62. * Creates a new dom object and calls loadFromFile() on the
  63. * new object.
  64. *
  65. * @param string $file
  66. * @return Dom
  67. */
  68. public static function loadFromFile(string $file): Dom
  69. {
  70. $dom = new Dom;
  71. self::$dom = $dom;
  72. return $dom->loadFromFile($file);
  73. }
  74. /**
  75. * Creates a new dom object and calls loadFromUrl() on the
  76. * new object.
  77. *
  78. * @param string $url
  79. * @param array $options
  80. * @param CurlInterface $curl
  81. * @return Dom
  82. */
  83. public static function loadFromUrl(string $url, array $options = [], CurlInterface $curl = null): Dom
  84. {
  85. $dom = new Dom;
  86. self::$dom = $dom;
  87. if (is_null($curl)) {
  88. // use the default curl interface
  89. $curl = new Curl;
  90. }
  91. return $dom->loadFromUrl($url, $options, $curl);
  92. }
  93. /**
  94. * Sets the $dom variable to null.
  95. */
  96. public static function unload(): void
  97. {
  98. self::$dom = null;
  99. }
  100. }