Esempio n. 1
0
 /**
  * {@inheritdoc}
  */
 public function getIterator()
 {
     if (null === $this->iterator) {
         $this->iterator = $this->paginator->getIterator();
     }
     return $this->iterator;
 }
Esempio n. 2
0
 /**
  * @inheritDoc
  */
 public function paginate($target, $offset, $limit)
 {
     $target->setFirstResult($offset)->setMaxResults($limit);
     $paginator = new Paginator($target);
     $this->total = $paginator->count();
     return $paginator->getIterator();
 }
Esempio n. 3
0
 /**
  * {@inheritdoc}
  */
 public function getIterator()
 {
     if (null === $this->_result) {
         return parent::getIterator();
     }
     return new \ArrayIterator($this->_result);
 }
Esempio n. 4
0
 /**
  * @param  int         $offset
  * @param  int         $limit
  * @param  string|null $status
  * @return PaginationResult
  */
 public function paginateAll($offset, $limit, $status = null)
 {
     $queryBuilder = $this->entityRepository->createQueryBuilder('invoice');
     $queryBuilder->innerJoin('invoice.client', 'client');
     $queryBuilder->setFirstResult($offset);
     $queryBuilder->setMaxResults($limit);
     $queryBuilder->orderBy('invoice.id', 'desc');
     switch ($status) {
         case 'paid':
             $queryBuilder->andWhere('invoice.payDate IS NOT NULL');
             break;
         case 'late':
             $queryBuilder->andWhere('invoice.payDate IS NULL');
             $queryBuilder->andWhere('invoice.dueDate IS NOT NULL');
             $queryBuilder->andWhere('invoice.dueDate < :now');
             $queryBuilder->setParameter('now', new DateTime());
             break;
         case 'sent':
             $queryBuilder->andWhere('invoice.payDate IS NULL');
             $queryBuilder->andWhere('invoice.dueDate IS NULL OR invoice.dueDate >= :now');
             $queryBuilder->andWhere('invoice.sendDate IS NOT NULL');
             $queryBuilder->setParameter('now', new DateTime());
             break;
         case 'draft':
             $queryBuilder->andWhere('invoice.payDate IS NULL');
             $queryBuilder->andWhere('invoice.dueDate IS NULL OR invoice.dueDate >= :now');
             $queryBuilder->andWhere('invoice.sendDate IS NULL');
             $queryBuilder->setParameter('now', new DateTime());
             break;
     }
     $paginator = new Paginator($queryBuilder->getQuery(), false);
     return new PaginationResult($paginator->getIterator(), $paginator->count());
 }
Esempio n. 5
0
 /**
  * Lists all Viaggio entities.
  *
  * @Route("/", name="travel")
  * @Method("GET")
  * @Template("AppBundle:Viaggio:mete-visitate.html.twig")
  */
 public function indexAction()
 {
     $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
     $em = $this->getDoctrine()->getManager();
     $user = $this->container->get('security.context')->getToken()->getUser();
     $user_id = $user->getId();
     // $entities = $em->getRepository('AppBundle:Viaggio')->findBy(['utente'=>$user, 'salvato'=>true],['id' => 'DESC']);
     // Limit per page.
     $limit = 4;
     $page = $this->getRequest()->query->get("page", 1);
     $thisPage = $page;
     $query = $em->createQuery("SELECT viaggio, viaggio.id, viaggio.descrizione, viaggio.meta, viaggio.partenza, viaggio.arrivo, viaggio.periodo, viaggio.salvato, user.id\n            FROM AppBundle:Viaggio viaggio\n            JOIN AppBundle:User user WHERE (viaggio.utente = {$user_id})\n            WHERE viaggio.salvato = true\n            ORDER BY viaggio.id DESC")->setFirstResult($limit * ($page - 1))->setMaxResults($limit);
     // $questo=$query->getResult();
     $paginator = new Paginator($query, $fetchJoinCollection = true);
     $maxPages = ceil($paginator->count() / $limit);
     // $c = count($paginator);
     // foreach ($paginator as $post) {
     //     echo $post->getHeadline() . "\n";
     // }
     $birthDate = $user->getDataDiNascita();
     $age = null;
     if ($birthDate != null) {
         //explode the date to get month, day and year
         $birthDate = explode("-", $birthDate);
         //get age from date or birthdate
         $age = date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? date("Y") - $birthDate[2] - 1 : date("Y") - $birthDate[2];
     }
     $ultimaSalvata = $em->getRepository('AppBundle:Viaggio')->findOneBy(array('utente' => $user->getId(), 'salvato' => true), array('id' => 'DESC'));
     return array('eta' => $age, 'salvata' => $ultimaSalvata, 'user' => $user, 'maxPages' => $maxPages, 'thisPage' => $thisPage, 'issues' => $paginator->getIterator());
 }
 /**
  * @return PaginatedResourceCollection
  */
 protected function createPaginated()
 {
     $entities = $this->paginator->getIterator()->getArrayCopy();
     $metadata = $this->mineMetadata($entities);
     $resources = array_map([$this, 'createResource'], $entities);
     $collection = new PaginatedResourceCollection($resources, $metadata);
     $collection->setPaginator($this->paginator);
     return $collection;
 }
