public function getPostThread($id) { return $this->createQueryBuilder('p')->select(array('p', 'c'))->join('\\sampleMessageBoard\\application\\model\\BoardModel', 'c', 'WITH', 'p.lft <= c.lft AND p.rgt >= c.rgt')->where('p.id = :id')->setParameter('id', $id)->getQuery()->getResults(\Doctrine\ORM\Query::HYDRATE_ARRAY); $nsm = new Manager(new Config($this->getEntityManager(), $this->_entityName)); $model = $nsm->wrapNode($this->find($id)); //$children = $model->getChildren(); $children = $model->{$model}->getDescendants(); foreach ($children as $c) { $ret[] = $c->getNode()->toArray(); } return $ret; $ret = array(); $model = $this->getEntityManager()->find($id); $descendants = $model->getDescendants(); foreach ($descendants as $d) { $ret[] = $d->toArray(); } return $ret; // // $q = Doctrine_Query::create() // ->select('p.*') // ->from('Posts p') // ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY); // $treeObject = Doctrine_Core::getTable('Posts')->getTree(); // $treeObject->setBaseQuery($q); // $tree = $treeobject->fetchTree(); // $treeObject->restBaseQuery(); // return $tree; }
/** * Retourne une vue de l'ensemble des Noeuds enregistrés * (destiné à être appelé par un render) * @Template() */ public function showAction($_locale) { /* Initialisation des repositories et du Manager */ $em = $this->getDoctrine()->getEntityManager(); $config = new Config($em, 'RNCMenuBundle:Item'); $nsm = new Manager($config); /* Configuration du manager */ $rep = $em->getRepository('RNCMenuBundle:Item'); $qb = $rep->getTreeQB(); $nsm->getConfiguration()->setBaseQueryBuilder($qb); /* Récupération des arbres */ $roots = $rep->findAllRoots(); $trees = array(); foreach ($roots as $root) { $trees[$root->getId()] = $nsm->fetchTreeAsArray($root->getId()); } return $this->render('RNCMenuBundle:Menu:show.html.twig', array('trees' => $trees, '_locale' => $_locale)); }
public function create($params) { $model = new $this->model(); $nsm = new Manager(new Config($this->entityManager, $this->model)); foreach ($params as $k => $v) { $f = 'set' . ucfirst($k); if (method_exists($model, $f)) { $model->{$f}($v); } } if ($model->getParentId() > 0) { // add new post as a child of another post $parent = $nsm->fetchTree($model->getParentId()); $parent->addChild($model); return $model; } else { $nsm->createRoot($model); return $model; } }
/** * Delete entity and flush * @param MenuItem entity */ public function deleteNode(MenuItem $entity) { $this->nestedSetManager->wrapNode($entity)->delete(); }
/** * Выводит меню публикаций * * @Route("/categories-menu/{feedType}/{selectedCategory}/{specialtyId}/{groupId}/{userId}", name = "categories_menu", defaults = {"feedType" = "main-feed", "specialtyId" = 0, "groupId" = 0, "userId" = 0}) */ public function categoriesMenuAction($selectedCategory = 'all', $specialtyId, $groupId, $feedType, $userId) { $em = $this->getDoctrine()->getManager(); $config = new Config($em, 'Evrika\\MainBundle\\Entity\\Category'); $nsManager = new Manager($config); $categories = $nsManager->fetchTreeAsArray(1); // @todo переделать в нормальный switch. Вместо unset лучше сразу выбирать только то что нам нужно (но при этом важно чтобы они были отсортированы (потомки должны идти сразу вслед за своими родителями)) if ($feedType != 'user_feed') { if ($groupId != 0) { // group feed foreach ($categories as $key => $category) { if (!$category->getNode()->isInGroupFeed()) { unset($categories[$key]); } } } else { // main feed foreach ($categories as $key => $category) { if (!$category->getNode()->isInMainFeed()) { unset($categories[$key]); } } } } else { // user feed foreach ($categories as $key => $category) { if (!$category->getNode()->isInUserFeed()) { unset($categories[$key]); } } } if (!($this->get('security.context')->isGranted('ROLE_DOCTOR') || $this->get('security.context')->isGranted('ROLE_STUDENT'))) { // exclude non public foreach ($categories as $key => $category) { if (!$category->getNode()->isPublic()) { unset($categories[$key]); } } } // Если выбран подпункт, подсвечиваем всё равно родительскую категорию foreach ($categories as $key => $category) { if ($category->getId() == $selectedCategory) { if ($categories[$key]->getLevel() > 1) { $selectedCategory = $categories[$key]->getParent()->getNode()->getId(); } } } return $this->render('EvrikaMainBundle::publications_menu.html.twig', array('categories' => $categories, 'feedType' => $feedType, 'selectedCategory' => $selectedCategory, 'specialtyId' => $specialtyId, 'groupId' => $groupId, 'userId' => $userId)); }
/** * Добавляет лайк к публикации или комментарию от имени текущего пользователя * * @Route("/vote/{type}/{entityId}", name = "vote", defaults = {"type" = "publication"}, requirements = {"entityId" = "\d+", "type" = "comment|publication"}) * @Secure(roles = "ROLE_DOCTOR, ROLE_STUDENT") */ public function voteAction($type, $entityId) { $em = $this->getDoctrine()->getManager(); $status = 'ERROR'; $data = null; if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED')) { $entity = $em->find('EvrikaMainBundle:' . ucfirst($type), $entityId); $user = $this->getUser(); $author = $entity->getAuthor(); # если у публикации/комментария нету автора или автор является текущим пользователем if (!$author || !($author->getId() === $user->getId())) { # если текущий пользователь еще НЕ проголосовал if (!$entity->hasVote($user)) { # добавляем лайк $entity->addVote($user); # добавляем уведомление автору публикации или комментария $type == 'publication' ? $this->get('evrika.notice_manager')->publicationVoted($entity, $user) : $this->get('evrika.notice_manager')->commentVoted($entity, $user); // @todo Начисление рейтинга (не удлаось вынести в DoctrineEventSubscriber из-за ограничений preUpdate, поэтому лучше вынести в отдельный сервис) if ($entity->getNumberOfLikes() == ($entity instanceof Publication ? 10 : 5)) { if ($author = $entity->getAuthor()) { $ratingAdder = 0; if ($entity instanceof Publication) { $config = new Config($em, 'Evrika\\MainBundle\\Entity\\Category'); $nsManager = new Manager($config); $categoryId = $entity->getCategory()->getId(); $category = $nsManager->wrapNode($entity->getCategory()); $ancestors = $category->getAncestors(); $ancestorsIds = array(); foreach ($ancestors as $ancestor) { $ancestorsIds[] = $ancestor->getNode()->getId(); } if ($categoryId == Category::VIDEO_CATEGORY_ID || in_array(Category::VIDEO_CATEGORY_ID, $ancestorsIds)) { $ratingAdder = 10; } else { if ($categoryId == Category::COUNCIL_CATEGORY_ID || in_array(Category::COUNCIL_CATEGORY_ID, $ancestorsIds)) { $ratingAdder = 15; } else { if ($categoryId == Category::ARTICLE_CATEGORY_ID || in_array(Category::ARTICLE_CATEGORY_ID, $ancestorsIds)) { $ratingAdder = 25; } } } } else { $ratingAdder = 1; } if ($ratingAdder) { $author->addRating($ratingAdder); } } } if ($type == 'publication') { $log = new LikeLog(); $log->setUser($this->getUser()); $log->setType('publication'); $log->setCategory($entity->getCategory()->getId()); $em->persist($log); $em->flush(); } $em->flush(); $status = 'OK'; } else { $data = $type == 'publication' ? 'Вы уже голосовали за эту статью' : 'Вы уже голосовали за этот комментарий'; } } else { $data = 'Вы не можете голосовать за собственные материалы'; } } else { $data = 'Вы не авторизованы'; } return $this->render('EvrikaMainBundle::response.json.twig', array('status' => $status, 'data' => $data)); }
private function onPublicationCreated(LifecycleEventArgs $args) { $publication = $args->getEntity(); # установить автора публикации $publication->setAuthor($this->container->get('security.context')->getToken()->getUser()); # добавить ему рейтинг за публикацию if ($author = $publication->getAuthor()) { $em = $args->getEntityManager(); $config = new Config($em, 'Evrika\\MainBundle\\Entity\\Category'); $nsManager = new Manager($config); $categoryId = $publication->getCategory()->getId(); $category = $nsManager->wrapNode($publication->getCategory()); $ancestors = $category->getAncestors(); $ancestorsIds = array(); foreach ($ancestors as $ancestor) { $ancestorsIds[] = $ancestor->getNode()->getId(); } $ratingAdder = 0; if ($categoryId == Category::VIDEO_CATEGORY_ID || in_array(Category::VIDEO_CATEGORY_ID, $ancestorsIds)) { $ratingAdder = 2; } else { if ($categoryId == Category::COUNCIL_CATEGORY_ID || in_array(Category::COUNCIL_CATEGORY_ID, $ancestorsIds)) { $ratingAdder = 3; } else { if ($categoryId == Category::ARTICLE_CATEGORY_ID || in_array(Category::ARTICLE_CATEGORY_ID, $ancestorsIds)) { $ratingAdder = 5; } } } if ($ratingAdder) { $author->addRating($ratingAdder); } } }
public function __construct(EntityManager $em, $clazz = null) { parent::__construct(new Config($em, $clazz)); }
/** * * @Route("/move", name="rnc_admin_menu_move", requirements={"_method"="POST"}) * @Template() * @Secure(roles="ROLE_ADMIN") */ public function moveAction() { $request = $this->get('request'); if ($request->isXmlHttpRequest()) { $cur = $request->request->get('cur'); $prev = $request->request->get('prev'); $next = $request->request->get('next'); $em = $this->getDoctrine()->getEntityManager(); $config = new Config($em, 'RNCMenuBundle:Item'); $nsm = new Manager($config); $rep = $em->getRepository('RNCMenuBundle:Item'); $cur_node = $rep->find($cur); $prev_node = $rep->find($prev); $next_node = $rep->find($next); if ($cur_node == null) { throw new NotFoundHttpException("Elément introuvable"); } $node = $nsm->wrapNode($cur_node); if ($prev_node != null) { $wrp = $nsm->wrapNode($prev_node); if ($node->isRoot()) { $new_pos = $prev_node->getPosition(); $old_pos = $cur_node->getPosition(); if ($old_pos < $new_pos) { $rep->moveItemDown($old_pos, $new_pos); $cur_node->setPosition($new_pos); } else { $rep->moveItemUp($old_pos, $new_pos + 1); $cur_node->setPosition($new_pos + 1); } $em->persist($cur_node); } else { $node->moveAsNextSiblingOf($wrp); } } else { if ($next_node != null) { $wrp = $nsm->wrapNode($next_node); if ($node->isRoot()) { $new_pos = 1; $old_pos = $cur_node->getPosition(); $rep->moveItemUp($old_pos, $new_pos); $cur_node->setPosition($new_pos); $em->persist($cur_node); } else { $node->moveAsPrevSiblingOf($wrp); } } } $em->flush(); $qb = $rep->getTreeQB(); $nsm->getConfiguration()->setBaseQueryBuilder($qb); $roots = $rep->findAllRoots(); $trees = array(); foreach ($roots as $root) { $trees[$root->getId()] = $nsm->fetchTreeAsArray($root->getId()); } return $this->render('RNCMenuBundle:Menu:show.html.twig', array('trees' => $trees)); } else { return $this->indexAction(); } }
private function getSubcategoriesDQL($rootCategoryId = 'all', $countryId = null) { $em = $this->getEntityManager(); $config = new Config($em, 'Evrika\\MainBundle\\Entity\\Category'); $nsManager = new Manager($config); if ($rootCategoryId == 'all') { $rootNode = $nsManager->fetchTree(Category::FEED_CATEGORIES_ROOT_ID); $selectedCategories = $rootNode->getDescendants(); } else { $rootNode = $em->find('EvrikaMainBundle:Category', $rootCategoryId); $rootNode = $nsManager->wrapNode($rootNode); $selectedCategories = $rootNode->getDescendants(); $selectedCategories[] = $rootNode; } $regionalCategoriesIds = array(); $commonCategoriesIds = array(); foreach ($selectedCategories as $category) { if ($category->getNode()->isRegional()) { $regionalCategoriesIds[] = $category->getNode()->getId(); } else { $commonCategoriesIds[] = $category->getNode()->getId(); } $categoriesIds[] = $category->getNode()->getId(); } $regionalCategoriesDQL = ''; $commonCategoriesDQL = ''; if (!empty($regionalCategoriesIds)) { $regionalCategoriesDQL = '(c.id IN (' . implode(',', $regionalCategoriesIds) . ')' . ($countryId ? ' AND p.country = ' . $countryId : '') . ')'; } if (!empty($commonCategoriesIds)) { $commonCategoriesDQL = 'c.id IN (' . implode(',', $commonCategoriesIds) . ')'; } $query = ' AND (' . $regionalCategoriesDQL . ($commonCategoriesDQL && $regionalCategoriesDQL ? ' OR ' : '') . $commonCategoriesDQL . ' OR (c.id IN (' . implode(',', $categoriesIds) . ') AND p.country IS NULL))'; return $query; }