001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.web.converter;
017
018import com.jfinal.core.JFinal;
019import com.jfinal.core.converter.IConverter;
020import com.jfinal.core.converter.TypeConverter;
021import com.jfinal.kit.Func;
022import io.jboot.utils.StrUtil;
023
024import java.text.ParseException;
025
026public class TypeConverterFunc implements Func.F21<Class<?>, String, Object> {
027
028
029    @Override
030    public Object call(Class<?> type, String s) {
031        if (s == null) {
032            return null;
033        }
034
035        // mysql type: varchar, char, enum, set, text, tinytext, mediumtext, longtext
036        if (type == String.class) {
037//            return ("".equals(s) ? null : s);    // 用户在表单域中没有输入内容时将提交过来 "", 因为没有输入,所以要转成 null.
038            return StrUtil.isBlank(s) ? null : s.trim();
039        }
040        s = s.trim();
041        if ("".equals(s)) {    // 前面的 String跳过以后,所有的空字符串全都转成 null,  这是合理的
042            return null;
043        }
044
045        // 以上两种情况无需转换,直接返回, 注意, 本方法不接受null为 s 参数(经测试永远不可能传来null, 因为无输入传来的也是"")
046        //String.class提前处理
047
048        if (type.isEnum()) {
049            for (Enum<?> e : ((Class<? extends Enum<?>>) type).getEnumConstants()) {
050                if (e.name().equals(s)) {
051                    return e;
052                }
053            }
054        }
055
056        // --------
057        IConverter<?> converter = TypeConverter.me().getConverterMap().get(type);
058        if (converter != null) {
059            try {
060                return converter.convert(s);
061            } catch (ParseException e) {
062                throw new RuntimeException(e);
063            }
064        }
065        if (JFinal.me().getConstants().getDevMode()) {
066            throw new RuntimeException("Please add code in " + TypeConverter.class + ". The type can't be converted: " + type.getName());
067        } else {
068            throw new RuntimeException(type.getName() + " can not be converted, please use other type of attributes in your model!");
069        }
070    }
071}