pquery.url.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * pQuery plugin for parsing URL's and calling corresponding handlers.
  4. *
  5. * @package pQuery
  6. */
  7. /**
  8. * pQuery extension class for the 'url' plugin.
  9. *
  10. * @property string $url The current url, with slashes removed at begin and end.
  11. */
  12. class pQueryUrl extends pQuery {
  13. static $accepts = array('string' => 'parse_url');
  14. /**
  15. * @see pQuery::$variable_alias
  16. * @var string|array
  17. */
  18. static $variable_alias = 'url';
  19. /**
  20. * The current set of handlers, pointed to by regular expression patterns.
  21. *
  22. * The handler that is called for the current URL is the one corresponding
  23. * to the first pattern in this list that matches the URL.
  24. *
  25. * @var array
  26. */
  27. static $handlers = array();
  28. /**
  29. * Remove slashes at the begin and end of the URL.
  30. *
  31. * @param string $url The URL to parse.
  32. */
  33. function parse_url($url) {
  34. return preg_replace('%(^/|/$)%', '', $url);
  35. }
  36. /**
  37. * Add a handler function to a URL match.
  38. *
  39. * @param string $pattern The URL pattern to match.
  40. * @param callback $handler The handler to execute when the pattern is matched.
  41. */
  42. static function add_handler($pattern, $handler) {
  43. is_callable($handler) || self::error('Handler "%s" is not callable.', $handler);
  44. self::$handlers["%$pattern%"] = $handler;
  45. }
  46. /**
  47. * Add a list of handler functions to regexes.
  48. *
  49. * @param array $handlers The list of handlers to add, with regexes as keys.
  50. */
  51. static function add_handlers($handlers) {
  52. foreach( $handlers as $pattern => $handler )
  53. self::add_handler($pattern, $handler);
  54. }
  55. /**
  56. * Execute the handler of the first matching URL regex.
  57. *
  58. * @param string $path The path to add.
  59. * @param bool $relative Indicates whether the path is relative to the document root.
  60. */
  61. function handler() {
  62. foreach( self::$handlers as $pattern => $handler )
  63. if( preg_match($pattern, $this->url, $matches) )
  64. return call_user_func_array($handler, array_slice($matches, 1));
  65. self::error('URL "%s" has no handler.', $this->url);
  66. // @codeCoverageIgnoreStart
  67. }
  68. // @codeCoverageIgnoreEnd
  69. }
  70. /**
  71. * Shortcut constructor for {@link pQueryUrl}.
  72. *
  73. * @param string $url
  74. * @returns pQueryUrl A new URL instance.
  75. */
  76. function _url($url) {
  77. return pQuery::create('url', $url);
  78. }
  79. /*
  80. * Add plugin to pQuery
  81. */
  82. __p::extend('pQueryUrl', 'url');
  83. ?>