| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 /** |
| 6 * Pattern utilities for use with server.Router. |
| 7 * |
| 8 * Example: |
| 9 * |
| 10 * var router = new Router(server); |
| 11 * router.filter(matchesAny(new UrlPattern(r'/(\w+)'), |
| 12 * exclude: [new UrlPattern('/login')]), authFilter); |
| 13 */ |
| 14 library pattern; |
| 15 |
| 16 class _MultiPattern extends Pattern { |
| 17 final Iterable<Pattern> include; |
| 18 final Iterable<Pattern> exclude; |
| 19 |
| 20 _MultiPattern(Iterable<Pattern> this.include, |
| 21 {Iterable<Pattern> this.exclude}); |
| 22 |
| 23 Iterable<Match> allMatches(String str) { |
| 24 var _allMatches = []; |
| 25 for (var pattern in include) { |
| 26 var matches = pattern.allMatches(str); |
| 27 if (_hasMatch(matches)) { |
| 28 if (exclude != null) { |
| 29 for (var excludePattern in exclude) { |
| 30 if (_hasMatch(excludePattern.allMatches(str))) { |
| 31 return []; |
| 32 } |
| 33 } |
| 34 } |
| 35 _allMatches.add(matches); |
| 36 } |
| 37 } |
| 38 return _allMatches.expand((x) => x); |
| 39 } |
| 40 } |
| 41 |
| 42 /** |
| 43 * Returns a [Pattern] that matches against every pattern in [include] and |
| 44 * returns all the matches. If the input string matches against any pattern in |
| 45 * [exclude] no matches are returned. |
| 46 */ |
| 47 Pattern matchAny(Iterable<Pattern> include, {Iterable<Pattern> exclude}) => |
| 48 new _MultiPattern(include, exclude: exclude); |
| 49 |
| 50 /** |
| 51 * Returns true if [pattern] has a single match in [str] that matches the whole |
| 52 * string, not a substring. |
| 53 */ |
| 54 bool matchesFull(Pattern pattern, String str) { |
| 55 var iter = pattern.allMatches(str).iterator; |
| 56 if (iter.moveNext()) { |
| 57 var match = iter.current; |
| 58 return match.start == 0 && match.end == str.length && !iter.moveNext(); |
| 59 } |
| 60 return false; |
| 61 } |
| 62 |
| 63 bool matchesPrefix(Pattern pattern, String str) { |
| 64 Iterable<Match> matches = pattern.allMatches(str); |
| 65 return !matches.isEmpty && matches.first.start == 0; |
| 66 } |
| 67 |
| 68 /// return the tail |
| 69 Match prefixMatch(Pattern pattern, String str) { |
| 70 Iterable<Match> matches = pattern.allMatches(str); |
| 71 if (!matches.isEmpty && matches.first.start == 0) { |
| 72 return matches.first; |
| 73 } |
| 74 return null; |
| 75 } |
| 76 |
| 77 bool _hasMatch(Iterable<Match> matches) => matches.iterator.moveNext(); |
| OLD | NEW |