pquery.url.php 2.0 KB

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