1
votes

this seems like a simple question but I couldn't find the answer. If I have a component path "pathToComponent", how can I validate that it is valid? Right now I am resorting to using try/catch, but surely there is a more elegant way?

boolean function isValidComponent( required string pathToComponent ){

    try{
        var metaData = getComponentMetaData( arguments.pathToComponent );
        return true;
    }
    catch( any e ){
        return false;
    }
}

Thanks!

1
Is the pathToComponent coming through as an actual file path or dot notation? If an actual path you can do either a directoryExists() or fileExists(). If it's dot notation, you could replace the dots with slashes and fileExists()... - Jedihomer Townend
I was worried for situations where the pathToComponent is not the full path, but relative to either the calling or child component. That would break it. But maybe I should just require that pathToComponent be a full path. - user2943775
If you are referring to the ability to create an instance of a component, the try/catch approach is the best way. You should consider caching the result (serverside) though. - Alex
@AlexanderKwaschny, no, I was trying to check whether or not the path of the component exists (eg. "com.order.billing", "com.order.shipping"). Doing fileExists would require that the path be absolute rather than relative (eg. "billing" if calling from shipping.cfc). - user2943775

1 Answers

0
votes

If you want to test if the component path can be used to create a component, use:

boolean function isValidComponent( required string pathToComponent ) {

    try {

        createObject("component", ARGUMENTS.pathToComponent);
        return true;
    }
    catch(any) {
    }

    return false;
}

If you want to access the component physically, use:

string function getComponentLocation( required string pathToComponent ) {

    var normalizedPath  = replaceNoCase(ARGUMENTS.pathToComponent, ".", "/", "ALL");
    var resolvedPath    = expandPath(normalizedPath);
    var fileLocation    = (resolvedPath & ".cfc");

    return fileLocation;
}