Esempio n. 7
0
 /**
  * @param $params
  *
  * @return mixed
  */
 public function findWithJoins($params)
 {
     $queryBuilder = $this->createQueryBuilder('h')->select('h, s, t, lc, cer, pm, hp, tr')->leftJoin('h.services', 's')->leftJoin('h.thematics', 't')->leftJoin('h.linkedCities', 'lc')->leftJoin('h.certificates', 'cer')->leftJoin('h.paymentMethods', 'pm')->leftJoin('h.hotelPois', 'hp')->leftJoin('h.transports', 'tr');
     $i = 0;
     foreach ($params as $key => $value) {
         $queryBuilder->andWhere("h.{$key} = :param_{$i}")->setParameter("param_{$i}", $value);
         $i++;
     }
     $query = $queryBuilder->setMaxResults(1)->getQuery();
     $results = new Paginator($query, $fetchJoin = true);
     return $results->getIterator()->current();
 }
 /**
  * @param mixed $query      query
  * @param int   $page       page
  * @param int   $maxPerPage maxPerPage
  *
  * @throws \Exception
  * @return \Traversable
  */
 public function fetch($query, $page = 1, $maxPerPage = 10)
 {
     if (!$query instanceof DoctrineQueryBuilder) {
         throw new \Exception('Not supported yet');
     }
     if ($maxPerPage) {
         $offset = ($page - 1) * (int) $maxPerPage;
         $query->setFirstResult($offset)->setMaxResults($maxPerPage);
     }
     // use pager even if it's a query executor, to fix number of results returned issue.
     $paginator = new Paginator($query, true);
     return (array) $paginator->getIterator();
 }
Esempio n. 9
0
 /**
  * Fetch items by node
  * http://docs.doctrine-project.org/en/latest/tutorials/pagination.html
  * http://stackoverflow.com/questions/10043588/doctrine-2-pagination-with-association-mapping
  * http://docs.doctrine-project.org/en/latest/reference/query-builder.html
  * @param object $node The node
  * @param array $options Associtive array
  * $options = array(
  *  'page' => $theCurrentPage,
  *  'rowsPerPage' => $theRowsPerPage
  *  'sortField' => $theFieldToSort
  *  'sortDirection' => $theDirectionToSort
  * )
  * @return object \Zend\Paginator
  */
 public function fetchItems($node, $options = array())
 {
     $page = (int) isset($options['page']) ? $options['page'] : 0;
     $maxRows = (int) isset($options['rowsPerPage']) ? $options['rowsPerPage'] : 15;
     $sortField = isset($options['sortField']) ? $options['sortField'] : 'created';
     $sortDirection = isset($options['sortDirection']) ? $options['sortDirection'] : 'DESC';
     $cacheName = $this->cacheName($node->getId() . 'collection' . __FUNCTION__ . $page . $maxRows . $sortField . $sortDirection);
     $query = $this->_em->createQuery("\n\t\t\tSELECT i\n\t\t\t FROM DxBuySell\\Entity\\Item i \n\t\t\t  INNER JOIN i.categories c\n\t\t\t  WHERE c.id = " . $node->getId() . " \n\t\t\t  ORDER By i." . $sortField . " " . $sortDirection);
     $query->useResultCache($this->cacheEnabled, $this->cacheLifetime, $cacheName);
     $paginator = new Paginator($query, $fetchJoinCollection = true);
     $zendPaginator = new \Zend\Paginator\Paginator(new \Zend\Paginator\Adapter\Iterator($paginator->getIterator()));
     $zendPaginator->setItemCountPerPage($maxRows)->setCurrentPageNumber($page);
     return $zendPaginator;
 }
Esempio n. 10
0
 /**
  * {@inheritdoc}
  */
 public function paginate($target, $page = 1, $limit = 10)
 {
     if (!$target instanceof DoctrineQueryBuilder) {
         throw new \Exception('Not supported yet');
     }
     if ($limit) {
         $offset = ($page - 1) * (int) $limit;
         $target->setFirstResult($offset)->setMaxResults($limit);
     }
     $paginator = new Paginator($target, true);
     $this->page = $page;
     $this->items = (array) $paginator->getIterator();
     $this->nbResults = count($paginator);
     $this->lastPage = intval(ceil($this->nbResults / $limit));
     return $this;
 }
