From 2a3280f268d89cfeaeffbc257044096df18ac702 Mon Sep 17 00:00:00 2001 From: macroxing Date: Sun, 27 Jan 2019 12:42:14 +0800 Subject: [PATCH] fix(Util): DO NOT process any non-string type value --- src/util/string.js | 20 ++++++++++++++++++++ test/util/string-spec.js | 16 ++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/util/string.js b/src/util/string.js index ff6e64ba63..9f16b06701 100644 --- a/src/util/string.js +++ b/src/util/string.js @@ -1,3 +1,6 @@ +import { warning } from './log'; +import { typeOf } from './object'; + /** * 将字符串转化为驼峰式写法 * @param {String} str 例:-webkit-transition @@ -16,6 +19,14 @@ export function camelcase (str) { * @return {String} 例:-webkit-transition */ export function hyphenate (str) { + if (typeof str !== 'string') { + warning( + '[ hyphenate(str: string): string ] ' + + `Expected arguments[0] to be a string but get a ${typeOf(str)}.` + + 'It will return an empty string without any processing.' + ); + return ''; + } return str.replace(/([A-Z])/g, $0 => `-${$0.toLowerCase()}`); } @@ -26,6 +37,15 @@ export function hyphenate (str) { * @return {String} 例: */ export function template (tpl, object = {}) { + if (typeof tpl !== 'string') { + warning( + '[ template(tpl: string, object: object): string ] ' + + `Expected arguments[0] to be a string but get a ${typeOf(tpl)}.` + + 'It will return an empty string without any processing.' + ); + return ''; + } + return tpl.replace(/\{[a-z]*\}/g, (str) => { const key = str.substring(1, str.length - 1); return object[key] || ''; diff --git a/test/util/string-spec.js b/test/util/string-spec.js index ad28b50074..b2fe52e21d 100644 --- a/test/util/string-spec.js +++ b/test/util/string-spec.js @@ -15,6 +15,14 @@ describe('src/string.js', function() { assert(string.hyphenate('transitionDelay') === 'transition-delay'); }); + it('string.hyphenate(str) should return empty string if arg[0] is not a string', function () { + assert(string.hyphenate() === ''); + assert(string.hyphenate(null) === ''); + assert(string.hyphenate([]) === ''); + assert(string.hyphenate({}) === ''); + assert(string.hyphenate(function() {}) === ''); + }) + it('camelcase can restore the result of hyphenate', function () { assert(string.camelcase(string.hyphenate('WebkitTransition')) === 'WebkitTransition'); }); @@ -22,4 +30,12 @@ describe('src/string.js', function() { it('string.template(tpl, obj) should return correct string', function () { assert(string.template('当前{current}, 共{total}页', { total: 3, current: 1}) === '当前1, 共3页'); }); + + it('string.template(tpl, obj) should return empty string if arg[0] is not a string', function () { + assert(string.template() === ''); + assert(string.template(null) === ''); + assert(string.template([]) === ''); + assert(string.template({}) === ''); + assert(string.template(function() {}) === ''); + }) });