3 namespace Rapsys\AirBundle\Repository
; 
   5 use Symfony\Component\Translation\TranslatorInterface
; 
   6 use Doctrine\DBAL\Types\Type
; 
   7 use Doctrine\ORM\Query\ResultSetMapping
; 
   8 use Doctrine\ORM\Query
; 
  13 class SessionRepository 
extends \Doctrine\ORM\EntityRepository 
{ 
  14         ///Set accuweather max number of daily pages 
  15         const ACCUWEATHER_DAILY 
= 12; 
  17         ///Set accuweather max number of hourly pages 
  18         const ACCUWEATHER_HOURLY 
= 3; 
  21         const GUEST_DELAY 
= 2; 
  24         const REGULAR_DELAY 
= 3; 
  27         const SENIOR_DELAY 
= 4; 
  30         //TODO: document utf-8 codes ? 
  33                 'Morning' => 'π
', #0001f305 
  34                 'Afternoon' => 'βοΈ', #2600 
  35                 'Evening' => 'π', #0001f307 
  36                 'After' => 'β¨', #2728 
  38                 'Cleary' => 'β', #2600 
  39                 'Sunny' => 'β
', #26c5 
  40                 'Cloudy' => 'β', #2601 
  41                 'Winty' => 'βοΈ', #2744 
  42                 'Rainy' => 'π', #0001f302 
  43                 'Stormy' => 'β' #2614 
  47          * Find session by location, slot and date 
  49          * @param $location The location 
  50          * @param $slot The slot 
  51          * @param $date The datetime 
  53         public function findOneByLocationSlotDate($location, $slot, $date) { 
  55                 return $this->getEntityManager() 
  56                         ->createQuery('SELECT s FROM RapsysAirBundle:Session s WHERE (s.location = :location AND s.slot = :slot AND s.date = :date)') 
  57                         ->setParameter('location', $location) 
  58                         ->setParameter('slot', $slot) 
  59                         ->setParameter('date', $date) 
  64          * Find sessions by date period 
  66          * @param $period The date period 
  68         public function findAllByDatePeriod($period) { 
  70                 return $this->getEntityManager() 
  71                         ->createQuery('SELECT s FROM RapsysAirBundle:Session s WHERE s.date BETWEEN :begin AND :end') 
  72                         ->setParameter('begin', $period->getStartDate()) 
  73                         ->setParameter('end', $period->getEndDate()) 
  78          * Find sessions by location and date period 
  80          * @param $location The location 
  81          * @param $period The date period 
  83         public function findAllByLocationDatePeriod($location, $period) { 
  85                 return $this->getEntityManager() 
  86                         ->createQuery('SELECT s FROM RapsysAirBundle:Session s WHERE (s.location = :location AND s.date BETWEEN :begin AND :end)') 
  87                         ->setParameter('location', $location) 
  88                         ->setParameter('begin', $period->getStartDate()) 
  89                         ->setParameter('end', $period->getEndDate()) 
  94          * Find one session by location and user id within last month 
  96          * @param $location The location id 
  97          * @param $user The user id 
  99         public function findOneWithinLastMonthByLocationUser($location, $user) { 
 101                 $em = $this->getEntityManager(); 
 104                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
 105                 $dp = $em->getConnection()->getDatabasePlatform(); 
 107                 //Get quoted table names 
 108                 //XXX: this allow to make this code table name independent 
 110                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
 111                         'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp), 
 117                 //XXX: give the gooddelay to guest just in case 
 120 FROM RapsysAirBundle:Session s 
 121 JOIN RapsysAirBundle:Application a ON (a.id = s.application_id AND a.user_id = :uid AND (a.canceled IS NULL OR TIMESTAMPDIFF(DAY, a.canceled, ADDTIME(s.date, s.begin)) < 1)) 
 122 WHERE s.location_id = :lid AND s.date >= DATE_ADD(DATE_SUB(NOW(), INTERVAL 1 MONTH), INTERVAL :gooddelay DAY) 
 125                 //Replace bundle entity name by table name 
 126                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
 128                 //Get result set mapping instance 
 129                 $rsm = new ResultSetMapping(); 
 132                 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php 
 133                 $rsm->addScalarResult('id', 'id', 'integer') 
 134                         ->addIndexByScalar('id'); 
 138                         ->createNativeQuery($req, $rsm) 
 139                         ->setParameter('lid', $location) 
 140                         ->setParameter('uid', $user) 
 141                         ->setParameter('gooddelay', self
::SENIOR_DELAY
) 
 142                         ->getOneOrNullResult(); 
 146          * Fetch session by id 
 148          * @param $id The session id 
 149          * @param $locale The locale 
 150          * @return array The session data 
 152         public function fetchOneById($id, $locale = null) { 
 154                 $em = $this->getEntityManager(); 
 157                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
 158                 $dp = $em->getConnection()->getDatabasePlatform(); 
 160                 //Get quoted table names 
 161                 //XXX: this allow to make this code table name independent 
 163                         'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp), 
 164                         'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp), 
 165                         'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp), 
 166                         'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp), 
 167                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
 168                         'RapsysAirBundle:Snippet' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Snippet'), $dp), 
 169                         'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp), 
 170                         'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp), 
 178                 //TODO: compute scores ? 
 179                 //TODO: compute delivery date ? (J-3/J-4 ?) 
 185         ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS start, 
 187         ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) AS stop, 
 199         s.location_id AS l_id, 
 202         l.address AS l_address, 
 203         l.zipcode AS l_zipcode, 
 205         l.latitude AS l_latitude, 
 206         l.longitude AS l_longitude, 
 209         s.application_id AS a_id, 
 211         au.pseudonym AS au_pseudonym, 
 212         au.donation AS au_donation, 
 215         p.description AS p_description, 
 216         GROUP_CONCAT(sa.id ORDER BY sa.user_id SEPARATOR "\\n") AS sa_id, 
 217         GROUP_CONCAT(IFNULL(sa.score, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_score, 
 218         GROUP_CONCAT(sa.created ORDER BY sa.user_id SEPARATOR "\\n") AS sa_created, 
 219         GROUP_CONCAT(sa.updated ORDER BY sa.user_id SEPARATOR "\\n") AS sa_updated, 
 220         GROUP_CONCAT(IFNULL(sa.canceled, 'NULL') ORDER BY sa.user_id SEPARATOR "\\n") AS sa_canceled, 
 221         GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS sau_id, 
 222         GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS sau_pseudonym 
 223 FROM RapsysAirBundle:Session AS s 
 224 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id) 
 225 JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id) 
 226 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id) 
 227 LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id) 
 228 LEFT JOIN RapsysAirBundle:Snippet AS p ON (p.location_id = s.location_id AND p.user_id = a.user_id AND p.locale = :locale) 
 229 LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id) 
 230 LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id) 
 236                 //Replace bundle entity name by table name 
 237                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
 239                 //Get result set mapping instance 
 240                 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php 
 241                 $rsm = new ResultSetMapping(); 
 244                 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php 
 245                 $rsm->addScalarResult('id', 'id', 'integer') 
 246                         ->addScalarResult('date', 'date', 'date') 
 247                         ->addScalarResult('begin', 'begin', 'time') 
 248                         ->addScalarResult('start', 'start', 'datetime') 
 249                         ->addScalarResult('length', 'length', 'time') 
 250                         ->addScalarResult('stop', 'stop', 'datetime') 
 251                         ->addScalarResult('rainfall', 'rainfall', 'float') 
 252                         ->addScalarResult('rainrisk', 'rainrisk', 'float') 
 253                         ->addScalarResult('realfeel', 'realfeel', 'float') 
 254                         ->addScalarResult('realfeelmin', 'realfeelmin', 'float') 
 255                         ->addScalarResult('realfeelmax', 'realfeelmax', 'float') 
 256                         ->addScalarResult('temperature', 'temperature', 'float') 
 257                         ->addScalarResult('temperaturemin', 'temperaturemin', 'float') 
 258                         ->addScalarResult('temperaturemax', 'temperaturemax', 'float') 
 259                         ->addScalarResult('locked', 'locked', 'datetime') 
 260                         ->addScalarResult('created', 'created', 'datetime') 
 261                         ->addScalarResult('updated', 'updated', 'datetime') 
 262                         ->addScalarResult('l_id', 'l_id', 'integer') 
 263                         ->addScalarResult('l_short', 'l_short', 'string') 
 264                         ->addScalarResult('l_title', 'l_title', 'string') 
 265                         ->addScalarResult('l_address', 'l_address', 'string') 
 266                         ->addScalarResult('l_zipcode', 'l_zipcode', 'string') 
 267                         ->addScalarResult('l_city', 'l_city', 'string') 
 268                         ->addScalarResult('l_latitude', 'l_latitude', 'float') 
 269                         ->addScalarResult('l_longitude', 'l_longitude', 'float') 
 270                         ->addScalarResult('t_id', 't_id', 'integer') 
 271                         ->addScalarResult('t_title', 't_title', 'string') 
 272                         ->addScalarResult('a_id', 'a_id', 'integer') 
 273                         ->addScalarResult('au_id', 'au_id', 'integer') 
 274                         ->addScalarResult('au_pseudonym', 'au_pseudonym', 'string') 
 275                         ->addScalarResult('au_donation', 'au_donation', 'string') 
 276                         ->addScalarResult('au_site', 'au_site', 'string') 
 277                         ->addScalarResult('p_id', 'p_id', 'integer') 
 278                         ->addScalarResult('p_description', 'p_description', 'text') 
 279                         //XXX: is a string because of \n separator 
 280                         ->addScalarResult('sa_id', 'sa_id', 'string') 
 281                         //XXX: is a string because of \n separator 
 282                         ->addScalarResult('sa_score', 'sa_score', 'string') 
 283                         //XXX: is a string because of \n separator 
 284                         ->addScalarResult('sa_created', 'sa_created', 'string') 
 285                         //XXX: is a string because of \n separator 
 286                         ->addScalarResult('sa_updated', 'sa_updated', 'string') 
 287                         //XXX: is a string because of \n separator 
 288                         ->addScalarResult('sa_canceled', 'sa_canceled', 'string') 
 289                         //XXX: is a string because of \n separator 
 290                         ->addScalarResult('sau_id', 'sau_id', 'string') 
 291                         //XXX: is a string because of \n separator 
 292                         ->addScalarResult('sau_pseudonym', 'sau_pseudonym', 'string') 
 293                         ->addIndexByScalar('id'); 
 297                         ->createNativeQuery($req, $rsm) 
 298                         ->setParameter('sid', $id) 
 299                         ->setParameter('locale', $locale) 
 300                         ->getOneOrNullResult(); 
 304          * Fetch sessions calendar with translated location by date period 
 306          * @param $translator The TranslatorInterface instance 
 307          * @param $period The date period 
 308          * @param $locationId The location id 
 309          * @param $sessionId The session id 
 310          * @param $granted The session is granted 
 312         public function fetchCalendarByDatePeriod(TranslatorInterface 
$translator, $period, $locationId = null, $sessionId = null, $granted = false) { 
 314                 $em = $this->getEntityManager(); 
 317                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
 318                 $dp = $em->getConnection()->getDatabasePlatform(); 
 320                 //Get quoted table names 
 321                 //XXX: this allow to make this code table name independent 
 323                         'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp), 
 324                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
 325                         'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp), 
 326                         'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp), 
 327                         'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp), 
 328                         'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp), 
 329                         'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp), 
 335                 //TODO: change as_u_* in sau_*, a_u_* in au_*, etc, see request up 
 336                 $req = 'SELECT s.id, s.date, s.rainrisk, s.rainfall, s.realfeel, s.temperature, s.location_id AS l_id, l.short AS l_short, l.title AS l_title, s.slot_id AS t_id, t.title AS t_title, s.application_id AS a_id, a.user_id AS a_u_id, au.pseudonym AS a_u_pseudonym, GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_id, GROUP_CONCAT(sau.pseudonym ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_pseudonym 
 337                         FROM RapsysAirBundle:Session AS s 
 338                         JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id) 
 339                         JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id) 
 340                         '.($granted?'':'LEFT ').'JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id) 
 341                         '.($granted?'':'LEFT ').'JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id) 
 342                         LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id) 
 343                         LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id) 
 344                         WHERE s.date BETWEEN :begin AND :end 
 345                         '.(!empty($locationId)?'AND s.location_id = :lid':'').' 
 349                 //Replace bundle entity name by table name 
 350                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
 352                 //Get result set mapping instance 
 353                 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php 
 354                 $rsm = new ResultSetMapping(); 
 357                 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php 
 358                 //addScalarResult($sqlColName, $resColName, $type = 'string'); 
 359                 $rsm->addScalarResult('id', 'id', 'integer') 
 360                         ->addScalarResult('date', 'date', 'date') 
 361                         ->addScalarResult('rainrisk', 'rainrisk', 'float') 
 362                         ->addScalarResult('rainfall', 'rainfall', 'float') 
 363                         ->addScalarResult('realfeel', 'realfeel', 'float') 
 364                         ->addScalarResult('temperature', 'temperature', 'float') 
 365                         ->addScalarResult('t_id', 't_id', 'integer') 
 366                         ->addScalarResult('t_title', 't_title', 'string') 
 367                         ->addScalarResult('l_id', 'l_id', 'integer') 
 368                         ->addScalarResult('l_short', 'l_short', 'string') 
 369                         ->addScalarResult('l_title', 'l_title', 'string') 
 370                         ->addScalarResult('a_id', 'a_id', 'integer') 
 371                         ->addScalarResult('a_u_id', 'a_u_id', 'integer') 
 372                         ->addScalarResult('a_u_pseudonym', 'a_u_pseudonym', 'string') 
 373                         //XXX: is a string because of \n separator 
 374                         ->addScalarResult('as_u_id', 'as_u_id', 'string') 
 375                         //XXX: is a string because of \n separator 
 376                         ->addScalarResult('as_u_pseudonym', 'as_u_pseudonym', 'string') 
 377                         ->addIndexByScalar('id'); 
 381                         ->createNativeQuery($req, $rsm) 
 382                         ->setParameter('begin', $period->getStartDate()) 
 383                         ->setParameter('end', $period->getEndDate()); 
 385                 //Add optional location id 
 386                 if (!empty($locationId)) { 
 387                         $res->setParameter('lid', $locationId); 
 391                 $res = $res->getResult(); 
 399                 //Iterate on each day 
 400                 foreach($period as $date) { 
 401                         //Init day in calendar 
 402                         $calendar[$Ymd = $date->format('Ymd')] = [ 
 403                                 'title' => $date->format('d'), 
 408                         //Detect month change 
 409                         if ($month != $date->format('m')) { 
 410                                 $month = $date->format('m'); 
 411                                 //Append month for first day of month 
 412                                 //XXX: except if today to avoid double add 
 413                                 if ($date->format('U') != strtotime('today')) { 
 414                                         $calendar[$Ymd]['title'] .= '/'.$month; 
 418                         if ($date->format('U') == ($today = strtotime('today'))) { 
 419                                 $calendar[$Ymd]['title'] .= '/'.$month; 
 420                                 $calendar[$Ymd]['current'] = true; 
 421                                 $calendar[$Ymd]['class'][] = 'current'; 
 423                         //Disable passed days 
 424                         if ($date->format('U') < $today) { 
 425                                 $calendar[$Ymd]['disabled'] = true; 
 426                                 $calendar[$Ymd]['class'][] = 'disabled'; 
 428                         //Set next month days 
 429                         if ($date->format('m') > date('m')) { 
 430                                 $calendar[$Ymd]['next'] = true; 
 431                                 $calendar[$Ymd]['class'][] = 'next'; 
 434                         //Iterate on each session to find the one of the day 
 435                         foreach($res as $session) { 
 436                                 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) { 
 437                                         //Count number of application 
 438                                         $count = count(explode("\n", $session['as_u_id'])); 
 442                                         if (!empty($session['a_id'])) { 
 443                                                 $applications = [ $session['a_u_id'] => $session['a_u_pseudonym'] ]; 
 444                                                 $class[] = 'granted'; 
 445                                         } elseif ($count == 0) { 
 446                                                 $class[] = 'orphaned'; 
 447                                         } elseif ($count > 1) { 
 448                                                 $class[] = 'disputed'; 
 450                                                 $class[] = 'pending'; 
 453                                         if ($sessionId == $session['id']) { 
 454                                                 $class[] = 'highlight'; 
 458                                         //XXX: realfeel may be null, temperature should not 
 459                                         $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature']; 
 462                                         //XXX: rainfall may be null 
 463                                         if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) { 
 464                                                 $weather = self
::GLYPHS
['Stormy']; 
 465                                         } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) { 
 466                                                 $weather = self
::GLYPHS
['Rainy']; 
 467                                         } elseif ($temperature > 24) { 
 468                                                 $weather = self
::GLYPHS
['Cleary']; 
 469                                         } elseif ($temperature > 17) { 
 470                                                 $weather = self
::GLYPHS
['Sunny']; 
 471                                         } elseif ($temperature > 10) { 
 472                                                 $weather = self
::GLYPHS
['Cloudy']; 
 473                                         } elseif ($temperature !== null) { 
 474                                                 $weather = self
::GLYPHS
['Winty']; 
 482                                         //Check if realfeel is available 
 483                                         if ($session['realfeel'] !== null) { 
 484                                                 $weathertitle[] = $session['realfeel'].'Β°R'; 
 487                                         //Check if temperature is available 
 488                                         if ($session['temperature'] !== null) { 
 489                                                 $weathertitle[] = $session['temperature'].'Β°C'; 
 492                                         //Check if rainrisk is available 
 493                                         if ($session['rainrisk'] !== null) { 
 494                                                 $weathertitle[] = ($session['rainrisk']*100).'%'; 
 497                                         //Check if rainfall is available 
 498                                         if ($session['rainfall'] !== null) { 
 499                                                 $weathertitle[] = $session['rainfall'].'mm'; 
 504                                                 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':') 
 507                                         //Fetch pseudonyms from session applications 
 508                                         $applications +
= array_combine(explode("\n", $session['as_u_id']), array_map(function ($v) {return '- '.$v
;}, explode("\n", $session['as_u_pseudonym']))); 
 510                                         //Check that session is not granted 
 511                                         if (empty($session['a_id'])) { 
 512                                                 //With location id and unique application 
 513                                                 if ($locationId && $count == 1) { 
 514                                                         //Set unique application pseudonym as title 
 515                                                         $title = $session['as_u_pseudonym']; 
 516                                                 //Without location id or multiple application 
 518                                                         //Set location title with optional count 
 519                                                         $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':''); 
 523                                                 //Replace granted application 
 524                                                 $applications[$session['a_u_id']] = '* '.$session['a_u_pseudonym']; 
 525                                                 //Set pseudonym with optional location title and count 
 526                                                 $title = $session['a_u_pseudonym'].($locationId?'':' '.$translator->trans('at '.$session['l_short'])).($count > 1 ? ' ['.$count.']':''); 
 530                                         $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [ 
 531                                                 'id' => $session['id'], 
 534                                                 'slot' => self
::GLYPHS
[$session['t_title']], 
 535                                                 'slottitle' => $translator->trans($session['t_title']), 
 536                                                 'weather' => $weather, 
 537                                                 'weathertitle' => implode(' ', $weathertitle), 
 538                                                 'applications' => $applications 
 544                         ksort($calendar[$Ymd]['sessions']); 
 552          * Fetch sessions calendar with translated location by date period and user 
 554          * @param $translator The TranslatorInterface instance 
 555          * @param $period The date period 
 556          * @param $userId The user id 
 557          * @param $sessionId The session id 
 559         public function fetchUserCalendarByDatePeriod(TranslatorInterface 
$translator, $period, $userId = null, $sessionId = null) { 
 561                 $em = $this->getEntityManager(); 
 564                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
 565                 $dp = $em->getConnection()->getDatabasePlatform(); 
 567                 //Get quoted table names 
 568                 //XXX: this allow to make this code table name independent 
 570                         'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp), 
 571                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
 572                         'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp), 
 573                         'RapsysAirBundle:Group' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Group'), $dp), 
 574                         'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp), 
 575                         'RapsysAirBundle:Slot' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Slot'), $dp), 
 576                         'RapsysAirBundle:User' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:User'), $dp), 
 582                 $req = 'SELECT s.id, s.date, s.rainrisk, s.rainfall, s.realfeel, s.temperature, s.location_id AS l_id, l.short AS l_short, l.title AS l_title, s.slot_id AS t_id, t.title AS t_title, s.application_id AS a_id, a.user_id AS a_u_id, au.pseudonym AS a_u_pseudonym, GROUP_CONCAT(sa.user_id ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_id, GROUP_CONCAT(CONCAT("- ", sau.pseudonym) ORDER BY sa.user_id SEPARATOR "\\n") AS as_u_pseudonym 
 583                         FROM RapsysAirBundle:Session AS s 
 584                         JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id) 
 585                         JOIN RapsysAirBundle:Slot AS t ON (t.id = s.slot_id) 
 586                         '.($userId?'JOIN RapsysAirBundle:Application AS sua ON (sua.session_id = s.id)':'').' 
 587                         LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id) 
 588                         LEFT JOIN RapsysAirBundle:User AS au ON (au.id = a.user_id) 
 589                         LEFT JOIN RapsysAirBundle:Application AS sa ON (sa.session_id = s.id) 
 590                         LEFT JOIN RapsysAirBundle:User AS sau ON (sau.id = sa.user_id) 
 591                         WHERE s.date BETWEEN :begin AND :end 
 592                         '.($userId?'AND sua.user_id = :uid':'').' 
 596                 //Replace bundle entity name by table name 
 597                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
 599                 //Get result set mapping instance 
 600                 //XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php 
 601                 $rsm = new ResultSetMapping(); 
 604                 //XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php 
 605                 //addScalarResult($sqlColName, $resColName, $type = 'string'); 
 606                 $rsm->addScalarResult('id', 'id', 'integer') 
 607                         ->addScalarResult('date', 'date', 'date') 
 608                         ->addScalarResult('rainrisk', 'rainrisk', 'float') 
 609                         ->addScalarResult('rainfall', 'rainfall', 'float') 
 610                         ->addScalarResult('realfeel', 'realfeel', 'float') 
 611                         ->addScalarResult('temperature', 'temperature', 'float') 
 612                         ->addScalarResult('t_id', 't_id', 'integer') 
 613                         ->addScalarResult('t_title', 't_title', 'string') 
 614                         ->addScalarResult('l_id', 'l_id', 'integer') 
 615                         ->addScalarResult('l_short', 'l_short', 'string') 
 616                         ->addScalarResult('l_title', 'l_title', 'string') 
 617                         ->addScalarResult('a_id', 'a_id', 'integer') 
 618                         ->addScalarResult('a_u_id', 'a_u_id', 'integer') 
 619                         ->addScalarResult('a_u_pseudonym', 'a_u_pseudonym', 'string') 
 620                         //XXX: is a string because of \n separator 
 621                         ->addScalarResult('as_u_id', 'as_u_id', 'string') 
 622                         //XXX: is a string because of \n separator 
 623                         ->addScalarResult('as_u_pseudonym', 'as_u_pseudonym', 'string') 
 624                         ->addIndexByScalar('id'); 
 628                         ->createNativeQuery($req, $rsm) 
 629                         ->setParameter('begin', $period->getStartDate()) 
 630                         ->setParameter('end', $period->getEndDate()) 
 631                         ->setParameter('uid', $userId) 
 640                 //Iterate on each day 
 641                 foreach($period as $date) { 
 642                         //Init day in calendar 
 643                         $calendar[$Ymd = $date->format('Ymd')] = [ 
 644                                 'title' => $date->format('d'), 
 649                         //Detect month change 
 650                         if ($month != $date->format('m')) { 
 651                                 $month = $date->format('m'); 
 652                                 //Append month for first day of month 
 653                                 //XXX: except if today to avoid double add 
 654                                 if ($date->format('U') != strtotime('today')) { 
 655                                         $calendar[$Ymd]['title'] .= '/'.$month; 
 659                         if ($date->format('U') == ($today = strtotime('today'))) { 
 660                                 $calendar[$Ymd]['title'] .= '/'.$month; 
 661                                 $calendar[$Ymd]['current'] = true; 
 662                                 $calendar[$Ymd]['class'][] = 'current'; 
 664                         //Disable passed days 
 665                         if ($date->format('U') < $today) { 
 666                                 $calendar[$Ymd]['disabled'] = true; 
 667                                 $calendar[$Ymd]['class'][] = 'disabled'; 
 669                         //Set next month days 
 670                         if ($date->format('m') > date('m')) { 
 671                                 $calendar[$Ymd]['next'] = true; 
 672                                 $calendar[$Ymd]['class'][] = 'next'; 
 675                         //Iterate on each session to find the one of the day 
 676                         foreach($res as $session) { 
 677                                 if (($sessionYmd = $session['date']->format('Ymd')) == $Ymd) { 
 678                                         //Count number of application 
 679                                         $count = count(explode("\n", $session['as_u_id'])); 
 683                                         if (!empty($session['a_id'])) { 
 684                                                 $applications = [ $session['a_u_id'] => $session['a_u_pseudonym'] ]; 
 685                                                 if ($session['a_u_id'] == $userId) { 
 686                                                         $class[] = 'granted'; 
 688                                                         $class[] = 'disputed'; 
 690                                         } elseif ($count == 0) { 
 691                                                 $class[] = 'orphaned'; 
 692                                         } elseif ($count > 1) { 
 693                                                 $class[] = 'disputed'; 
 695                                                 $class[] = 'pending'; 
 698                                         if ($sessionId == $session['id']) { 
 699                                                 $class[] = 'highlight'; 
 703                                         //XXX: realfeel may be null, temperature should not 
 704                                         $temperature = $session['realfeel'] !== null ? $session['realfeel'] : $session['temperature']; 
 707                                         //XXX: rainfall may be null 
 708                                         if ($session['rainrisk'] > 0.50 || $session['rainfall'] > 2) { 
 709                                                 $weather = self
::GLYPHS
['Stormy']; 
 710                                         } elseif ($session['rainrisk'] > 0.40 || $session['rainfall'] > 1) { 
 711                                                 $weather = self
::GLYPHS
['Rainy']; 
 712                                         } elseif ($temperature > 24) { 
 713                                                 $weather = self
::GLYPHS
['Cleary']; 
 714                                         } elseif ($temperature > 17) { 
 715                                                 $weather = self
::GLYPHS
['Sunny']; 
 716                                         } elseif ($temperature > 10) { 
 717                                                 $weather = self
::GLYPHS
['Cloudy']; 
 718                                         } elseif ($temperature !== null) { 
 719                                                 $weather = self
::GLYPHS
['Winty']; 
 727                                         //Check if realfeel is available 
 728                                         if ($session['realfeel'] !== null) { 
 729                                                 $weathertitle[] = $session['realfeel'].'Β°R'; 
 732                                         //Check if temperature is available 
 733                                         if ($session['temperature'] !== null) { 
 734                                                 $weathertitle[] = $session['temperature'].'Β°C'; 
 737                                         //Check if rainrisk is available 
 738                                         if ($session['rainrisk'] !== null) { 
 739                                                 $weathertitle[] = ($session['rainrisk']*100).'%'; 
 742                                         //Check if rainfall is available 
 743                                         if ($session['rainfall'] !== null) { 
 744                                                 $weathertitle[] = $session['rainfall'].'mm'; 
 749                                                 0 => $translator->trans($session['t_title']).' '.$translator->trans('at '.$session['l_title']).$translator->trans(':') 
 752                                         //Check that session is not granted 
 753                                         if (empty($session['a_id'])) { 
 754                                                 //Fetch pseudonyms from session applications 
 755                                                 $applications +
= array_combine(explode("\n", $session['as_u_id']), explode("\n", $session['as_u_pseudonym'])); 
 758                                                 //Fetch pseudonyms from session applications 
 759                                                 $applications +
= array_combine(explode("\n", $session['as_u_id']), explode("\n", $session['as_u_pseudonym'])); 
 760                                                 //Replace granted application 
 761                                                 $applications[$session['a_u_id']] = '* '.$session['a_u_pseudonym']; 
 765                                         $title = $translator->trans($session['l_title']).($count > 1 ? ' ['.$count.']':''); 
 768                                         $calendar[$Ymd]['sessions'][$session['t_id'].sprintf('%02d', $session['l_id'])] = [ 
 769                                                 'id' => $session['id'], 
 772                                                 'slot' => self
::GLYPHS
[$session['t_title']], 
 773                                                 'slottitle' => $translator->trans($session['t_title']), 
 774                                                 'weather' => $weather, 
 775                                                 'weathertitle' => implode(' ', $weathertitle), 
 776                                                 'applications' => $applications 
 782                         ksort($calendar[$Ymd]['sessions']); 
 790          * Find all session pending hourly weather 
 792          * @return array<Session> The sessions to update 
 794         public function findAllPendingHourlyWeather() { 
 796                 $em = $this->getEntityManager(); 
 799                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
 800                 $dp = $em->getConnection()->getDatabasePlatform(); 
 802                 //Get quoted table names 
 803                 //XXX: this allow to make this code table name independent 
 805                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
 806                         'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp), 
 808                         ':accuhourly' => self
::ACCUWEATHER_HOURLY
, 
 815                 //Select all sessions starting and stopping in the next 3 days 
 816                 //XXX: select session starting after now and stopping before date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY) 
 818 SELECT s.id, s.slot_id, s.location_id, s.date, s.begin, s.length, s.rainfall, s.rainrisk, s.realfeel, s.realfeelmin, s.realfeelmax, s.temperature, s.temperaturemin, s.temperaturemax, l.zipcode 
 819 FROM RapsysAirBundle:Session AS s 
 820 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id) 
 821 WHERE ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) >= NOW() AND ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) < DATE(ADDDATE(NOW(), INTERVAL :accuhourly DAY)) 
 824                 //Replace bundle entity name by table name 
 825                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
 827                 //Get result set mapping instance 
 828                 $rsm = new ResultSetMapping(); 
 832                         ->addEntityResult('RapsysAirBundle:Session', 's') 
 833                         ->addFieldResult('s', 'id', 'id') 
 834                         ->addFieldResult('s', 'date', 'date') 
 835                         ->addFieldResult('s', 'begin', 'begin') 
 836                         ->addFieldResult('s', 'length', 'length') 
 837                         ->addFieldResult('s', 'rainfall', 'rainfall') 
 838                         ->addFieldResult('s', 'rainrisk', 'rainrisk') 
 839                         ->addFieldResult('s', 'realfeel', 'realfeel') 
 840                         ->addFieldResult('s', 'realfeelmin', 'realfeelmin') 
 841                         ->addFieldResult('s', 'realfeelmax', 'realfeelmax') 
 842                         ->addFieldResult('s', 'temperature', 'temperature') 
 843                         ->addFieldResult('s', 'temperaturemin', 'temperaturemin') 
 844                         ->addFieldResult('s', 'temperaturemax', 'temperaturemax') 
 845                         ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot') 
 846                         ->addFieldResult('o', 'slot_id', 'id') 
 847                         ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location') 
 848                         ->addFieldResult('l', 'location_id', 'id') 
 849                         ->addFieldResult('l', 'zipcode', 'zipcode') 
 850                         ->addIndexBy('s', 'id'); 
 854                         ->createNativeQuery($req, $rsm) 
 859          * Find all session pending daily weather 
 861          * @return array<Session> The sessions to update 
 863         public function findAllPendingDailyWeather() { 
 865                 $em = $this->getEntityManager(); 
 868                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
 869                 $dp = $em->getConnection()->getDatabasePlatform(); 
 871                 //Get quoted table names 
 872                 //XXX: this allow to make this code table name independent 
 874                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
 875                         'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp), 
 877                         ':accudaily' => self
::ACCUWEATHER_DAILY
, 
 878                         ':accuhourly' => self
::ACCUWEATHER_HOURLY
, 
 885                 //Select all sessions stopping after next 3 days 
 886                 //XXX: select session stopping after or equal date(now)+3d as accuweather only provide hourly data for the next 3 days (INTERVAL 3 DAY) 
 888 SELECT s.id, s.slot_id, s.location_id, s.date, s.begin, s.length, s.rainfall, s.rainrisk, s.realfeel, s.realfeelmin, s.realfeelmax, s.temperature, s.temperaturemin, s.temperaturemax, l.zipcode 
 889 FROM RapsysAirBundle:Session AS s 
 890 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id) 
 891 WHERE ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) >= DATE(ADDDATE(NOW(), INTERVAL :accuhourly DAY)) AND ADDDATE(ADDTIME(ADDTIME(s.date, s.begin), s.length), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY) < DATE(ADDDATE(NOW(), INTERVAL :accudaily DAY)) 
 894                 //Replace bundle entity name by table name 
 895                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
 897                 //Get result set mapping instance 
 898                 $rsm = new ResultSetMapping(); 
 902                         ->addEntityResult('RapsysAirBundle:Session', 's') 
 903                         ->addFieldResult('s', 'id', 'id') 
 904                         ->addFieldResult('s', 'date', 'date') 
 905                         ->addFieldResult('s', 'begin', 'begin') 
 906                         ->addFieldResult('s', 'length', 'length') 
 907                         ->addFieldResult('s', 'rainfall', 'rainfall') 
 908                         ->addFieldResult('s', 'rainrisk', 'rainrisk') 
 909                         ->addFieldResult('s', 'realfeel', 'realfeel') 
 910                         ->addFieldResult('s', 'realfeelmin', 'realfeelmin') 
 911                         ->addFieldResult('s', 'realfeelmax', 'realfeelmax') 
 912                         ->addFieldResult('s', 'temperature', 'temperature') 
 913                         ->addFieldResult('s', 'temperaturemin', 'temperaturemin') 
 914                         ->addFieldResult('s', 'temperaturemax', 'temperaturemax') 
 915                         ->addJoinedEntityResult('RapsysAirBundle:Slot', 'o', 's', 'slot') 
 916                         ->addFieldResult('o', 'slot_id', 'id') 
 917                         ->addJoinedEntityResult('RapsysAirBundle:Location', 'l', 's', 'location') 
 918                         ->addFieldResult('l', 'location_id', 'id') 
 919                         ->addFieldResult('l', 'zipcode', 'zipcode') 
 920                         ->addIndexBy('s', 'id'); 
 924                         ->createNativeQuery($req, $rsm) 
 929          * Find every session pending application 
 931          * @return array<Session> The sessions to update 
 933         public function findAllPendingApplication() { 
 935                 $em = $this->getEntityManager(); 
 938                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
 939                 $dp = $em->getConnection()->getDatabasePlatform(); 
 941                 //Get quoted table names 
 942                 //XXX: this allow to make this code table name independent 
 944                         'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp), 
 945                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
 947                         ':regulardelay' => self
::REGULAR_DELAY 
* 24 * 3600, 
 948                         ':seniordelay' => self
::SENIOR_DELAY 
* 24 * 3600, 
 955                 //Select all sessions not locked without application or canceled application within attribution period 
 956                 //XXX: DIFF(start, now) <= IF(DIFF(start, created) <= SENIOR_DELAY in DAY, DIFF(start, created) * 3 / 4, SENIOR_DELAY) 
 957                 //TODO: remonter les donnΓ©es pour le mail ? 
 960 FROM RapsysAirBundle:Session as s 
 961 LEFT JOIN RapsysAirBundle:Application AS a ON (a.id = s.application_id AND a.canceled IS NULL) 
 962 JOIN RapsysAirBundle:Application AS a2 ON (a2.session_id = s.id AND a2.canceled IS NULL) 
 963 WHERE s.locked IS NULL AND a.id IS NULL AND 
 964 TIME_TO_SEC(TIMEDIFF(@dt_start := ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) <= IF( 
 965         TIME_TO_SEC(@td_sc := TIMEDIFF(@dt_start, s.created)) <= :seniordelay, 
 966         ROUND(TIME_TO_SEC(@td_sc) * :regulardelay / :seniordelay), 
 970 ORDER BY @dt_start ASC, s.created ASC 
 974                 //Replace bundle entity name by table name 
 975                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
 977                 //Get result set mapping instance 
 978                 $rsm = new ResultSetMapping(); 
 982                         ->addEntityResult('RapsysAirBundle:Session', 's') 
 983                         ->addFieldResult('s', 'id', 'id') 
 984                         ->addIndexBy('s', 'id'); 
 988                         ->createNativeQuery($req, $rsm) 
 993          * Fetch session best application by session id 
 995          * @param int $id The session id 
 996          * @return Application|null The application or null 
 998         public function findBestApplicationById($id) { 
1000                 $em = $this->getEntityManager(); 
1002                 //Get quote strategy 
1003                 $qs = $em->getConfiguration()->getQuoteStrategy(); 
1004                 $dp = $em->getConnection()->getDatabasePlatform(); 
1006                 //Get quoted table names 
1007                 //XXX: this allow to make this code table name independent 
1009                         'RapsysAirBundle:Application' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Application'), $dp), 
1010                         'RapsysAirBundle:GroupUser' => $qs->getJoinTableName($em->getClassMetadata('RapsysAirBundle:User')->getAssociationMapping('groups'), $em->getClassMetadata('RapsysAirBundle:User'), $dp), 
1011                         'RapsysAirBundle:Location' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Location'), $dp), 
1012                         'RapsysAirBundle:Session' => $qs->getTableName($em->getClassMetadata('RapsysAirBundle:Session'), $dp), 
1013                         //XXX: Set limit used to workaround mariadb subselect optimization 
1014                         ':limit' => PHP_INT_MAX
, 
1016                         ':guestdelay' => self
::GUEST_DELAY 
* 24 * 3600, 
1017                         ':regulardelay' => self
::REGULAR_DELAY 
* 24 * 3600, 
1018                         ':seniordelay' => self
::SENIOR_DELAY 
* 24 * 3600, 
1024                         ':afternoonid' => 2, 
1027                         //XXX: days since last session after which guest regain normal priority 
1029                         //XXX: session count until considered at regular delay 
1031                         //XXX: pn_ratio over which considered at regular delay 
1033                         //XXX: tr_ratio diff over which considered at regular delay 
1040                  * Query session applications ranked by location score, global score, created and user_id 
1042                  * @xxx guest (or less) with application on location within 30 day are only considered within guestdelay 
1044                  * @xxx regular (or less) premium application on hotspot are only considered within regulardelay 
1046                  * @xxx senior (or less) with 5 or less session on location are only considered within seniordelay 
1048                  * @xxx senior (or less) with l_pn_ratio >= 1 are only considered within seniordelay 
1050                  * @xxx senior (or less) with l_tr_ratio >= (o_tr_ratio + 5) are only considered within seniordelay 
1052                  * @xxx only consider session within one year (may be unaccurate by the day with after session) 
1054                  * @xxx rainfall may not be accessible for previous session and other session at d-4 (only at d-2) 
1056                  * @todo ??? feedback the data to inform the rejected users ??? 
1059 SELECT e.id, e.l_score AS score 
1071                 MAX(gu.group_id) AS group_id, 
1086                         AVG(IF(a4.id IS NOT NULL AND s4.temperature IS NOT NULL AND s4.rainfall IS NOT NULL, s4.temperature/(1+s4.rainfall), NULL)) AS o_tr_ratio, 
1103                                 SUM(IF(a3.id IS NOT NULL, 1/ABS(DATEDIFF(ADDDATE(b.date, INTERVAL IF(b.slot_id = :afterid, 1, 0) DAY), ADDDATE(s3.date, INTERVAL IF(s3.slot_id = :afterid, 1, 0) DAY))), 0)) AS g_score, 
1116                                         COUNT(a2.id) AS l_count, 
1117                                         SUM(IF(a2.id IS NOT NULL, 1/ABS(DATEDIFF(ADDDATE(s.date, INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), ADDDATE(s2.date, INTERVAL IF(s2.slot_id = :afterid, 1, 0) DAY))), 0)) AS l_score, 
1118                                         AVG(IF(a2.id IS NOT NULL AND s2.temperature IS NOT NULL AND s2.rainfall IS NOT NULL, s2.temperature/(1+s2.rainfall), NULL)) AS l_tr_ratio, 
1119                                         (SUM(IF(a2.id IS NOT NULL AND s2.premium = 1, 1, 0))+1)/(SUM(IF(a2.id IS NOT NULL AND s2.premium = 0, 1, 0))+1) AS l_pn_ratio, 
1120                                         MIN(IF(a2.id IS NOT NULL, DATEDIFF(ADDDATE(s.date, INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), ADDDATE(s2.date, INTERVAL IF(s2.slot_id = :afterid, 1, 0) DAY)), NULL)) AS l_previous, 
1121                                         TIME_TO_SEC(TIMEDIFF(ADDDATE(ADDTIME(s.date, s.begin), INTERVAL IF(s.slot_id = :afterid, 1, 0) DAY), NOW())) AS remaining, 
1125                                 FROM RapsysAirBundle:Session AS s 
1126                                 JOIN RapsysAirBundle:Location AS l ON (l.id = s.location_id) 
1127                                 JOIN RapsysAirBundle:Application AS a ON (a.session_id = s.id AND a.canceled IS NULL) 
1128                                 LEFT JOIN RapsysAirBundle:Session AS s2 ON (s2.id != s.id AND s2.location_id = s.location_id AND s2.slot_id IN (:afternoonid, :eveningid) AND s2.application_id IS NOT NULL AND s2.locked IS NULL AND s2.date > s.date - INTERVAL 1 YEAR) 
1129                                 LEFT JOIN RapsysAirBundle:Application AS a2 ON (a2.id = s2.application_id AND a2.user_id = a.user_id AND (a2.canceled IS NULL OR TIMESTAMPDIFF(DAY, a2.canceled, ADDDATE(ADDTIME(s2.date, s2.begin), INTERVAL IF(s2.slot_id = :afterid, 1, 0) DAY)) < 1)) 
1135                         LEFT JOIN RapsysAirBundle:Session AS s3 ON (s3.id != b.session_id AND s3.application_id IS NOT NULL AND s3.locked IS NULL AND s3.date > b.date - INTERVAL 1 YEAR) 
1136                         LEFT JOIN RapsysAirBundle:Application AS a3 ON (a3.id = s3.application_id AND a3.user_id = b.user_id AND (a3.canceled IS NULL OR TIMESTAMPDIFF(DAY, a3.canceled, ADDDATE(ADDTIME(s3.date, s3.begin), INTERVAL IF(s3.slot_id = :afterid, 1, 0) DAY)) < 1)) 
1141                 LEFT JOIN RapsysAirBundle:Session AS s4 ON (s4.id != c.session_id AND s4.location_id = c.location_id AND s4.application_id IS NOT NULL AND s4.locked IS NULL AND s4.date > c.date - INTERVAL 1 YEAR) 
1142                 LEFT JOIN RapsysAirBundle:Application AS a4 ON (a4.id = s4.application_id AND a4.user_id != c.user_id AND (a4.canceled IS NULL OR TIMESTAMPDIFF(DAY, a4.canceled, ADDDATE(ADDTIME(s4.date, s4.begin), INTERVAL IF(s4.slot_id = :afterid, 1, 0) DAY)) < 1)) 
1147         LEFT JOIN RapsysAirBundle:GroupUser AS gu ON (gu.user_id = d.user_id) 
1152         IF(e.group_id <= :guestid AND e.l_previous <= :guestwait, e.remaining <= :guestdelay, 1) AND 
1153         IF(e.group_id <= :regularid AND e.premium = 1 AND e.hotspot = 1, e.remaining <= :regulardelay, 1) AND 
1154         IF(e.group_id <= :seniorid AND e.l_count <= :scount, e.remaining <= :regulardelay, 1) AND 
1155         IF(e.group_id <= :seniorid AND e.l_pn_ratio >= :pnratio, e.remaining <= :regulardelay, 1) AND 
1156         IF(e.group_id <= :seniorid AND e.l_tr_ratio >= (e.o_tr_ratio + :trdiff), e.remaining <= :regulardelay, 1) 
1157 ORDER BY e.l_score ASC, e.g_score ASC, e.created ASC, e.user_id ASC 
1160                 //Replace bundle entity name by table name 
1161                 $req = str_replace(array_keys($tables), array_values($tables), $req); 
1163                 //Set update request 
1164                 $upreq = 'UPDATE RapsysAirBundle:Application SET score = :score, updated = NOW() WHERE id = :id'; 
1166                 //Replace bundle entity name by table name 
1167                 $upreq = str_replace(array_keys($tables), array_values($tables), $upreq); 
1169                 //Get result set mapping instance 
1170                 $rsm = new ResultSetMapping(); 
1172                 //Declare all fields 
1174                         ->addEntityResult('RapsysAirBundle:Application', 'a') 
1175                         ->addFieldResult('a', 'id', 'id') 
1176                         ->addFieldResult('a', 'score', 'score') 
1177                         ->addIndexBy('a', 'id'); 
1180                 //XXX: setting limit in subqueries is required to prevent mariadb optimisation 
1182                         ->createNativeQuery($req, $rsm) 
1183                         ->setParameter('sid', $id) 
1184                         //XXX: removed, we update score before returning best candidate 
1185                         //->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR); 
1192                 foreach($applications as $application) { 
1193                         //Check if we already saved best candidate 
1194                         if ($ret === null) { 
1195                                 //Return first application 
1196                                 $ret = $application; 
1199                         //Update application updated field 
1200                         //XXX: updated field is not modified for user with bad behaviour as application is not retrieved until delay is reached 
1201                         $em->getConnection()->executeUpdate($upreq, ['id' => $application->getId(), 'score' => $application->getScore()], ['id' => Type
::INTEGER, 'score' => Type
::FLOAT]); 
1204                 //Return best ranked application