from plone import api
from Products.membrane import utils


def findImplementations(context, iface, **query):
    """The original method is just querying the portal catalog.
    This patch first checks if the query will not fail to find content
    in an obvious way
    """
    mt = api.portal.get_tool("membrane_tool")
    for key in ("exact_getUserId", "exact_getUserName", "exact_getGroupId"):
        if key in query:
            value = query[key]
            if isinstance(value, str):
                if value.strip() not in mt._catalog.getIndex(key)._index:
                    return []
    return mt.unrestrictedSearchResults(object_implements=iface.__identifier__, **query)


utils.findImplementations = findImplementations