Esempio n. 11
0
 /**
  * Sets up the query, builds the output and returns it ready for JSON encoding
  */
 public function getResult()
 {
     $query = $this->getQueryBuilder()->getQuery();
     // Only use the paginator if we have joins
     if (!empty($this->links)) {
         $paginator = new Paginator($query, true);
         $results = iterator_to_array($paginator->getIterator());
     } else {
         $results = $query->getResult();
     }
     // Build the output array
     if ($this->field) {
         $this->buildFieldOutput($results, $this->field);
     } else {
         // Get meta info for the root type
         $this->buildOutputMeta($results);
         // Get Doctrine to add the missing collection data
         $this->performAllHydrations();
         $this->buildOutput($results);
     }
     return $this->output;
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 public function getIterator()
 {
     return $this->paginator->getIterator();
 }
Esempio n. 13
0
 /**
  * {@inheritDoc}
  *
  * @api
  */
 public function getItems($offset, $limit)
 {
     $this->paginator->getQuery()->setFirstResult($offset)->setMaxResults($limit);
     return iterator_to_array($this->paginator->getIterator());
 }
Esempio n. 14
0
 public function testCloneQuery()
 {
     $dql = "SELECT u FROM Doctrine\\Tests\\Models\\CMS\\CmsUser u";
     $query = $this->_em->createQuery($dql);
     $paginator = new Paginator($query);
     $paginator->getIterator();
     $this->assertTrue($query->getParameters()->isEmpty());
 }
 public function getResult()
 {
     $perPage = $this->getPerPage();
     $page = $this->getPage();
     $queryBuilder = $this->createResultQueryBuilder();
     try {
         if ($perPage !== null) {
             $queryBuilder->setMaxResults($perPage);
             $queryBuilder->setFirstResult($perPage * ($page - 1));
             $query = $queryBuilder->getQuery();
             $paginator = new Paginator($query, true);
             $entities = $paginator->getIterator()->getArrayCopy();
         } else {
             $query = $queryBuilder->getQuery();
             $entities = $query->getResult();
         }
         $total = $this->getTotal();
     } catch (NoResultException $e) {
         $entities = array();
         $total = 0;
     }
     $routeParameters = $this->getRouteParameters();
     return new EntityFinderResult($entities, $total, $page, $perPage, $routeParameters);
 }
Esempio n. 16
0
 public function testIterateComplexWithOutputWalker()
 {
     $dql = "SELECT g, COUNT(u.id) AS userCount FROM Doctrine\\Tests\\Models\\CMS\\CmsGroup g LEFT JOIN g.users u GROUP BY g HAVING COUNT(u.id) > 0";
     $query = $this->_em->createQuery($dql);
     $paginator = new Paginator($query);
     $paginator->setUseOutputWalkers(true);
     $this->assertCount(9, $paginator->getIterator());
 }
 /**
  * @param $userId
  *
  * @return array
  */
 public function getUserChannels($userId, $search = '', $limit = 10, $start = 0)
 {
     $q = $this->_em->createQueryBuilder();
     $select = 'partial c.{id, name}';
     if (is_array($search) && !empty($search)) {
         $count = 1;
         $order = '(CASE';
         foreach ($search as $count => $id) {
             $order .= ' WHEN c.id = ' . $id . ' THEN ' . $count;
             $count++;
         }
         $order .= ' ELSE ' . $count . ' END) AS HIDDEN ORD';
         $select .= ", {$order}";
     }
     $q->select($select)->from('MauticChatBundle:Channel', 'c', 'c.id')->leftJoin('c.privateUsers', 'u');
     $q->where($q->expr()->orX($q->expr()->eq('c.isPrivate', ':false'), $q->expr()->andX($q->expr()->eq('c.isPrivate', ':true'), $q->expr()->eq('u.id', ':userId'))))->setParameter('userId', $userId);
     $q->andWhere('c.isPublished = :true')->setParameter(':true', true, 'boolean')->setParameter(':false', false, 'boolean');
     if (!empty($search)) {
         if (is_array($search)) {
             $q->andWhere($q->expr()->in('c.id', ':channels'))->setParameter('channels', $search);
         } else {
             $q->andWhere($q->expr()->like('c.name', ':search'))->setParameter('search', "{$search}%");
         }
     }
     if (!empty($limit)) {
         $q->setFirstResult($start)->setMaxResults($limit);
     }
     if (!is_array($search)) {
         $q->orderBy('c.name', 'ASC');
     } elseif (!empty($search)) {
         //force array order
         $q->orderBy('ORD', 'ASC');
     }
     $query = $q->getQuery();
     $query->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);
     $results = new Paginator($query);
     $iterator = $results->getIterator();
     $channels = array('channels' => $iterator->getArrayCopy(), 'count' => count($iterator), 'total' => count($results));
     return $channels;
 }
