|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace TheFold\WordPress; |
| 4 | + |
| 5 | +class Dispatch { |
| 6 | + |
| 7 | + function __construct(array $url_callbacks, $priority = 5) { |
| 8 | + |
| 9 | + add_filter('rewrite_rules_array', function($rules) use ($url_callbacks) { |
| 10 | + |
| 11 | + foreach(array_keys($url_callbacks) as $look_for_in_url) { |
| 12 | + |
| 13 | + $newRule = ['^'.trim($look_for_in_url,'/').'/?$' => 'index.php?'.$this->query_var_name($look_for_in_url).'=1']; |
| 14 | + $rules = $newRule + $rules; |
| 15 | + } |
| 16 | + |
| 17 | + return $rules; |
| 18 | + }); |
| 19 | + |
| 20 | + add_filter('query_vars', function($qvars) use ($url_callbacks) { |
| 21 | + |
| 22 | + foreach(array_keys($url_callbacks) as $look_for_in_url) { |
| 23 | + |
| 24 | + $var = $this->query_var_name($look_for_in_url); |
| 25 | + $qvars[] = $var; |
| 26 | + } |
| 27 | + return $qvars; |
| 28 | + }); |
| 29 | + |
| 30 | + add_action( 'template_redirect', function() use ($url_callbacks) { |
| 31 | + |
| 32 | + global $wp_query; |
| 33 | + |
| 34 | + foreach($url_callbacks as $url_key => $callback) { |
| 35 | + |
| 36 | + if ( $wp_query->get( $this->query_var_name($url_key) ) ){ |
| 37 | + |
| 38 | + $wp_query->is_home = false; |
| 39 | + |
| 40 | + $params = null; |
| 41 | + |
| 42 | + preg_match('#'.trim($url_key,'/').'#',$_SERVER['REQUEST_URI'],$params); |
| 43 | + |
| 44 | + $res = call_user_func_array($callback,$params); |
| 45 | + |
| 46 | + if($res === false) |
| 47 | + $this->send_404(); |
| 48 | + else{ |
| 49 | + exit(); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + }, get_option('url_access_priority',$priority) ); |
| 54 | + |
| 55 | + add_action('init', function() use ($url_callbacks) { |
| 56 | + $this->maybe_flush_rewrites($url_callbacks); |
| 57 | + }, 99); |
| 58 | + } |
| 59 | + |
| 60 | + protected function maybe_flush_rewrites($url_callbacks) { |
| 61 | + |
| 62 | + $current = md5(json_encode(array_keys($url_callbacks))); |
| 63 | + |
| 64 | + $cached = get_option(get_called_class(), null ); |
| 65 | + |
| 66 | + if ( empty( $cached ) || $current !== $cached ) { |
| 67 | + flush_rewrite_rules(); |
| 68 | + update_option(get_called_class(), $current ); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + protected function query_var_name($rewrite) { |
| 73 | + |
| 74 | + static $cache; |
| 75 | + |
| 76 | + if(!isset($cache[$rewrite])){ |
| 77 | + $cache[$rewrite] = md5($rewrite); |
| 78 | + } |
| 79 | + |
| 80 | + return $cache[$rewrite]; |
| 81 | + } |
| 82 | + |
| 83 | + protected function send_404() { |
| 84 | + global $wp_query; |
| 85 | + status_header('404'); |
| 86 | + $wp_query->set_404(); |
| 87 | + } |
| 88 | +} |
0 commit comments