all files / app/utils/ TranslateLocaleParser.ts

100% Statements 37/37
92% Branches 23/25
100% Functions 9/9
100% Lines 31/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57            1× 1× 1×   40× 1× 40× 40×   267× 267× 107×     160× 480× 83× 83×       1× 259× 259× 259× 286× 286× 205× 205× 81× 73×   8×       259×     170× 170× 170×       1×     655×    
/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */
 
import {Injectable} from "@angular/core";
import {TranslateParser} from "@ngx-translate/core";
import {TranslateClass} from "./pipes/translate";
 
@Injectable()
export class TranslateLocaleParser extends TranslateParser {
    templates = [/\{\{(.*?)\}\}/g, /\%\((.*?)\)s/g, /{([^{}]*)}/g];
    translateClass = new TranslateClass();
 
    public interpolate(expr: string, params?: any): string {
        if (typeof expr !== 'string' || !params) {
            return expr;
        }
 
        let translatedParams = this.translateParams(params || {});
        return this.templates.reduce((str, template) => str.replace(template, (substr: string, b: string) => {
            let r = this.getValue(translatedParams, b);
            return isDefined(r) ? r : substr;
        }), expr);
    }
 
    getValue(target: any, key: string): string {
        let keys = key.trim().split('.');
        key = '';
        do {
            key += keys.shift();
            if (isDefined(target) && isDefined(target[key]) && (typeof target[key] === 'object' || !keys.length)) {
                target = target[key];
                key = '';
            } else if (!keys.length) {
                target = undefined;
            } else {
                key += '.';
            }
        } while (keys.length);
 
        return target;
    }
 
    translateParams(params) {
        return Object.keys(params).reduce((newParams, key) =>
                (params[key] && typeof params[key] === 'object') ?
                    {...newParams, [key]: this.translateParams(params[key])} :
                    {...newParams, [key]: this.translateClass.transform(params[key])}, {});
    }
}
 
function isDefined(value) {
    return typeof value !== 'undefined' && value !== null;
}