Esempio n. 18
0
date_default_timezone_set('Europe/Prague');
$cache = new \Doctrine\Common\Cache\FilesystemCache(__DIR__ . '/temp');
$config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/Benchmark/Entities'], TRUE, __DIR__ . '/Benchmark/Entities/Proxies', $useCache ? $cache : NULL, FALSE);
$config->setProxyNamespace('Benchmark\\Entities\\Proxies');
$config->setAutoGenerateProxyClasses(TRUE);
// we need __toString on DateTime, since UoW converts composite primary keys to string
// (who the hell invented composite PKs :P)
Type::overrideType(Type::DATE, 'Benchmark\\Types\\DateType');
Type::overrideType(Type::DATETIME, 'Benchmark\\Types\\DateTimeType');
// TODO you may want to change this? ;)
$em = EntityManager::create(['driver' => 'pdo_mysql', 'user' => 'root', 'password' => '', 'dbname' => 'employees'], $config);
$time = -microtime(TRUE);
ob_start();
$qb = $em->createQueryBuilder()->from('Benchmark\\Entities\\Employee', 'e')->select('e')->innerJoin('e.salaries', 's')->addSelect('s')->innerJoin('e.affiliatedDepartments', 'd')->addSelect('d')->innerJoin('d.department', 'dd')->addSelect('dd')->setMaxResults(500)->getQuery();
$paginator = new Paginator($qb);
foreach ($paginator->getIterator() as $emp) {
    /** @var Employee $emp */
    // $output->writeln
    echo sprintf('%s %s (%d):', $emp->getFirstName(), $emp->getLastName(), $emp->getId()), PHP_EOL;
    // $output->writeln
    echo "\tSalaries:", PHP_EOL;
    foreach ($emp->getSalaries() as $salary) {
        // $output->writeln
        echo "\t\t", $salary->getAmount(), PHP_EOL;
    }
    // $output->writeln
    echo "\tDepartments:", PHP_EOL;
    foreach ($emp->getAffiliatedDepartments() as $department) {
        // $output->writeln
        echo "\t\t" . $department->getDepartment()->getName(), PHP_EOL;
    }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public function getSlice($offset, $length)
 {
     $this->paginator->getQuery()->setFirstResult($offset)->setMaxResults($length);
     return $this->paginator->getIterator();
 }
 /**
  * Returns an array of items for a page.
  *
  * @param  integer $offset Page offset
  * @param  integer $itemCountPerPage Number of items per page
  *
  * @return array
  */
 public function getItems($offset, $itemCountPerPage)
 {
     return $this->paginator->getIterator();
 }
Esempio n. 21
0
 /**
  * @dataProvider useOutputWalkersAndFetchJoinCollection
  */
 public function testPaginationWithSubSelectOrderByExpression($useOutputWalker, $fetchJoinCollection)
 {
     $query = $this->_em->createQuery("SELECT u, \n                (\n                    SELECT MAX(a.version)\n                    FROM Doctrine\\Tests\\Models\\CMS\\CmsArticle a\n                    WHERE a.user = u\n                ) AS HIDDEN max_version\n            FROM Doctrine\\Tests\\Models\\CMS\\CmsUser u\n            ORDER BY max_version DESC");
     $paginator = new Paginator($query, $fetchJoinCollection);
     $paginator->setUseOutputWalkers($useOutputWalker);
     $this->assertCount(9, $paginator->getIterator());
 }
Esempio n. 22
0
 /**
  * массив элементов пагинатора
  *
  * @return array
  */
 public function getItemsArray()
 {
     return $this->resource->getIterator()->getArrayCopy();
 }
Esempio n. 23
0
 /**
  * @param string  $entityName
  * @param integer $page
  *
  * @return \Lexik\Bundle\MailerBundle\Tools\SimplePager
  */
 public function retrievePageElements($entityName, $page)
 {
     $page = $page < 1 ? 1 : $page;
     $qb = $this->createQueryBuilder($entityName);
     $qb->setMaxResults($this->itemPerPage)->setFirstResult(($page - 1) * $this->itemPerPage);
     $paginator = new Paginator($qb, true);
     $this->page = $page;
     $this->count = $paginator->count();
     $this->results = $paginator->getIterator();
     $this->maxPage = ceil($this->count / $this->itemPerPage);
     return $this;
 }
Esempio n. 24
0
 /**
  * Returns a list of users that can be used in chat, etc
  *
  * @param int    $currentUserId
  * @param mixed  $search
  * @param int    $limit
  * @param int    $start
  */
 public function getUsers($currentUserId = 0, $search = '', $limit = 10, $start = 0)
 {
     $q = $this->_em->createQueryBuilder();
     $select = 'partial u.{id, username, firstName, lastName, email, lastActive, onlineStatus}';
     if (is_array($search) && !empty($search)) {
         $order = '(CASE';
         $count = 1;
         foreach ($search as $count => $id) {
             $order .= ' WHEN u.id = ' . $id . ' THEN ' . $count;
             $count++;
         }
         $order .= ' ELSE ' . $count . ' END) AS HIDDEN ORD';
         $select .= ", {$order}";
     }
     $q->select($select)->from('MauticUserBundle:User', 'u', 'u.id');
     if (!empty($currentUserId)) {
         $q->where('u.id != :currentUser')->setParameter('currentUser', $currentUserId);
     }
     $q->andWhere('u.isPublished = :true')->setParameter(':true', true, 'boolean');
     if (!empty($search)) {
         if (is_array($search)) {
             $q->andWhere($q->expr()->in('u.id', ':users'))->setParameter('users', $search);
         } else {
             $q->andWhere($q->expr()->orX($q->expr()->like('u.email', ':search'), $q->expr()->like('u.firstName', ':search'), $q->expr()->like('u.lastName', ':search'), $q->expr()->like($q->expr()->concat('u.firstName', $q->expr()->concat($q->expr()->literal(' '), 'u.lastName')), ':search')))->setParameter('search', "{$search}%");
         }
     }
     if (!is_array($search)) {
         $q->orderBy('u.firstName, u.lastName');
     } elseif (!empty($search)) {
         //force array order
         $q->orderBy('ORD', 'ASC');
     }
     if (!empty($limit)) {
         $q->setFirstResult($start)->setMaxResults($limit);
     }
     $query = $q->getQuery();
     $query->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);
     $results = new Paginator($query);
     $iterator = $results->getIterator();
     $users = array('users' => $iterator->getArrayCopy(), 'count' => count($iterator), 'total' => count($results));
     return $users;
 }
