/** * Check the constraint and execute the query * * @param QueryInterface $query * @param array $constraints * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface */ public function matchAndExecute(QueryInterface $query, array $constraints = []) { if ($constraints) { $query->matching($query->logicalAnd($constraints)); } return $query->execute(); }
/** * Returns an array of constraints created from a given demand object. * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param Tx_MooxNews_Domain_Model_DemandInterface $demand * @return array<\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface> */ protected function createConstraintsFromDemand(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query, Tx_MooxNews_Domain_Model_DemandInterface $demand) { $constraints = array(); // Storage page if ($demand->getStoragePage() != 0) { $pidList = \TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $demand->getStoragePage(), TRUE); $constraints[] = $query->in('pid', $pidList); } // Clean not used constraints foreach ($constraints as $key => $value) { if (is_null($value)) { unset($constraints[$key]); } } return $constraints; }
/** * Returns an array of constraints created from a given demand object. * * @param QueryInterface $query * @param DemandInterface $demand * @return array<\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface> */ protected function createConstraintsFromDemand(QueryInterface $query, DemandInterface $demand) { $constraints = array(); // Storage page if ($demand->getStoragePage() != 0) { $pidList = GeneralUtility::intExplode(',', $demand->getStoragePage(), TRUE); $constraints[] = $query->in('pid', $pidList); } // Clean not used constraints foreach ($constraints as $key => $value) { if (is_null($value)) { unset($constraints[$key]); } } return $constraints; }
/** * Returns the objects of this repository matching the given demand * * @param \SKYFILLERS\SfSimpleFaq\Domain\Model\Dto\FaqDemand $demand A demand * * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface */ public function findByDemand(FaqDemand $demand) { $this->query = $this->createQuery(); $this->generateCategories($demand); $this->generateSearchConstraints($demand); $this->buildQuery(); return $this->query->execute(); }
/** * @test */ public function magicCallMethodReturnsNullInFindOneBySomethingIfQueryReturnsEmptyRawResult() { $queryResultArray = array(); $this->mockQuery->expects($this->once())->method('equals')->with('foo', 'bar')->will($this->returnValue('matchCriteria')); $this->mockQuery->expects($this->once())->method('matching')->with('matchCriteria')->will($this->returnValue($this->mockQuery)); $this->mockQuery->expects($this->once())->method('setLimit')->with(1)->will($this->returnValue($this->mockQuery)); $this->mockQuery->expects($this->once())->method('execute')->will($this->returnValue($queryResultArray)); $this->assertNull($this->repository->findOneByFoo('bar')); }
/** * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param \DWenzel\T3events\Domain\Model\Dto\DemandInterface $demand * @return array */ public function createConstraintsFromDemand(QueryInterface $query, DemandInterface $demand) { /** @var ReservationDemand $demand */ $constraints = []; if ($demand->getLessonDeadline()) { $constraints[] = $query->logicalAnd($query->lessThan('lesson.deadline', $demand->getLessonDeadline())); } if ($demand->getStatus()) { $statusArr = GeneralUtility::intExplode(',', $demand->getStatus()); $statusConstraints = []; foreach ($statusArr as $status) { $statusConstraints[] = $query->equals('status', $status); } $constraints[] = $query->logicalOr($statusConstraints); } if ($demand->getMinAge()) { $constraints[] = $query->logicalAnd($query->lessThan('tstamp', time() - $demand->getMinAge())); } if ($demand->getLessonDate()) { if ($demand->getPeriod() === 'futureOnly') { $constraints[] = $query->greaterThanOrEqual('lesson.date', $demand->getLessonDate()); } elseif ($demand->getPeriod() === 'pastOnly') { $constraints[] = $query->lessThanOrEqual('lesson.date', $demand->getLessonDate()); } } if ((bool) ($genreConstraints = $this->createGenreConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $genreConstraints, $demand->getCategoryConjunction()); } if ((bool) ($searchConstraints = $this->createSearchConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $searchConstraints, 'OR'); } if ((bool) ($eventTypeConstraints = $this->createEventTypeConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $eventTypeConstraints, $demand->getCategoryConjunction()); } if ((bool) ($periodConstraints = $this->createPeriodConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $periodConstraints); } if ((bool) ($audienceConstraints = $this->createAudienceConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $audienceConstraints); } return $constraints; }
/** * sets query storage page(s) * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface &$query * @param array|integer|string $storagePages * @return void */ protected function setQueryStoragePages(QueryInterface &$query, $storagePages = NULL) { $query->getQuerySettings()->setRespectStoragePage(TRUE); if (is_string($storagePages)) { if ($storagePages == "all") { $query->getQuerySettings()->setRespectStoragePage(FALSE); } elseif (strpos($storagePages, ",") !== false) { $query->getQuerySettings()->setStoragePageIds(explode(",", $storagePages)); } } elseif (is_array($storagePages)) { $setStoragePages = []; foreach ($storagePages as $storagePage) { if (is_numeric($storagePage)) { $setStoragePages[] = $storagePage; } } if (count($setStoragePages)) { $query->getQuerySettings()->setStoragePageIds($setStoragePages); } } elseif (is_numeric($storagePages)) { $query->getQuerySettings()->setStoragePageIds(array($storagePages)); } }
/** * Pagination array gets build up * * @return array */ protected function buildPagination() { $pages = array(); $numberOfCharacters = count($this->characters); /* * Generates the pages and also checks if * the page has no objects */ for ($i = 0; $i < $numberOfCharacters; $i++) { $pages[] = array('linkCharacter' => str_replace(array('Ä', 'Ö', 'Ü'), array('AE', 'OE', 'UE'), $this->characters[$i]), 'character' => $this->characters[$i], 'isCurrent' => $this->characters[$i] === $this->currentCharacter, 'isEmpty' => 0 === $this->query->matching($this->query->like($this->field, $this->characters[$i] . '%'))->execute()->count()); } $pagination = array('pages' => $pages, 'current' => $this->currentCharacter, 'numberOfPages' => $numberOfCharacters, 'startCharacter' => $this->characters[0], 'endCharacter' => $this->characters[count($this->characters) + 1]); return $pagination; }
/** * Returns an array of constraints created from a given demand object. * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param \DWenzel\T3events\Domain\Model\Dto\DemandInterface $demand * @return array<\TYPO3\CMS\Extbase\Persistence\Generic\Qom\Constraint> */ public function createConstraintsFromDemand(QueryInterface $query, DemandInterface $demand) { /** @var \CPSIT\T3eventsReservation\Domain\Model\Dto\PersonDemand $demand */ $constraints = []; if ($demand->getTypes()) { $personTypes = explode(',', $demand->getTypes()); $personConstraints = []; foreach ($personTypes as $personType) { $personConstraints[] = $query->equals('type', $personType); } if (count($personConstraints)) { $constraints[] = $query->logicalAnd($personConstraints); } } if ($demand->getLessonDeadline()) { $constraints[] = $query->logicalAnd($query->lessThan('lesson.deadline', $demand->getLessonDeadline())); } if ($demand->getLessonDate()) { if ($demand->getLessonPeriod() === 'futureOnly') { $constraints[] = $query->greaterThanOrEqual('reservation.lesson.date', $demand->getLessonDate()); } elseif ($demand->getLessonPeriod() === 'pastOnly') { $constraints[] = $query->lessThanOrEqual('reservation.lesson.date', $demand->getLessonDate()); } } if ((bool) ($genreConstraints = $this->createGenreConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $genreConstraints, $demand->getCategoryConjunction()); } if ((bool) ($searchConstraints = $this->createSearchConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $searchConstraints, 'OR'); } if ((bool) ($eventTypeConstraints = $this->createEventTypeConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $eventTypeConstraints, $demand->getCategoryConjunction()); } if ((bool) ($categoryConstraints = $this->createCategoryConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $categoryConstraints, $demand->getCategoryConjunction()); } if ((bool) ($periodConstraints = $this->createPeriodConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $periodConstraints); } if ((bool) ($audienceConstraints = $this->createAudienceConstraints($query, $demand))) { $this->combineConstraints($query, $constraints, $audienceConstraints); } return $constraints; }
/** * Builds and returns the constraint for multi value properties. * * @param Persistence\QueryInterface $query * @param DomainObjectInterface $parentObject * @param string $propertyName * @param string $fieldValue * @param array $relationTableMatchFields * * @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint */ protected function getConstraint(Persistence\QueryInterface $query, DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $relationTableMatchFields = array()) { $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName); if ($columnMap->getParentKeyFieldName() !== null) { if ($columnMap->isRelationsOverriddenByTranslation()) { $constraint = $query->equals($columnMap->getParentKeyFieldName(), $parentObject->_getProperty('_localizedUid')); } else { $constraint = $query->equals($columnMap->getParentKeyFieldName(), $parentObject); } if ($columnMap->getParentTableFieldName() !== null) { $constraint = $query->logicalAnd($constraint, $query->equals($columnMap->getParentTableFieldName(), $this->getDataMap(get_class($parentObject))->getTableName())); } } else { $constraint = $query->in('uid', GeneralUtility::intExplode(',', $fieldValue)); } if (!empty($relationTableMatchFields)) { foreach ($relationTableMatchFields as $relationTableMatchFieldName => $relationTableMatchFieldValue) { $constraint = $query->logicalAnd($constraint, $query->equals($relationTableMatchFieldName, $relationTableMatchFieldValue)); } } return $constraint; }
/** * Returns a constraint array created by a given filter array * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param array $filter * @param array $constraints * @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface|null */ protected function createFilterConstraints(QueryInterface $query, $filter = NULL, $constraints = NULL) { if (is_null($constraints)) { $constraints = []; } if (isset($filter['uid_foreign']) && is_numeric($filter['uid_foreign']) && $filter['uid_foreign'] > 0 && isset($filter['tablenames']) && $filter['tablenames'] != "") { $constraints[] = $query->equals('uidForeign', $filter['uid_foreign']); $constraints[] = $query->equals('tablenames', $filter['tablenames']); } else { $constraints[] = $query->equals('uidForeign', 0); $constraints[] = $query->equals('tablenames', "dfgdfgjrezu67q348673463"); } if (isset($filter['feUser']) && is_numeric($filter['feUser']) && $filter['feUser'] > 0) { $constraints[] = $query->equals('feUser', $filter['feUser']); } $constraints[] = $query->greaterThan('confirmed', 0); if (count($constraints) < 1) { $constraints = NULL; } return $constraints; }
/** * This function builds the matchings. * It enables matchings like: * - single character: 'B' * - multiple characters: 'BDEFG' * - range of characters: 'B-G' * * @param string $characters * @return QueryInterface */ protected function getMatchings($characters = NULL) { $matching = array(); if ($characters === NULL) { $characters = $this->currentCharacter; } $characterLength = strlen($characters); if ($characterLength === 1) { // single character B $matching = $this->query->like($this->field, $characters . '%'); } else { if ($characterLength === 3 && $characters[1] === '-') { // range B-G // Build the characters like multiple characters B-G => BCDEFG // Fix orderings $firstCharacter = ord($characters[0]); $lastCharacter = ord($characters[2]); if ($firstCharacter - $lastCharacter > 0) { $tmp = $firstCharacter; $firstCharacter = $lastCharacter; $lastCharacter = $tmp; } // Build the new String $characters = ''; for ($char = $firstCharacter; $char <= $lastCharacter; ++$char) { $characters .= chr($char); } } // multiple characters BDEFG $characters = str_split($characters); foreach ($characters as $char) { $matching[] = $this->query->like($this->field, $char . '%'); } $matching = $this->query->logicalOr($matching); } return $this->query->matching($matching); }
/** * @param \GeorgRinger\Newsadvancedsearch\Domain\Model\Dto\Demand $demand * @param bool $respectEnableFields * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param array $constraints */ protected function updateConstraints(\GeorgRinger\Newsadvancedsearch\Domain\Model\Dto\Demand $demand, $respectEnableFields, \TYPO3\CMS\Extbase\Persistence\QueryInterface $query, array &$constraints) { $subject = $demand->getSubject(); if (!empty($subject)) { $constraints[] = $query->like('title', '%' . $subject . '%'); } $locations = $demand->getLocations(); if (!empty($locations)) { $locationConstraints = array(); foreach ($locations as $typeId) { $locationConstraints[] = $query->contains('locations', $typeId); } $constraints[] = $query->logicalOr($locationConstraints); } $types = $demand->getTypes(); if (!empty($types)) { $typesConstraints = array(); foreach ($types as $typeId) { $typesConstraints[] = $query->contains('eventtypes', $typeId); } $constraints[] = $query->logicalOr($typesConstraints); } }
/** * Sets the topEvent constraint to the given constraints array * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand * @param array $constraints Constraints * * @return void */ protected function setTopEventConstraint($query, $eventDemand, &$constraints) { if ($eventDemand->getTopEventRestriction() > 0) { $constraints[] = $query->equals('topEvent', (bool) ($eventDemand->getTopEventRestriction() - 1)); } }
/** * Returns a constraint array created by a given filter array * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param array $filter * @param array $constraints * @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface|null */ protected function createFilterConstraints(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query, $filter = NULL, $constraints = NULL) { if (is_null($constraints)) { $constraints = []; } if (isset($filter['uid_foreign']) && is_numeric($filter['uid_foreign']) && $filter['uid_foreign'] > 0 && isset($filter['tablenames']) && $filter['tablenames'] != "") { $constraints[] = $query->equals('uidForeign', $filter['uid_foreign']); $constraints[] = $query->equals('tablenames', $filter['tablenames']); } else { $constraints[] = $query->equals('uidForeign', 0); $constraints[] = $query->equals('tablenames', "dfgdfgjrezu67q348673463"); } if (isset($filter['feUser']) && is_numeric($filter['feUser']) && $filter['feUser'] > 0) { $constraints[] = $query->equals('feUser', $filter['feUser']); } if (!(isset($filter['isModerator']) && is_bool($filter['isModerator']) && $filter['isModerator'] == true)) { if (isset($filter['confirmed']) && is_bool($filter['confirmed']) && $filter['confirmed'] == true) { $constraints[] = $query->greaterThan('confirmed', 0); } else { $constraints[] = $query->logicalOr($query->equals('confirmed', 0), $query->equals('confirmed', ''), $query->equals('confirmed', NULL)); } } if (count($constraints) < 1) { $constraints = NULL; } return $constraints; }
/** * Returns the result of the query based on the given displaymode set in demand * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query The query * @param \DERHANSEN\SfBanners\Domain\Model\BannerDemand $demand The demand * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface */ protected function getResult(QueryInterface $query, BannerDemand $demand) { $result = array(); // Do not respect syslanguage since we search for uids - @see forge #47192 $query->getQuerySettings()->setRespectSysLanguage(false); switch ($demand->getDisplayMode()) { case 'all': $result = $query->execute(); break; case 'allRandom': $result = $this->objectManager->get('DERHANSEN\\SfBanners\\Persistence\\RandomQueryResult', $query); break; case 'random': $rows = $query->execute()->count(); $rowNumber = mt_rand(0, max(0, $rows - 1)); $result = $query->setOffset($rowNumber)->setLimit(1)->execute(); break; default: break; } return $result; }
/** * Get the search constraints * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param Tx_News_Domain_Model_DemandInterface $demand * @return array * @throws UnexpectedValueException */ protected function getSearchConstraints(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query, Tx_News_Domain_Model_DemandInterface $demand) { $constraints = array(); if ($demand->getSearch() === NULL) { return $constraints; } /* @var $searchObject Tx_News_Domain_Model_Dto_Search */ $searchObject = $demand->getSearch(); $searchSubject = $searchObject->getSubject(); if (!empty($searchSubject)) { $searchFields = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $searchObject->getFields(), TRUE); $searchConstraints = array(); if (count($searchFields) === 0) { throw new UnexpectedValueException('No search fields defined', 1318497755); } foreach ($searchFields as $field) { if (!empty($searchSubject)) { $searchConstraints[] = $query->like($field, '%' . $searchSubject . '%'); } } if (count($searchConstraints)) { $constraints[] = $query->logicalOr($searchConstraints); } } $minimumDate = strtotime($searchObject->getMinimumDate()); if ($minimumDate) { $field = $searchObject->getDateField(); if (empty($field)) { throw new UnexpectedValueException('No date field is defined', 1396348732); } $constraints[] = $query->greaterThanOrEqual($field, $minimumDate); } $maximumDate = strtotime($searchObject->getMaximumDate()); if ($maximumDate) { $field = $searchObject->getDateField(); if (empty($field)) { throw new UnexpectedValueException('No date field is defined', 1396348733); } $constraints[] = $query->lessThanOrEqual($field, $maximumDate); } return $constraints; }
/** * Adds handle of ordering to query object * * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @return void */ protected function handleOrdering(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) { $query->setOrderings(array($this->orderBy => $this->orderDirection)); }
/** * Parses the query and returns the SQL statement parts. * * @param QueryInterface $query The query * @return array The SQL statement parts */ public function parseQuery(QueryInterface $query) { $sql = array(); $sql['keywords'] = array(); $sql['tables'] = array(); $sql['unions'] = array(); $sql['fields'] = array(); $sql['where'] = array(); $sql['additionalWhereClause'] = array(); $sql['orderings'] = array(); $sql['limit'] = (int) $query->getLimit() ?: NULL; $sql['offset'] = (int) $query->getOffset() ?: NULL; $source = $query->getSource(); $this->parseSource($source, $sql); $this->parseConstraint($query->getConstraint(), $source, $sql); $this->parseOrderings($query->getOrderings(), $source, $sql); $tableNames = array_unique(array_keys($sql['tables'] + $sql['unions'])); foreach ($tableNames as $tableName) { if (is_string($tableName) && !empty($tableName)) { $this->addAdditionalWhereClause($query->getQuerySettings(), $tableName, $sql); } } return $sql; }
/** * Parses the query and returns the SQL statement parts. * * @param QueryInterface $query The query * @param array &$parameters * @return array The SQL statement parts */ public function parseQuery(QueryInterface $query, array &$parameters) { $statementParts = array(); $statementParts['keywords'] = array(); $statementParts['tables'] = array(); $statementParts['unions'] = array(); $statementParts['fields'] = array(); $statementParts['where'] = array(); $statementParts['additionalWhereClause'] = array(); $statementParts['orderings'] = array(); $statementParts['limit'] = array(); $source = $query->getSource(); $this->parseSource($source, $statementParts); $this->parseConstraint($query->getConstraint(), $source, $statementParts, $parameters); $this->parseOrderings($query->getOrderings(), $source, $statementParts); $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $statementParts); $tableNames = array_unique(array_keys($statementParts['tables'] + $statementParts['unions'])); foreach ($tableNames as $tableNameOrAlias) { if (is_string($tableNameOrAlias) && strlen($tableNameOrAlias) > 0) { $this->addAdditionalWhereClause($query->getQuerySettings(), $tableNameOrAlias, $statementParts); } } return $statementParts; }
/** * Returns the number of tuples matching the query. * * @param QueryInterface $query * @throws Exception\BadConstraintException * @return int The number of matching tuples * @throws SqlErrorException */ public function getObjectCountByQuery(QueryInterface $query) { if ($query->getConstraint() instanceof Qom\Statement) { throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException('Could not execute count on queries with a constraint of type TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Qom\\Statement', 1256661045); } $queryBuilder = $this->objectManager->get(Typo3DbQueryParser::class)->convertQueryToDoctrineQueryBuilder($query); try { $count = $queryBuilder->count('*')->execute()->fetchColumn(0); } catch (DBALException $e) { throw new SqlErrorException($e->getPrevious()->getMessage(), 1472074379); } if ($query->getOffset()) { $count -= $query->getOffset(); } if ($query->getLimit()) { $count = min($count, $query->getLimit()); } return (int) max(0, $count); }
/** * Loads the objects this QueryResult is supposed to hold * * @return void */ protected function initialize() { if (!is_array($this->queryResult)) { $this->queryResult = $this->dataMapper->map($this->query->getType(), $this->persistenceManager->getObjectDataByQuery($this->query)); } }
/** * Add time frame related queries * * @param array $constraints * @param QueryInterface $query * @param int $startTime * @param int|null $endTime * * @see IndexUtility::isIndexInRange */ protected function addTimeFrameConstraints(&$constraints, QueryInterface $query, $startTime, $endTime = null) { // Simulate end time if ($endTime === null) { $endTime = $startTime + DateTimeUtility::SECONDS_DECADE; } $orConstraint = []; // before - in $beforeIn = [$query->lessThan('start_date', $startTime), $query->greaterThanOrEqual('end_date', $startTime), $query->lessThan('end_date', $endTime)]; $orConstraint[] = $query->logicalAnd($beforeIn); // in - in $inIn = [$query->greaterThanOrEqual('start_date', $startTime), $query->lessThan('end_date', $endTime)]; $orConstraint[] = $query->logicalAnd($inIn); // in - after $inAfter = [$query->greaterThanOrEqual('start_date', $startTime), $query->lessThan('start_date', $endTime), $query->greaterThanOrEqual('end_date', $endTime)]; $orConstraint[] = $query->logicalAnd($inAfter); // before - after $beforeAfter = [$query->lessThan('start_date', $startTime), $query->greaterThan('end_date', $endTime)]; $orConstraint[] = $query->logicalAnd($beforeAfter); // finish $constraints[] = $query->logicalOr($orConstraint); }
/** * @param QueryInterface $query * @return array */ protected function addOptionsFromResults(QueryInterface $query) { $items = array(); $results = $query->execute(); $type = $query->getType(); $table = strtolower(str_replace('\\', '_', $type)); $propertyName = $this->getLabelPropertyName($table, $type); foreach ($results as $result) { $uid = $result->getUid(); array_push($items, array(ObjectAccess::getProperty($result, $propertyName), $uid)); } return $items; }
/** * Returns the number of tuples matching the query. * * @param QueryInterface $query * @throws Exception\BadConstraintException * @return int The number of matching tuples */ public function getObjectCountByQuery(QueryInterface $query) { if ($query->getConstraint() instanceof Qom\Statement) { throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException('Could not execute count on queries with a constraint of type TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Qom\\Statement', 1256661045); } list($statementParts) = $this->getStatementParts($query); $fields = '*'; if (isset($statementParts['keywords']['distinct'])) { $fields = 'DISTINCT ' . reset($statementParts['tables']) . '.uid'; } $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts); $count = $this->databaseHandle->exec_SELECTcountRows($fields, $queryCommandParameters['fromTable'], $queryCommandParameters['whereClause']); $this->checkSqlErrors(); if ($statementParts['offset']) { $count -= $statementParts['offset']; } if ($statementParts['limit']) { $count = min($count, $statementParts['limit']); } return (int) max(0, $count); }
/** * Builds and returns the constraint for multi value properties. * * @param Persistence\QueryInterface $query * @param DomainObjectInterface $parentObject * @param string $propertyName * @param string $fieldValue * @param array $relationTableMatchFields * @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint */ protected function getConstraint(Persistence\QueryInterface $query, DomainObjectInterface $parentObject, $propertyName, $fieldValue = '', $relationTableMatchFields = array()) { $columnMap = $this->getDataMap(get_class($parentObject))->getColumnMap($propertyName); if ($columnMap->getParentKeyFieldName() !== NULL) { $constraint = $query->equals($columnMap->getParentKeyFieldName(), $parentObject); if ($columnMap->getParentTableFieldName() !== NULL) { $constraint = $query->logicalAnd($constraint, $query->equals($columnMap->getParentTableFieldName(), $this->getDataMap(get_class($parentObject))->getTableName())); } } else { $constraint = $query->in('uid', \TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $fieldValue)); } if (count($relationTableMatchFields) > 0) { foreach ($relationTableMatchFields as $relationTableMatchFieldName => $relationTableMatchFieldValue) { $constraint = $query->logicalAnd($constraint, $query->equals($relationTableMatchFieldName, $relationTableMatchFieldValue)); } } return $constraint; }
/** * Adds users and groups to the query constraints. * * @param \TYPO3\CMS\Belog\Domain\Model\Constraint $constraint * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param array &$queryConstraints the query constraints to add to, will be modified * @return void */ protected function addUsersAndGroupsToQueryConstraints(\TYPO3\CMS\Belog\Domain\Model\Constraint $constraint, \TYPO3\CMS\Extbase\Persistence\QueryInterface $query, array &$queryConstraints) { $userOrGroup = $constraint->getUserOrGroup(); if ($userOrGroup === '') { return; } // Constraint for a group if (substr($userOrGroup, 0, 3) === 'gr-') { $groupId = (int) substr($userOrGroup, 3); $userIds = array(); foreach ($this->beUserList as $userId => $userData) { if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList($userData['usergroup_cached_list'], $groupId)) { $userIds[] = $userId; } } if (!empty($userIds)) { $queryConstraints[] = $query->in('userid', $userIds); } else { // If there are no group members -> use -1 as constraint to not find anything $queryConstraints[] = $query->in('userid', array(-1)); } } elseif (substr($userOrGroup, 0, 3) === 'us-') { $queryConstraints[] = $query->equals('userid', (int) substr($userOrGroup, 3)); } elseif ($userOrGroup === '-1') { $queryConstraints[] = $query->equals('userid', (int) $GLOBALS['BE_USER']->user['uid']); } }
/** * Update the main event constraints * * @param Demand $demand * @param bool $respectEnableFields * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query * @param array $constraints * @return void */ protected function updateEventConstraints(Demand $demand, $respectEnableFields, \TYPO3\CMS\Extbase\Persistence\QueryInterface $query, array &$constraints) { // reset datetime constraint unset($constraints['datetime']); $eventRestriction = $demand->getEventRestriction(); if ($eventRestriction === Demand::EVENT_RESTRICTION_NO_EVENTS) { $constraints[] = $query->equals('isEvent', 0); } elseif ($eventRestriction === Demand::EVENT_RESTRICTION_ONLY_EVENTS) { $dateField = $demand->getDateField(); $begin = mktime(0, 0, 0, $demand->getMonth(), 1, $demand->getYear()); $end = mktime(23, 59, 59, $demand->getMonth() + 1, 0, $demand->getYear()); $eventsWithNoEndDate = array($query->logicalAnd($query->greaterThanOrEqual($demand->getDateField(), $begin), $query->lessThanOrEqual($demand->getDateField(), $end))); $eventsWithEndDate = array($query->logicalAnd($query->greaterThanOrEqual('datetime', $begin), $query->lessThanOrEqual('datetime', $end), $query->lessThanOrEqual('eventEnd', $end)), $query->logicalAnd($query->lessThanOrEqual($dateField, $begin), $query->greaterThanOrEqual('eventEnd', $end)), $query->logicalAnd($query->lessThanOrEqual($dateField, $begin), $query->greaterThanOrEqual('eventEnd', $begin)), $query->logicalAnd($query->lessThanOrEqual($dateField, $end), $query->greaterThanOrEqual('eventEnd', $end))); $dateConstraints1 = array($query->logicalAnd($eventsWithNoEndDate), $query->logicalOr($eventsWithEndDate)); $constraints['datetime'] = $query->logicalOr($dateConstraints1); $organizers = $demand->getOrganizers(); if (!empty($organizers)) { $constraints[] = $query->in('organizer', $organizers); } $locations = $demand->getLocations(); if (!empty($locations)) { $constraints[] = $query->in('location', $locations); } } }
/** * Get the search constraints * * @param QueryInterface $query * @param DemandInterface $demand * @return array * @throws \UnexpectedValueException */ protected function getSearchConstraints(QueryInterface $query, DemandInterface $demand) { $constraints = []; if ($demand->getSearch() === null) { return $constraints; } /* @var $searchObject \GeorgRinger\News\Domain\Model\Dto\Search */ $searchObject = $demand->getSearch(); $searchSubject = $searchObject->getSubject(); if (!empty($searchSubject)) { $searchFields = GeneralUtility::trimExplode(',', $searchObject->getFields(), true); $searchConstraints = []; if (count($searchFields) === 0) { throw new \UnexpectedValueException('No search fields defined', 1318497755); } foreach ($searchFields as $field) { if (!empty($searchSubject)) { $searchConstraints[] = $query->like($field, '%' . $searchSubject . '%'); } } if (count($searchConstraints)) { $constraints[] = $query->logicalOr($searchConstraints); } } $minimumDate = strtotime($searchObject->getMinimumDate()); if ($minimumDate) { $field = $searchObject->getDateField(); if (empty($field)) { throw new \UnexpectedValueException('No date field is defined', 1396348732); } $constraints[] = $query->greaterThanOrEqual($field, $minimumDate); } $maximumDate = strtotime($searchObject->getMaximumDate()); if ($maximumDate) { $field = $searchObject->getDateField(); if (empty($field)) { throw new \UnexpectedValueException('No date field is defined', 1396348733); } $constraints[] = $query->lessThanOrEqual($field, $maximumDate); } return $constraints; }
/** * Get a QueryInterface constraint from an array definition * * @param QueryInterface $query * @param array $demands * @param string $conjunction * * @return ConstraintInterface|null */ public static function getConstraintsForDemand($query, $demands, $conjunction = 'AND') { $constraints = array(); if (!is_array($demands) || empty($demands)) { return null; } foreach ($demands as $key => $demand) { if (!isset($demand['demand'])) { continue; } $constraint = $demand['demand']; switch ($constraint['operation']) { case 'EQUALS': $constraints[] = $query->equals($constraint['property'], $constraint['value']); break; case 'LIKE': $constraints[] = $query->like($constraint['property'], $constraint['value']); break; case 'CONTAINS': $constraints[] = $query->contains($constraint['property'], $constraint['value']); break; case 'LESSTHAN': $constraints[] = $query->lessThan($constraint['property'], $constraint['value']); break; case 'LESSTHANOREQUAL': $constraints[] = $query->lessThanOrEqual($constraint['property'], $constraint['value']); break; case 'GREATERTHAN': $constraints[] = $query->greaterThan($constraint['property'], $constraint['value']); break; case 'GREATERTHANOREQUAL': $constraints[] = $query->greaterThanOrEqual($constraint['property'], $constraint['value']); break; case 'AND': $tmp = self::getConstraintsForDemand($query, $constraint['operands'], 'AND'); if ($tmp !== null) { $constraints[] = $tmp; } break; case 'OR': $tmp = self::getConstraintsForDemand($query, $constraint['operands'], 'OR'); if ($tmp !== null) { $constraints[] = $tmp; } break; default: return null; } } if (count($constraints) == 0) { return null; } $result = null; switch ($conjunction) { case 'AND': $result = $query->logicalAnd($constraints); break; case 'OR': $result = $query->logicalOr($constraints); break; } return $result; }