ZF\Apigility\Doctrine\Server\Resource\DoctrineResource::findEntity PHP Method

findEntity() protected method

Gets an entity by route params and/or the specified id
protected findEntity ( $id, $method, null | array $data = null ) : object
$id
$method
$data null | array parameters
return object
    protected function findEntity($id, $method, $data = null)
    {
        // Match identity identifier name(s) with id(s)
        $ids = explode($this->getMultiKeyDelimiter(), $id);
        $keys = explode($this->getMultiKeyDelimiter(), $this->getEntityIdentifierName());
        $criteria = [];
        if (count($ids) !== count($keys)) {
            return new ApiProblem(500, 'Invalid multi identifier count.  ' . count($ids) . ' must equal ' . count($keys));
        }
        foreach ($keys as $index => $identifier) {
            $criteria[$identifier] = $ids[$index];
        }
        $classMetaData = $this->getObjectManager()->getClassMetadata($this->getEntityClass());
        $routeMatch = $this->getEvent()->getRouteMatch();
        $associationMappings = $classMetaData->getAssociationNames();
        $fieldNames = $classMetaData->getFieldNames();
        $routeParams = $routeMatch->getParams();
        if (array_key_exists($this->getRouteIdentifierName(), $routeParams)) {
            unset($routeParams[$this->getRouteIdentifierName()]);
        }
        $reservedRouteParams = ['controller', 'action', ModuleRouteListener::MODULE_NAMESPACE, ModuleRouteListener::ORIGINAL_CONTROLLER];
        $allowedRouteParams = array_diff_key($routeParams, array_flip($reservedRouteParams));
        /**
         * Append query selection parameters by route match.
         */
        foreach ($allowedRouteParams as $routeMatchParam => $value) {
            if (in_array($routeMatchParam, $associationMappings) || in_array($routeMatchParam, $fieldNames)) {
                $criteria[$routeMatchParam] = $value;
            }
        }
        // Build query
        $queryProvider = $this->getQueryProvider($method);
        $queryBuilder = $queryProvider->createQuery($this->getEvent(), $this->getEntityClass(), $data);
        if ($queryBuilder instanceof ApiProblem) {
            return $queryBuilder;
        }
        // Add criteria
        foreach ($criteria as $key => $value) {
            if ($queryBuilder instanceof MongoDBQueryBuilder) {
                $queryBuilder->field($key)->equals($value);
            } else {
                $parameterName = 'a' . md5(rand());
                $queryBuilder->andwhere($queryBuilder->expr()->eq('row.' . $key, ":{$parameterName}"));
                $queryBuilder->setParameter($parameterName, $value);
            }
        }
        try {
            $entity = $queryBuilder->getQuery()->getSingleResult();
        } catch (NoResultException $e) {
            $entity = null;
        }
        if (!$entity) {
            $entity = new ApiProblem(404, 'Entity was not found');
        }
        return $entity;
    }