Esempio n. 25
0
 public function testQueryWalkerIsKept()
 {
     $dql = "SELECT u FROM Doctrine\\Tests\\Models\\CMS\\CmsUser u";
     $query = $this->_em->createQuery($dql);
     $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\\Tests\\ORM\\Functional\\CustomPaginationTestTreeWalker'));
     $paginator = new Paginator($query, true);
     $paginator->setUseOutputWalkers(false);
     $this->assertCount(1, $paginator->getIterator());
     $this->assertEquals(1, $paginator->count());
 }
 /**
  *
  * {@inheritdoc}
  *
  */
 public function getItems($offset, $itemCountPerPage)
 {
     $this->paginator->getQuery()->setFirstResult($offset)->setMaxResults($itemCountPerPage);
     return $this->paginator->getIterator();
 }
 public function apiQuery($qdata, $options = [])
 {
     $this->_apiFindParamList = [];
     $app = App::i();
     $findOne = key_exists('findOne', $options) ? $options['findOne'] : false;
     $counting = key_exists('@count', $qdata);
     if ($counting) {
         unset($qdata['@count']);
     }
     if (class_exists($this->entityClassName)) {
         if (!$qdata && !$counting) {
             $this->apiErrorResponse('no data');
         }
         $class = $this->entityClassName;
         $entity_properties = array_keys($app->em->getClassMetadata($this->entityClassName)->fieldMappings);
         $entity_associations = $app->em->getClassMetadata($this->entityClassName)->associationMappings;
         $entity_metadata = [];
         $metadata_class = "";
         $meta_num = 0;
         $taxo_num = 0;
         $dql_joins = "";
         $dql_select = "";
         $dql_select_joins = "";
         if ($class::usesMetadata()) {
             $metadata_class = $class::getMetadataClassName();
             $metadata_class = $class . 'Meta';
             $dql_join_template = "\n\tLEFT JOIN e.__metadata {ALIAS} WITH {ALIAS}.key = '{KEY}'\n";
             foreach ($app->getRegisteredMetadata($this->entityClassName) as $meta) {
                 $entity_metadata[] = $meta->key;
             }
         }
         if ($class::usesTaxonomies()) {
             $taxonomies = [];
             $taxonomies_ids = [];
             foreach ($app->getRegisteredTaxonomies($class) as $obj) {
                 $taxonomies[] = 'term:' . $obj->slug;
                 $taxonomies_ids['term:' . $obj->slug] = $obj->id;
             }
             $dql_join_term_template = "\n\tLEFT JOIN e.__termRelations {ALIAS_TR} LEFT JOIN {ALIAS_TR}.term {ALIAS_T} WITH {ALIAS_T}.taxonomy = {TAXO}\n";
         }
         $keys = [];
         $append_files_cb = function () {
         };
         $select = ['id'];
         $select_metadata = [];
         $order = null;
         $op = ' AND ';
         $offset = null;
         $limit = null;
         $page = null;
         $keyword = null;
         $permissions = null;
         $dqls = [];
         foreach ($qdata as $key => $val) {
             $val = trim($val);
             if (strtolower($key) == '@select') {
                 $select = explode(',', $val);
                 $_joins = [];
                 foreach ($select as $prop) {
                     if (in_array($prop, $entity_metadata)) {
                         $select_metadata[] = $prop;
                     } elseif (strpos($prop, '.') > 0) {
                         $relation = substr($prop, 0, strpos($prop, '.'));
                         $relation_property = substr($prop, strpos($prop, '.') + 1);
                         if (strpos($relation_property, '.') > 0) {
                             $relation_property = substr($relation_property, 0, strpos($relation_property, '.'));
                         }
                         if (isset($entity_associations[$relation])) {
                             if (!isset($_joins[$relation])) {
                                 $_joins[$relation] = [];
                             }
                             $_joins[$relation][] = $relation_property;
                         }
                     }
                 }
                 foreach ($_joins as $j => $props) {
                     $join_id = uniqid($j);
                     $dql_select_joins = " LEFT JOIN e.{$j} {$join_id}";
                     $dql_select .= ", {$join_id}";
                 }
                 continue;
             } elseif (strtolower($key) == '@keyword') {
                 $keyword = $val;
                 continue;
             } elseif (strtolower($key) == '@permissions') {
                 $permissions = explode(',', $val);
                 continue;
             } elseif (strtolower($key) == '@order') {
                 $order = $val;
                 continue;
             } elseif (strtolower($key) == '@or') {
                 $op = ' OR ';
                 continue;
             } elseif (strtolower($key) == '@offset') {
                 $offset = $val;
                 continue;
             } elseif (strtolower($key) == '@page') {
                 $page = $val;
                 continue;
             } elseif (strtolower($key) == '@limit') {
                 $limit = $val;
                 continue;
             } elseif (strtolower($key) == '@type') {
                 continue;
             } elseif (strtolower($key) == '@debug') {
                 continue;
             } elseif (strtolower($key) == '@files' && preg_match('#^\\(([\\w\\., ]+)\\)[ ]*(:[ ]*([\\w, ]+))?#i', $val, $imatch)) {
                 if ($counting) {
                     continue;
                 }
                 // example:
                 // @files=(avatar.smallAvatar,header.header):name,url
                 $cfg = ['files' => explode(',', $imatch[1]), 'props' => key_exists(3, $imatch) ? explode(',', $imatch[3]) : ['url']];
                 $_join_in = [];
                 foreach ($cfg['files'] as $_f) {
                     if (strpos($_f, '.') > 0) {
                         list($_f_group, $_f_transformation) = explode('.', $_f);
                         $_join_in[] = $_f_group;
                         $_join_in[] = 'img:' . $_f_transformation;
                     } else {
                         $_join_in[] = $_f;
                     }
                 }
                 $_join_in = array_unique($_join_in);
                 $dql_select .= " , files, fparent";
                 $dql_select_joins .= " LEFT JOIN e.__files files WITH files.group IN ('" . implode("','", $_join_in) . "') LEFT JOIN files.parent fparent";
                 $extract_data_cb = function ($file, $ipath, $props) {
                     $result = [];
                     if ($ipath) {
                         $path = explode('.', $ipath);
                         foreach ($path as $transformation) {
                             $file = $file->transform($transformation);
                         }
                     }
                     if (is_object($file)) {
                         foreach ($props as $prop) {
                             $result[$prop] = $file->{$prop};
                         }
                     }
                     return $result;
                 };
                 $append_files_cb = function (&$result, $entity) use($cfg, $extract_data_cb) {
                     $files = $entity->files;
                     foreach ($cfg['files'] as $im) {
                         $im = trim($im);
                         list($igroup, $ipath) = explode('.', $im, 2) + [null, null];
                         if (!key_exists($igroup, $files)) {
                             continue;
                         }
                         if (is_array($files[$igroup])) {
                             $result["@files:{$im}"] = [];
                             foreach ($files[$igroup] as $file) {
                                 $result["@files:{$im}"][] = $extract_data_cb($file, $ipath, $cfg['props']);
                             }
                         } else {
                             $result["@files:{$im}"] = $extract_data_cb($files[$igroup], $ipath, $cfg['props']);
                         }
                     }
                 };
                 continue;
             }
             if (key_exists($key, $entity_associations) && $entity_associations[$key]['isOwningSide']) {
                 $keys[$key] = 'e.' . $key;
             } elseif (in_array($key, $entity_properties)) {
                 $keys[$key] = 'e.' . $key;
             } elseif ($class::usesTypes() && $key === 'type') {
                 $keys[$key] = 'e._type';
             } elseif ($class::usesTaxonomies() && in_array($key, $taxonomies)) {
                 $taxo_num++;
                 $tr_alias = "tr{$taxo_num}";
                 $t_alias = "t{$taxo_num}";
                 $taxonomy_id = $taxonomies_ids[$key];
                 $keys[$key] = "{$t_alias}.term";
                 $dql_joins .= str_replace('{ALIAS_TR}', $tr_alias, str_replace('{ALIAS_T}', $t_alias, str_replace('{TAXO}', $taxonomy_id, $dql_join_term_template)));
             } elseif ($class::usesMetadata() && in_array($key, $entity_metadata)) {
                 $meta_num++;
                 $meta_alias = "m{$meta_num}";
                 $keys[$key] = "{$meta_alias}.value";
                 $dql_joins .= str_replace('{ALIAS}', $meta_alias, str_replace('{KEY}', $key, $dql_join_template));
             } elseif ($key[0] != '_' && $key != 'callback') {
                 $this->apiErrorResponse("property {$key} does not exists");
             } else {
                 continue;
             }
             $dqls[] = $this->_API_find_parseParam($keys[$key], $val);
         }
         if ($order) {
             $new_order = [];
             foreach (explode(',', $order) as $prop) {
                 $key = trim(preg_replace('#asc|desc#i', '', $prop));
                 if (key_exists($key, $keys)) {
                     $new_order[] = str_ireplace($key, $keys[$key], $prop);
                 } elseif (in_array($key, $entity_properties)) {
                     $new_order[] = str_ireplace($key, 'e.' . $key, $prop);
                 } elseif (in_array($key, $entity_metadata)) {
                     $meta_num++;
                     $meta_alias = "m{$meta_num}";
                     $dql_joins .= str_replace('{ALIAS}', $meta_alias, str_replace('{KEY}', $key, $dql_join_template));
                     $new_order[] = str_replace($key, "{$meta_alias}.value", $prop);
                 }
             }
             $order = "ORDER BY " . implode(', ', $new_order);
         }
         $dql_where = implode($op, $dqls);
         if ($metadata_class) {
             $metadata_class = ", {$metadata_class} m";
         }
         $dql_where = $dql_where ? "WHERE {$dql_where}" : "";
         if (in_array('status', $entity_properties)) {
             $status_where = is_array($permissions) && in_array('view', $permissions) ? 'e.status >= 0' : 'e.status > 0';
             $dql_where = $dql_where ? "{$dql_where} AND {$status_where}" : "WHERE {$status_where}";
         }
         if ($keyword) {
             $repo = $this->repo();
             if ($repo->usesKeyword()) {
                 $ids = implode(',', $repo->getIdsByKeyword($keyword));
                 $dql_where .= $ids ? "AND e.id IN({$ids})" : 'AND e.id < 0';
             }
         }
         if ($select_metadata) {
             $dql_select .= ', meta';
             $meta_keys = implode("', '", $select_metadata);
             $dql_select_joins .= " LEFT JOIN e.__metadata meta WITH meta.key IN ('{$meta_keys}')";
         }
         if (in_array('terms', $select)) {
             $dql_select .= ', termRelations, term';
             $dql_select_joins .= " LEFT JOIN e.__termRelations termRelations LEFT JOIN termRelations.term term";
         }
         if (in_array('owner', $select) || array_filter($select, function ($prop) {
             return substr($prop, 0, 6) == 'owner.';
         })) {
             $dql_select .= ', _owner';
             $dql_select_joins .= " LEFT JOIN e.owner _owner";
         }
         // unset sql_select and dql_select_joins if using permissions filters to reduce memory usage
         if (!$findOne && $permissions) {
             $dql_select = '';
             $dql_select_joins = '';
         }
         $final_dql = "\n                SELECT\n                    e {$dql_select}\n                FROM\n                    {$class} e\n\n                    {$dql_joins}\n                    {$dql_select_joins}\n\n                {$dql_where}\n\n               {$order}";
         $result[] = "{$final_dql}";
         if ($app->config['app.log.apiDql']) {
             $app->log->debug("API DQL: " . $final_dql);
         }
         $query = $app->em->createQuery($final_dql);
         if ($app->user->is('superAdmin') && isset($_GET['@debug'])) {
             if (isset($_GET['@type']) && $_GET['@type'] == 'html') {
                 echo '<pre style="color:red">';
             }
             echo "\nDQL Query:\n";
             echo "{$final_dql}\n\n";
             echo "DQL params: ";
             print_r($this->_apiFindParamList);
             echo "\n\nSQL Query\n";
             echo "\n{$query->getSQL()}\n\n";
         }
         // cache
         if ($app->config['app.useApiCache'] && $this->getApiCacheLifetime()) {
             $query->useResultCache(true, $this->getApiCacheLifetime());
         }
         $query->setParameters($this->_apiFindParamList);
         $processEntity = function ($r) use($append_files_cb, $select) {
             $entity = [];
             $append_files_cb($entity, $r);
             foreach ($select as $i => $prop) {
                 $prop = trim($prop);
                 try {
                     if (strpos($prop, '.')) {
                         $props = explode('.', $prop);
                         $current_object = $r;
                         foreach ($props as $pk => $p) {
                             if ($p === 'permissionTo' && $pk === count($props) - 2) {
                                 $current_object = $current_object->canUser($props[$pk + 1]);
                                 break;
                             } else {
                                 $current_object = $current_object->{$p};
                                 if (!is_object($current_object)) {
                                     break;
                                 }
                             }
                         }
                         $prop_value = $current_object;
                     } else {
                         $prop_value = $r->{$prop};
                     }
                     if (is_object($prop_value) && $prop_value instanceof \Doctrine\Common\Collections\Collection) {
                         $prop_value = $prop_value->toArray();
                     }
                     if (strpos($prop, '.')) {
                         $props = explode('.', $prop);
                         $carray =& $entity;
                         for ($i = 0; $i < count($props) - 1; $i++) {
                             $p = $props[$i];
                             if (!isset($carray[$p])) {
                                 $carray[$p] = [];
                             }
                             $carray =& $carray[$p];
                         }
                         $carray[array_pop($props)] = $prop_value;
                     } else {
                         $entity[$prop] = $prop_value;
                     }
                 } catch (\Exception $e) {
                 }
             }
             return $entity;
         };
         if ($findOne) {
             $query->setFirstResult(0)->setMaxResults(1);
             $paginator = new Paginator($query, $fetchJoinCollection = true);
             if (count($paginator)) {
                 $r = $paginator->getIterator()->current();
                 if ($permissions) {
                     foreach ($permissions as $perm) {
                         $perm = trim($perm);
                         if ($perm[0] === '!') {
                             if ($r->canUser(substr($perm, 1))) {
                                 $r = null;
                                 break;
                             }
                         } else {
                             if (!$r->canUser($perm)) {
                                 $r = null;
                                 break;
                             }
                         }
                     }
                 }
                 if ($r) {
                     $entity = $processEntity($r);
                 }
             } else {
                 $entity = null;
             }
             return $entity;
         } else {
             if ($permissions) {
                 $rs = $query->getResult();
                 $result = [];
                 $rs = array_values(array_filter($rs, function ($entity) use($permissions) {
                     foreach ($permissions as $perm) {
                         $perm = trim($perm);
                         if ($perm[0] === '!') {
                             $not = true;
                             $_perm = substr($perm, 1);
                         } else {
                             $not = false;
                             $_perm = $perm;
                         }
                         $can = $entity->canUser($_perm);
                         return $not ? !$can : $can;
                     }
                     return true;
                 }));
                 if (!$page) {
                     $page = 1;
                 }
                 $rs_count = count($rs);
                 if ($page && $limit) {
                     $offset = ($page - 1) * $limit;
                     $rs = array_slice($rs, $offset, $limit);
                 }
             } else {
                 if ($limit) {
                     if (!$page) {
                         $page = 1;
                     }
                     $offset = ($page - 1) * $limit;
                     $query->setFirstResult($offset)->setMaxResults($limit);
                     $paginator = new Paginator($query, $fetchJoinCollection = true);
                     $rs_count = $paginator->count();
                     $rs = $paginator->getIterator()->getArrayCopy();
                 } else {
                     $rs = $query->getResult();
                     $rs_count = count($rs);
                 }
             }
             if ($counting) {
                 return count($rs);
             }
             $this->apiAddHeaderMetadata($rs, $rs_count);
             $result = array_map(function ($entity) use($processEntity) {
                 return $processEntity($entity);
             }, $rs);
             return $result;
         }
     }
 }
