UNPKG

2.1 kBPlain TextView Raw
1import {Injectable} from "@angular/core";
2import {isDefined} from "./util";
3
4export abstract class TranslateParser {
5 /**
6 * Interpolates a string to replace parameters
7 * "This is a {{ key }}" ==> "This is a value", with params = { key: "value" }
8 * @param expr
9 * @param params
10 */
11 abstract interpolate(expr: string | Function, params?: any): string | undefined;
12
13 /**
14 * Gets a value from an object by composed key
15 * parser.getValue({ key1: { keyA: 'valueI' }}, 'key1.keyA') ==> 'valueI'
16 * @param target
17 * @param key
18 */
19 abstract getValue(target: any, key: string): any
20}
21
22@Injectable()
23export class TranslateDefaultParser extends TranslateParser {
24 templateMatcher: RegExp = /{{\s?([^{}\s]*)\s?}}/g;
25
26 public interpolate(expr: string | Function, params?: any): string {
27 let result: string;
28
29 if (typeof expr === 'string') {
30 result = this.interpolateString(expr, params);
31 } else if (typeof expr === 'function') {
32 result = this.interpolateFunction(expr, params);
33 } else {
34 // this should not happen, but an unrelated TranslateService test depends on it
35 result = expr as string;
36 }
37
38 return result;
39 }
40
41 getValue(target: any, key: string): any {
42 let keys = typeof key === 'string' ? key.split('.') : [key];
43 key = '';
44 do {
45 key += keys.shift();
46 if (isDefined(target) && isDefined(target[key]) && (typeof target[key] === 'object' || !keys.length)) {
47 target = target[key];
48 key = '';
49 } else if (!keys.length) {
50 target = undefined;
51 } else {
52 key += '.';
53 }
54 } while (keys.length);
55
56 return target;
57 }
58
59 private interpolateFunction(fn: Function, params?: any) {
60 return fn(params);
61 }
62
63 private interpolateString(expr: string, params?: any) {
64 if (!params) {
65 return expr;
66 }
67
68 return expr.replace(this.templateMatcher, (substring: string, b: string) => {
69 let r = this.getValue(params, b);
70 return isDefined(r) ? r : substring;
71 });
72 }
73}