| OLD | NEW |
| (Empty) | |
| 1 library url_template; |
| 2 |
| 3 import 'url_matcher.dart'; |
| 4 |
| 5 final _specialChars = new RegExp(r'[\\\(\)\$\^\.\+\[\]\{\}\|]'); |
| 6 |
| 7 /** |
| 8 * A reversible URL template class that can match/parse and reverse URL |
| 9 * templates like: /foo/:bar/baz |
| 10 */ |
| 11 class UrlTemplate implements UrlMatcher { |
| 12 List<String> _fields; |
| 13 RegExp _pattern; |
| 14 List _chunks; |
| 15 |
| 16 String toString() { |
| 17 return '$_pattern'; |
| 18 } |
| 19 |
| 20 UrlTemplate(String template) { |
| 21 _compileTemplate(template); |
| 22 } |
| 23 |
| 24 void _compileTemplate(String template) { |
| 25 template = template. |
| 26 replaceAllMapped(_specialChars, (m) => r'\' + m.group(0)); |
| 27 _fields = <String>[]; |
| 28 _chunks = []; |
| 29 var exp = new RegExp(r':([\w0-9]+)'); |
| 30 StringBuffer sb = new StringBuffer('^'); |
| 31 int start = 0; |
| 32 exp.allMatches(template).forEach((Match m) { |
| 33 var paramName = m.group(1); |
| 34 var txt = template.substring(start, m.start); |
| 35 _fields.add(paramName); |
| 36 _chunks.add(txt); |
| 37 _chunks.add((Map params) => params != null ? params[paramName] : null); |
| 38 sb.write(txt); |
| 39 sb.write(r'([^/?]+)'); |
| 40 start = m.end; |
| 41 }); |
| 42 if (start != template.length) { |
| 43 var txt = template.substring(start, template.length); |
| 44 sb.write(txt); |
| 45 _chunks.add(txt); |
| 46 } |
| 47 _pattern = new RegExp(sb.toString()); |
| 48 } |
| 49 |
| 50 UrlMatch match(String url) { |
| 51 var matches = _pattern.allMatches(url); |
| 52 if (matches.isEmpty) { |
| 53 return null; |
| 54 } |
| 55 var parameters = new Map(); |
| 56 Match match = matches.first; |
| 57 for (var i = 0; i < match.groupCount; i++) { |
| 58 parameters[_fields[i]] = match.group(i + 1); |
| 59 } |
| 60 var tail = url.substring(match.group(0).length); |
| 61 return new UrlMatch(match.group(0), tail, parameters); |
| 62 } |
| 63 |
| 64 String reverse({Map parameters, String tail: ''}) => |
| 65 _chunks.map((c) => c is Function ? c(parameters) : c).join() + tail; |
| 66 |
| 67 List<String> urlParameterNames() { |
| 68 return _fields; |
| 69 } |
| 70 } |
| OLD | NEW |