本文整理汇总了PHP中Doctrine\Common\Collections\Criteria::create方法的典型用法代码示例。如果您正苦于以下问题:PHP Criteria::create方法的具体用法?PHP Criteria::create怎么用?PHP Criteria::create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Doctrine\Common\Collections\Criteria
的用法示例。
在下文中一共展示了Criteria::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testAction
/**
* @Route("/wotr/test/{id}")
* @ParamConverter("post", class="WotRBundle:Game", options={"repository_method" = "getCurrentGame"})
* @param Game $game
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
*/
public function testAction(Game $game, Request $request)
{
$em = $this->getDoctrine()->getManager();
// $startNations = $em->getRepository('WotRBundle:NationDetails')
// ->findAll();
// foreach( $startNations as $sN ) {
// $n = new NationCopy($sN,$game);
// $em->persist($n);
// }
// $em->flush();
// exit();
$nations = $game->getNations();
// foreach( $nations as $n )
// {
// echo $n->getId();
// }
//
// $nations->filter(
// function ($n) {
// return $n->getName() == 'Dwarves';
// }
// );
//
$c = Criteria::create();
$e = Criteria::expr();
$c->where($e->eq('name', 'Dwarves'));
$nations = $nations->matching($c);
/** @var Nation $n */
foreach ($nations as $n) {
echo $n->getName();
}
return new Response('<body>Test</body>');
}
示例2: getStatisticForRangeAndType
/**
*
* @param \DateTime $startDate beginning >=
* @param \DateTime $endDate end <=
* @param $type - type of the StatisticEntryFilter
*
* @return StatisticEntry[]
*
* Note: can be replaced with DQL if performance issues are notable
*/
public function getStatisticForRangeAndType(\DateTime $startDate, \DateTime $endDate, $type = null)
{
/** @var TrainingDayRepository $trainingDayRepository */
$trainingDayRepository = $this->manager->getRepository('TrainingScheduleBundle:TrainingDay');
$expr = Criteria::expr();
$criteria = Criteria::create();
$criteria->where($expr->gte('date', $startDate));
$criteria->andWhere($expr->lte('date', $endDate));
$criteria->andWhere($expr->eq('user', $this->userToken->getUser()));
/** @var LazyCriteriaCollection $trainingDays */
$trainingDays = $trainingDayRepository->matching($criteria);
$result = array();
/** @var TrainingDay $trainingDay * */
foreach ($trainingDays as $trainingDay) {
foreach ($trainingDay->getStatistics() as $statistic) {
/** @var StatisticEntry $statistic */
if ($type != null) {
if ($statistic->getName() === $type) {
$result[] = $statistic;
}
} else {
$result[] = $statistic;
}
}
}
return $result;
}
示例3: confirmAction
/**
* Confirm email
*
* @return \Zend\Http\Response
*/
public function confirmAction()
{
$confirm = $this->params('confirm');
try {
if (!$confirm) {
//$this->getResponse()->setStatusCode(404);
throw new \Exception('Invalid confirmation code');
}
/**
* @var \Doctrine\ORM\EntityManager $objectManager
*/
$objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
/** @var \User\Entity\User $user */
$user = $objectManager->getRepository('User\\Entity\\User')->findOneBy(array('confirm' => $confirm));
if (!$user) {
throw new \Exception('Invalid confirmation code');
}
$user->activate();
$objectManager->persist($user);
$objectManager->flush();
$criteria = Criteria::create()->where(Criteria::expr()->eq('provider', 'equals'));
$user->getAuths()->matching($criteria)->first()->login($this->getServiceLocator());
$this->flashMessenger()->addSuccessMessage("You've successfully activated your account");
} catch (\Exception $exception) {
$this->flashMessenger()->addErrorMessage($exception->getMessage());
}
return $this->redirect()->toRoute('home');
}
示例4: getPaymentsHistoryAction
/**
* @Rest\View
* @Rest\Get("/payment/history")
*/
public function getPaymentsHistoryAction(Request $request)
{
/** @var User $currentUser */
$currentUser = $this->container->get('security.context')->getToken()->getUser();
$transactions = $currentUser->getTransactions()->matching(Criteria::create()->where(Criteria::expr()->eq('isProcessed', 1)));
return $transactions;
}
示例5: getEmailContext
/**
* Returns the context for the given email
*
* @param Email $email
*
* @return array
*/
public function getEmailContext(Email $email)
{
$criteria = Criteria::create();
$criteria->andWhere(Criteria::expr()->eq('id', $email->getId()));
$qb = $this->activityManager->getActivityTargetsQueryBuilder($this->class, $criteria);
if (null === $qb) {
return [];
}
$result = $qb->getQuery()->getResult();
if (empty($result)) {
return $result;
}
$currentUser = $this->securityFacade->getLoggedUser();
$currentUserClass = ClassUtils::getClass($currentUser);
$currentUserId = $currentUser->getId();
$result = array_values(array_filter($result, function ($item) use($currentUserClass, $currentUserId) {
return !($item['entity'] === $currentUserClass && $item['id'] == $currentUserId);
}));
foreach ($result as &$item) {
$route = $this->configManager->getEntityMetadata($item['entity'])->getRoute();
$item['entityId'] = $email->getId();
$item['targetId'] = $item['id'];
$item['targetClassName'] = $this->entityClassNameHelper->getUrlSafeClassName($item['entity']);
$item['icon'] = $this->configManager->getProvider('entity')->getConfig($item['entity'])->get('icon');
$item['link'] = $route ? $this->router->generate($route, ['id' => $item['id']]) : null;
unset($item['id'], $item['entity']);
}
return $result;
}
示例6: __construct
/**
* setup form
*
*
* @access public
* @param string $name ,default is null
* @param array $options ,default is null
*/
public function __construct($name = null, $options = null)
{
$this->query = $options['query'];
unset($options['query']);
$this->organizationType = $options['organizationType'];
unset($options['organizationType']);
parent::__construct($name, $options);
$this->setAttribute('class', 'form form-horizontal');
$types = array();
$atcTypes = array(Role::PROCTOR_ROLE, Role::TEST_CENTER_ADMIN_ROLE);
$atpTypes = array(Role::TRAINING_MANAGER_ROLE);
if ($this->organizationType === Organization::TYPE_ATC) {
$types = $atcTypes;
} elseif ($this->organizationType === Organization::TYPE_ATP) {
$types = $atpTypes;
} else {
$types = array_merge($atpTypes, $atcTypes);
}
$this->add(array('name' => 'user', 'type' => 'DoctrineModule\\Form\\Element\\ObjectSelect', 'attributes' => array('class' => 'form-control chosen-select', 'required' => 'required'), 'options' => array('label' => 'User', 'object_manager' => $this->query->entityManager, 'target_class' => 'Users\\Entity\\User', 'property' => 'fullName', 'is_method' => true, 'find_method' => array('name' => 'findBy', 'params' => array('criteria' => array())), 'display_empty_item' => true, 'empty_item_label' => self::EMPTY_SELECT_VALUE)));
$criteria = Criteria::create();
$expr = Criteria::expr();
if (count($types) > 0) {
$criteria->andWhere($expr->in("name", $types));
}
$this->add(array('name' => 'role', 'type' => 'DoctrineModule\\Form\\Element\\ObjectSelect', 'attributes' => array('class' => 'form-control', 'required' => 'required'), 'options' => array('label' => 'Role', 'object_manager' => $this->query->entityManager, 'target_class' => 'Users\\Entity\\Role', 'property' => 'name', 'is_method' => false, 'find_method' => array('name' => 'matching', 'params' => array('criteria' => $criteria)), 'display_empty_item' => true, 'empty_item_label' => self::EMPTY_SELECT_VALUE)));
$this->add(array('name' => 'organization', 'type' => 'Zend\\Form\\Element\\Hidden'));
$this->add(array('name' => 'id', 'type' => 'Zend\\Form\\Element\\Hidden'));
$this->add(array('name' => 'Create', 'type' => 'Zend\\Form\\Element\\Submit', 'attributes' => array('class' => 'btn btn-success', 'value' => 'Add')));
$this->add(array('name' => 'reset', 'type' => 'Zend\\Form\\Element', 'attributes' => array('class' => 'btn btn-danger resetButton', 'value' => 'Reset', 'type' => 'button')));
}
示例7: getShortProfileAction
/**
* @Rest\View
* @Rest\Get("/profile/short")
*/
public function getShortProfileAction(Request $request)
{
/** @var User $currentUser */
$currentUser = $this->container->get('security.context')->getToken()->getUser();
$em = $this->getDoctrine()->getManager();
return ['id' => $currentUser->getId(), 'name' => $currentUser->getFullname(), 'exp' => $currentUser->getExpBill(), 'total_exp' => $currentUser->getExpTotal(), 'bill' => $currentUser->getBill(), 'available_dayoffs' => $em->getRepository('AcmeUserBundle:User')->getAvailableDayoffs($currentUser), 'notifications' => $currentUser->getNotifications()->matching(Criteria::create()->where(Criteria::expr()->isNull('readAt')))];
}
示例8: updateToolAction
/**
* @Rest\View
* @Rest\Patch("/tools/{id}")
*/
public function updateToolAction($id, Request $request)
{
/** @var $currentUser User */
$currentUser = $this->container->get('security.context')->getToken()->getUser();
$em = $this->getDoctrine()->getManager();
/** @var $tool Tool */
$tool = $em->find('AcmeEdelaBundle:Tool', $id);
if (!$tool) {
return $this->createNotFoundException();
}
$userTool = $tool->getUserTools()->matching(Criteria::create()->where(Criteria::expr()->eq('user', $currentUser)))->first();
if (!$userTool) {
$userTool = new UserTool();
$userTool->setUser($currentUser)->setTool($tool);
}
if ($request->get('is_enabled')) {
if ($userTool->getIsAvailable() || !$tool->getCost() && $currentUser->getLevel() > $tool->getMinLevel()) {
$userTool->setIsAvailable(true);
$currentEnable = $userTool->getIsEnabled();
$userTool->setIsEnabled(!$currentEnable);
}
}
if ($request->get('buy_exp')) {
if (!$userTool->getIsAvailable() && $currentUser->getExpBill() >= $tool->getCost() && $currentUser->getLevel() >= $tool->getMinLevel()) {
$em->getRepository('AcmeUserBundle:User')->spendExp($currentUser, $tool->getCost());
$userTool->setIsAvailable(true);
}
}
$em->persist($userTool);
$em->flush();
$serializer = $this->get('jms_serializer');
$toolArray = json_decode($serializer->serialize($tool, 'json'), true);
$userToolArray = json_decode($serializer->serialize($userTool, 'json'), true);
return ['success' => true, 'data' => array_merge($toolArray, $userToolArray)];
}
示例9: listarMovimentacao
public function listarMovimentacao($filters, $dados, $sort = null, $direction = null)
{
$qb = $this->createQueryBuilder('mo');
$qb->join("mo.placaVeiculo", "ve");
$qb->join("mo.solicitante", "so");
$qb->join("so.lotacao", "lo");
$criteria = Criteria::create();
foreach ($filters as $filter) {
if (strstr($filter['column'], '.')) {
//Caso ordenado por algum joins, substitui pelo alias
$column = str_replace("placaVeiculo.", "ve.", $filter['column']);
$column = str_replace("solicitante.lotacao.", "lo.", $column);
} else {
//caso não esteja ordenado por join insere o alias do objeto principal
$column = "mo." . $filter['column'];
}
//Código para permitir criterios de comparacao dinamicos ( eq, lt, gte...), de acordo com o tipo do filtro
$criteria = $criteria->andWhere($this->buildCriteriaExprByFilter($column, $filter));
}
$qb->addCriteria($criteria);
$qb->andwhere('lo.codigoMacro = :lotacaoMacro')->setParameter('lotacaoMacro', $dados['lotacaoMacro']);
if ($sort) {
if (strstr($sort, '.')) {
//Caso ordenado por algum joins
//Substitui os Sorts pelos aliases
$sort = str_replace("placaVeiculo.", "ve.", $sort);
$sort = str_replace("solicitante.lotacao.", "lo.", $sort);
$qb->addOrderBy($sort, $direction);
} else {
//caso não esteja ordenado por join insere o alias do objeto principal
$qb->addOrderBy("mo." . $sort, $direction);
}
}
return $qb->getQuery()->getResult();
}
示例10: getGoalsAction
/**
* @Rest\View
* @Rest\Get("/goals")
*/
public function getGoalsAction(Request $request)
{
$user_id = $request->get('user_id');
if ($user_id == 0) {
$user = $this->container->get('security.context')->getToken()->getUser();
} else {
$user = $this->getDoctrine()->getRepository('AcmeUserBundle:User')->find($user_id);
}
if (!$user) {
throw $this->createNotFoundException('user.not_found');
}
/** @var $user User */
$goals = $user->getGoals()->matching(Criteria::create()->where(Criteria::expr()->eq('isDeleted', 0)));
if ($user_id != 0 && $user != $this->container->get('security.context')->getToken()->getUser()) {
$goals = $goals->matching(Criteria::create()->where(Criteria::expr()->eq('isPrivate', 0)));
}
$response = [];
foreach ($goals as $goal) {
$oneGoal = ['title' => $goal->getName(), 'id' => $goal->getId()];
$oneGoal['actions'] = [];
$oneGoal['images'] = [];
foreach ($goal->getImages() as $image) {
$oneGoal['images'][] = ['webPath' => $image->getWebPath()];
}
foreach ($goal->getActions() as $action) {
$oneGoal['actions'][] = ['title' => $action->getTitle()];
}
$response[] = $oneGoal;
}
return $response;
}
示例11: loadWhere
/**
* @param array $criteria
* @param null $order
* @param null $limit
* @param null $offset
*
* @return static[]
*/
public static function loadWhere(array $criteria, $order = null, $limit = null, $offset = null)
{
$crit = Criteria::create();
if ($order) {
$crit->orderBy($order);
}
$crit->setMaxResults($limit);
$crit->setFirstResult($offset);
foreach ($criteria as $k => $v) {
if ($v instanceof Criteria) {
$crit->andWhere($crit->getWhereExpression());
} elseif ($v instanceof Expression) {
$crit->andWhere($v);
} elseif (is_array($v)) {
$expr = Criteria::expr();
$crit->andWhere($expr->andX($expr->in($k, $v)));
} else {
$expr = Criteria::expr();
$crit->andWhere($expr->andX($expr->eq($k, $v)));
}
}
$entities = static::getEntityManager()->getRepository(get_called_class())->matching($crit)->toArray();
foreach ($entities as $entity) {
/**
* @var $entity static
*/
$entity->setExists(true);
$entity->setPersistedData(call_user_func('get_object_vars', $entity));
}
return $entities;
}
示例12: getAll
/**
* @Phprest\Route(method="GET", path="/temperatures")
*
* @Docs\Api(
* path="/temperatures",
* @Docs\Operation(
* method="GET", summary="Gets temperatures",
* @Docs\Parameter(name="page", type="integer", paramType="query", defaultValue=1),
* @Docs\Parameter(name="limit", required=false, type="integer", paramType="query", defaultValue=20),
* @Docs\Parameter(name="query", type="string", paramType="query", defaultValue="value>-10", description="field1<=100,field2=value"),
* @Docs\Parameter(name="sort", required=false, type="string", paramType="query", defaultValue="-created", description="field1,-field2"),
* @Docs\Parameter(name="accept", required=false, type="string", paramType="header"),
* @Docs\ResponseMessage(code=400, message="Not Found"),
* @Docs\ResponseMessage(code=400, message="Bad Request"),
* @Docs\ResponseMessage(code=200, message="Ok")
* )
* )
*
* @param Request $request
* @return Response\Ok
* @throws Exception\NotFound
* @throws Exception\BadRequest
*/
public function getAll(Request $request)
{
$criteria = Criteria::create();
$processor = new Service\RequestFilter\Processor\Orm($criteria, ['created' => function ($value) {
return new \DateTime($value);
}]);
if (is_null($request->query->get('page'))) {
$request->query->set('page', 1);
}
if (is_null($request->query->get('limit'))) {
$request->query->set('limit', 20);
}
try {
$this->serviceRequestFilter()->processQuery($request, $processor);
$this->serviceRequestFilter()->processSort($request, $processor);
} catch (\Exception $e) {
throw new Exception\BadRequest(0, [$e->getMessage()]);
}
$repo = $this->serviceOrm()->getRepository('Api\\Temperature\\Entity\\Temperature');
try {
$temperatures = $repo->matching($criteria);
$criteria->setFirstResult(($request->query->get('page') - 1) * $request->query->get('limit'));
$criteria->setMaxResults($request->query->get('limit'));
$paginatedTemperatures = $repo->matching($criteria);
} catch (\Exception $e) {
throw new Exception\BadRequest(0, [$e->getMessage()]);
}
if (!count($paginatedTemperatures)) {
throw new Exception\NotFound();
}
$temperatures = new PaginatedRepresentation(new CollectionRepresentation($paginatedTemperatures), '/temperatures', $request->query->all(), (int) $request->query->get('page'), (int) $request->query->get('limit'), ceil(count($temperatures) / $request->query->get('limit')), 'page', 'limit', true, count($temperatures));
return new Response\Ok($temperatures);
}
示例13: subactionComplete
public function subactionComplete(SubactionProgressEvent $event, $name, EventDispatcher $dispatcher)
{
$action = $event->getSubaction()->getAction();
$user = $event->getUser();
$userAction = $this->em->getRepository('AcmeEdelaBundle:UserAction')->findOneBy(array('user' => $user, 'action' => $action));
$userTime = $user->getCurrentDateTime();
$dayStart = clone $userTime;
$dayFinish = clone $userTime;
$dayStart->modify('today midnight');
$dayFinish->modify('tomorrow midnight');
$existingProgress = $this->em->getRepository('AcmeEdelaBundle:UserActionProgress')->matching(Criteria::create()->where(Criteria::expr()->eq('userAction', $userAction))->andWhere(Criteria::expr()->gte('createdAt', $dayStart))->andWhere(Criteria::expr()->lte('createdAt', $dayFinish)));
$dispatch = null;
if (!$existingProgress->count() && $action->getSubactions()->count() == count($this->em->getRepository('AcmeEdelaBundle:Action')->getSubactions($action->getId(), $user, null, true))) {
$progress = new UserActionProgress();
$progress->setUserAction($userAction);
$progress->setResult(1);
$this->em->persist($progress);
$dispatch = true;
} elseif ($existingProgress->count()) {
$this->em->remove($existingProgress->first());
$dispatch = false;
}
$this->em->flush();
if ($dispatch !== null) {
$event = new ActionEvent($action, $user, $dispatch);
$dispatcher->dispatch($this->completeEvent, $event);
}
}
示例14: getOfferingsForTeachingReminders
/**
* {@inheritdoc}
*/
public function getOfferingsForTeachingReminders($daysInAdvance)
{
$now = time();
$startDate = new \DateTime();
$startDate->setTimezone(new \DateTimeZone('UTC'));
$startDate->setTimestamp($now);
$startDate->modify("midnight +{$daysInAdvance} days");
$daysInAdvance++;
$endDate = new \DateTime();
$endDate->setTimezone(new \DateTimeZone('UTC'));
$endDate->setTimestamp($now);
$endDate->modify("midnight +{$daysInAdvance} days");
$criteria = Criteria::create();
$expr = Criteria::expr();
$criteria->where($expr->andX($expr->eq('deleted', 0), $expr->gte('startDate', $startDate), $expr->lt('startDate', $endDate)));
$offerings = $this->getRepository()->matching($criteria);
// filter out any offerings belonging to unpublished events
// and with deleted parentage
$offerings->filter(function (OfferingInterface $offering) {
$session = $offering->getSession();
$course = $session->getCourse();
$publishEvent = $offering->getSession()->getPublishEvent();
$school = $course->getSchool();
return isset($publishEvent) && isset($school) && !$session->isDeleted() && !$course->isDeleted();
});
return $offerings;
}
示例15: indexAction
public function indexAction()
{
$viewmodel = new ViewModel();
$return = array();
if ($this->flashMessenger()->hasErrorMessages()) {
$return['error'] = $this->flashMessenger()->getErrorMessages();
}
if ($this->flashMessenger()->hasSuccessMessages()) {
$return['success'] = $this->flashMessenger()->getSuccessMessages();
}
$this->flashMessenger()->clearMessages();
$objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
$criteria = Criteria::create()->andWhere(Criteria::expr()->isNull('parent'));
$criteria->orderBy(array("place" => Criteria::ASC));
$rootcategories = $objectManager->getRepository('Application\\Entity\\Category')->matching($criteria);
$subcategories = array();
foreach ($rootcategories as $category) {
$criteria = Criteria::create()->andWhere(Criteria::expr()->eq('parent', $category));
$criteria->orderBy(array("place" => Criteria::ASC));
$subcategories[$category->getId()] = $objectManager->getRepository('Application\\Entity\\Category')->matching($criteria);
}
$events = array();
$models = array();
$fields = array();
foreach ($objectManager->getRepository('Application\\Entity\\Category')->findAll() as $cat) {
$models[$cat->getId()] = count($objectManager->getRepository('Application\\Entity\\PredefinedEvent')->findBy(array('category' => $cat->getId(), 'parent' => null)));
$fields[$cat->getId()] = count($objectManager->getRepository('Application\\Entity\\CustomField')->findBy(array('category' => $cat->getId())));
}
$viewmodel->setVariables(array('categories' => $rootcategories, 'subcategories' => $subcategories, 'events' => $events, 'models' => $models, 'fields' => $fields, 'messages' => $return));
$this->layout()->title = "Personnalisation > Catégories";
return $viewmodel;
}