Esempio n. 28
0
use Model\Entities\Employee;
require_once __DIR__ . '/../../bootstrap.php';
Bootstrap::init();
Bootstrap::check(__DIR__);
$cache = Bootstrap::$config['cache'] ? new FilesystemCache(__DIR__ . '/temp') : NULL;
$config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/model/entities'], TRUE, __DIR__ . '/model/entities/proxies', $cache, FALSE);
$config->setProxyNamespace('Model\\Entities\\Proxies');
$config->setAutoGenerateProxyClasses(TRUE);
// we need __toString on DateTime, since UoW converts composite primary keys to string
// (who the hell invented composite PKs :P)
Type::overrideType(Type::DATE, 'Model\\Types\\DateType');
Type::overrideType(Type::DATETIME, 'Model\\Types\\DateTimeType');
$em = EntityManager::create(['driver' => Bootstrap::$config['db']['driverpdo'], 'user' => Bootstrap::$config['db']['user'], 'password' => Bootstrap::$config['db']['password'], 'dbname' => Bootstrap::$config['db']['dbname']], $config);
$startTime = -microtime(TRUE);
ob_start();
$qb = $em->createQueryBuilder()->from('Model\\Entities\\Employee', 'e')->select('e')->innerJoin('e.salaries', 's')->addSelect('s')->innerJoin('e.affiliatedDepartments', 'd')->addSelect('d')->innerJoin('d.department', 'dd')->addSelect('dd')->setMaxResults(Bootstrap::$config['limit'])->getQuery();
$paginator = new Paginator($qb);
foreach ($paginator->getIterator() as $employee) {
    echo $employee->getFirstName(), ' ', $employee->getLastName(), ' (', $employee->getId(), ")\n";
    echo "Salaries:\n";
    foreach ($employee->getSalaries() as $salary) {
        echo $salary->getAmount() . "\n";
    }
    echo "Departments:\n";
    foreach ($employee->getAffiliatedDepartments() as $department) {
        echo $department->getDepartment()->getName() . "\n";
    }
}
ob_end_clean();
$endTime = microtime(TRUE);
Bootstrap::result('Doctrine2', '~2.4.0', $startTime, $endTime);
 /**
  * Public pagination method
  *
  * @\Mmoreram\ControllerExtraBundle\Annotation\Paginator(
  *      attributes = "paginatorAttributes",
  *      class = {
  *          "factory" = "Mmoreram\ControllerExtraBundle\Tests\FakeBundle\Factory\FakeFactory",
  *          "method" = "createNonStatic",
  *          "static" = false
  *      },
  *      limit = "#limit#",
  *      page = "#page#",
  *      wheres = {
  *          { "x", "id" , "LIKE", "#id#", true }
  *      },
  * )
  *
  * @\Mmoreram\ControllerExtraBundle\Annotation\JsonResponse()
  */
 public function paginatorRequestAction(Paginator $paginator, PaginatorAttributes $paginatorAttributes)
 {
     return array('count' => $paginator->getIterator()->count(), 'totalPages' => $paginatorAttributes->getTotalPages(), 'totalElements' => $paginatorAttributes->getTotalElements(), 'currentPage' => $paginatorAttributes->getCurrentPage());
 }
