001    /**
002     * Implements the CFML Function ArrayFilter
003     */
004    package railo.runtime.functions.arrays;
005    
006    import java.util.Iterator;
007    
008    import railo.commons.lang.CFTypes;
009    import railo.runtime.PageContext;
010    import railo.runtime.exp.ExpressionException;
011    import railo.runtime.exp.PageException;
012    import railo.runtime.functions.BIF;
013    import railo.runtime.op.Caster;
014    import railo.runtime.type.Array;
015    import railo.runtime.type.ArrayImpl;
016    import railo.runtime.type.FunctionArgument;
017    import railo.runtime.type.UDF;
018    
019    
020    public final class ArrayFilter extends BIF {
021    
022            private static final long serialVersionUID = 7710446268528845873L;
023    
024            public static Array call(PageContext pc , Array array, UDF filter) throws PageException {
025                    // check UDF return type
026                    int type = filter.getReturnType();
027                    if(type!=CFTypes.TYPE_BOOLEAN && type!=CFTypes.TYPE_ANY)
028                            throw new ExpressionException("invalid return type ["+filter.getReturnTypeAsString()+"] for UDF Filter; valid return types are [boolean,any]");
029                    
030                    // check UDF arguments
031                    FunctionArgument[] args = filter.getFunctionArguments();
032                    if(args.length>1)
033                            throw new ExpressionException("UDF filter has too many arguments ["+args.length+"], should have at maximum 1 argument");
034                    
035                    
036                    Array rtn=new ArrayImpl();
037                    Iterator<Object> it = array.valueIterator();
038                    Object value;
039                    while(it.hasNext()){
040                            value=it.next();
041                            if(Caster.toBooleanValue(filter.call(pc, new Object[]{value}, true)))
042                                    rtn.append(value);
043                    }
044                    return rtn;
045            }
046            
047            @Override
048            public Object invoke(PageContext pc, Object[] args) throws PageException {
049                    return call(pc,Caster.toArray(args[0]),Caster.toFunction(args[1]));
050            }
051    }