Skip to content

Commit 2a3280f

Browse files
committed
fix(Util): DO NOT process any non-string type value
1 parent eea4cfa commit 2a3280f

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/util/string.js

+20
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import { warning } from './log';
2+
import { typeOf } from './object';
3+
14
/**
25
* 将字符串转化为驼峰式写法
36
* @param {String} str 例:-webkit-transition
@@ -16,6 +19,14 @@ export function camelcase (str) {
1619
* @return {String} 例:-webkit-transition
1720
*/
1821
export function hyphenate (str) {
22+
if (typeof str !== 'string') {
23+
warning(
24+
'[ hyphenate(str: string): string ] ' +
25+
`Expected arguments[0] to be a string but get a ${typeOf(str)}.` +
26+
'It will return an empty string without any processing.'
27+
);
28+
return '';
29+
}
1930
return str.replace(/([A-Z])/g, $0 => `-${$0.toLowerCase()}`);
2031
}
2132

@@ -26,6 +37,15 @@ export function hyphenate (str) {
2637
* @return {String} 例:
2738
*/
2839
export function template (tpl, object = {}) {
40+
if (typeof tpl !== 'string') {
41+
warning(
42+
'[ template(tpl: string, object: object): string ] ' +
43+
`Expected arguments[0] to be a string but get a ${typeOf(tpl)}.` +
44+
'It will return an empty string without any processing.'
45+
);
46+
return '';
47+
}
48+
2949
return tpl.replace(/\{[a-z]*\}/g, (str) => {
3050
const key = str.substring(1, str.length - 1);
3151
return object[key] || '';

test/util/string-spec.js

+16
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,27 @@ describe('src/string.js', function() {
1515
assert(string.hyphenate('transitionDelay') === 'transition-delay');
1616
});
1717

18+
it('string.hyphenate(str) should return empty string if arg[0] is not a string', function () {
19+
assert(string.hyphenate() === '');
20+
assert(string.hyphenate(null) === '');
21+
assert(string.hyphenate([]) === '');
22+
assert(string.hyphenate({}) === '');
23+
assert(string.hyphenate(function() {}) === '');
24+
})
25+
1826
it('camelcase can restore the result of hyphenate', function () {
1927
assert(string.camelcase(string.hyphenate('WebkitTransition')) === 'WebkitTransition');
2028
});
2129

2230
it('string.template(tpl, obj) should return correct string', function () {
2331
assert(string.template('当前{current}, 共{total}页', { total: 3, current: 1}) === '当前1, 共3页');
2432
});
33+
34+
it('string.template(tpl, obj) should return empty string if arg[0] is not a string', function () {
35+
assert(string.template() === '');
36+
assert(string.template(null) === '');
37+
assert(string.template([]) === '');
38+
assert(string.template({}) === '');
39+
assert(string.template(function() {}) === '');
40+
})
2541
});

0 commit comments

Comments
 (0)