Esempio n. 30
0
 /**
  * Finds and displays a Commento entity.
  *
  * @Route("/{id}", name="commento_show")
  * @Method("GET")
  * @Template("AppBundle::comments-page.html.twig")
  */
 public function showAction($id)
 {
     $em = $this->getDoctrine()->getManager();
     $viaggio = $em->getRepository('AppBundle:Viaggio')->find($id);
     $viaggio_id = $viaggio->getId();
     $entity = $em->getRepository('AppBundle:Commento')->findBy(['viaggio' => $id]);
     $user = $this->container->get('security.context')->getToken()->getUser();
     //pagination
     $limit = 4;
     $page = $this->getRequest()->query->get("page", 1);
     $thisPage = $page;
     $query = $em->createQuery("SELECT commento\n            FROM AppBundle:Commento commento\n            JOIN AppBundle:Viaggio viaggio WHERE (commento.viaggio = {$viaggio_id})\n            ORDER BY commento.id DESC")->setFirstResult($limit * ($page - 1))->setMaxResults($limit);
     $paginator = new Paginator($query, $fetchJoinCollection = true);
     $maxPages = ceil($paginator->count() / $limit);
     $birthDate = $user->getDataDiNascita();
     $age = null;
     if ($birthDate != null) {
         //explode the date to get month, day and year
         $birthDate = explode("-", $birthDate);
         //get age from date or birthdate
         $age = date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? date("Y") - $birthDate[2] - 1 : date("Y") - $birthDate[2];
     }
     $ultimaSalvata = $em->getRepository('AppBundle:Viaggio')->findOneBy(array('utente' => $user->getId(), 'salvato' => true), array('id' => 'DESC'));
     // if (!$entity) {
     //     throw $this->createNotFoundException('Unable to find Commento entity.');
     // }
     $deleteForm = $this->createDeleteForm($id);
     return array('viaggio' => $viaggio, 'user' => $user, 'eta' => $age, 'salvata' => $ultimaSalvata, 'delete_form' => $deleteForm->createView(), 'maxPages' => $maxPages, 'thisPage' => $thisPage, 'issues' => $paginator->getIterator());
 }