/** * Generate query of particular entity list and search engine. * * @access public * @return SearchEngineGeneratedQueries * @since 1.0.0-alpha * @version 1.0.0-alpha */ public function generateQuery() { $oQuery = DB::queryBuilder()->select('t')->from($this->getModel()->getClass(), 't'); $aJoined = []; $iAlias = 0; $oForm = $this->getForm(); // if search engine form is submitted if ($oForm->isSubmitted()) { $aQueryParams = []; $aIgnoredQueryParams = []; foreach (array_keys($oForm->getFields()) as $sFieldName) { /* @var $oField Form\Field */ $mValue = $oForm->get($sFieldName); if ($mValue !== '') { $aQueryParams[$sFieldName] = $mValue; } else { $aIgnoredQueryParams[] = $sFieldName; } } $sURL = Router::currentUrlWithQueryParams($aQueryParams, $aIgnoredQueryParams); Router::relocate($sURL); } // if URL has any filters $aQueryParamsForSearch = Router::getQueryStringParams(); if (count($aQueryParamsForSearch) > 0) { foreach ($aQueryParamsForSearch as $sFieldName => $mValue) { // if value is not empty if (!is_array($mValue) && $mValue !== '' && $mValue !== NULL || is_array($mValue) && $mValue !== []) { // changing models for theirs IDs if (is_array($mValue)) { foreach ($mValue as &$oValue) { /* @var $oValue \Plethora\ModelCore */ if ($oValue instanceof ModelCore) { $oValue = $oValue->getId(); } } } elseif ($mValue instanceof ModelCore) { $mValue = $mValue->getId(); } // if field is from primary table if ($this->getModel()->getMetadata()->hasField($sFieldName)) { $oQuery->andWhere("t." . $sFieldName . " LIKE '%" . trim($mValue) . "%'"); } elseif ($this->getModel()->getMetadata()->hasAssociation($sFieldName)) { $sAssocTableAlias = 'a' . $sFieldName; if (is_array($mValue)) { $aConditions = []; foreach ($mValue as $mSingleValue) { $aConditions[] = $sAssocTableAlias . ".id ='" . trim($mSingleValue) . "'"; } $sCondition = implode(' OR ', $aConditions); } else { $sCondition = $sAssocTableAlias . ".id ='" . trim($mValue) . "'"; } $oQuery->join('t.' . $sFieldName, $sAssocTableAlias, \Doctrine\ORM\Query\Expr\Join::WITH, $sCondition); } else { $aRelFieldInfo = $this->getRelFieldInfo($sFieldName); if ($aRelFieldInfo !== FALSE) { if (!in_array($aRelFieldInfo->getVar(), $aJoined)) { $iAlias++; $sAlias = 't' . $iAlias; $aJoined[$sAlias] = $aRelFieldInfo->getVar(); $oQuery->join('t.' . $aRelFieldInfo->getVar(), $sAlias); } else { $sAlias = array_search($aRelFieldInfo->getVar(), $aJoined); } $oQuery->andWhere($sAlias . "." . $aRelFieldInfo->getOriginalName() . " LIKE '%" . trim($mValue) . "%'"); } } } } } $oQuery->orderBy('t.id', 'desc'); return SearchEngineGeneratedQueries::factory($oQuery); }