Ejemplo n.º 1
0
 public function topページ_初期表示(\AcceptanceTester $I)
 {
     $I->wantTo('EF0101-UC01-T01 TOPページ 初期表示');
     $I->amOnPage('/');
     // カテゴリ選択ボックス(キーワード検索用)、キーワード検索入力欄、虫眼鏡ボタンが表示されている
     $I->see('全ての商品', '#search #category_id');
     $I->see('', '#search #name');
     $I->see('', '#search .bt_search');
     // カテゴリ名(カテゴリ検索用)が表示されている
     $categories = Fixtures::get('categories');
     foreach ($categories as $category) {
         $I->see($category->getName(), '#search #category_id option');
     }
     //管理側のコンテンツ管理(新着情報管理)に設定されている情報が、順位順に表示されている
     $today = new DateTime();
     $minus1 = $today->sub(new DateInterval('P1D'));
     $minus2 = $today->sub(new DateInterval('P2D'));
     $I->haveInDatabase('dtb_news', array('news_id' => rand(999, 9999), 'news_date' => $minus1->format('Y-m-d 00:00:00'), 'news_title' => 'タイトル1', 'news_comment' => 'コメント1', 'creator_id' => 1, 'rank' => 2, 'create_date' => $today->format('Y-m-d 00:00:00'), 'update_date' => $today->format('Y-m-d 00:00:00')));
     $I->haveInDatabase('dtb_news', array('news_id' => rand(999, 9999), 'news_date' => $minus2->format('Y-m-d 00:00:00'), 'news_title' => 'タイトル2', 'news_comment' => 'コメント2', 'creator_id' => 1, 'rank' => 3, 'create_date' => $today->format('Y-m-d 00:00:00'), 'update_date' => $today->format('Y-m-d 00:00:00')));
     $I->reloadPage();
     $news = Fixtures::get('news');
     $newsset = array();
     $newsset[] = array('date' => $news[0]->getDate(), 'title' => $news[0]->getTitle(), 'comment' => $news[0]->getComment());
     $newsset[] = array('date' => $minus1->format('Y-m-d 00:00:00'), 'title' => 'タイトル1', 'comment' => 'コメント1');
     $newsset[] = array('date' => $minus2->format('Y-m-d 00:00:00'), 'title' => 'タイトル2', 'comment' => 'コメント2');
     foreach ($newsset as $key => $news) {
         $I->see($news['title'], '#news_area .newslist dl:nth-child(' . (count($newsset) - $key) . ') .news_title');
     }
 }
 /**
  * Get the ExRatesTable instance
  *
  * @param \DateTime $pubDate Optional rates table publication date
  *
  * @return ExRatesTable
  *
  * @throws \Exception
  */
 public function getExRatesTable(\DateTime $pubDate = null)
 {
     $this->setSoughtPubDate($pubDate);
     $i = 0;
     do {
         // Limit the number of times the loop repeats
         if ($i === self::MAX_ONE_TIME_API_REQ) {
             throw new \Exception('Max requests to api limit has been reached');
         }
         // If user doesn't want a specific date, try to get the rates from the last working day
         if (!$pubDate) {
             $this->soughtPubDate = $this->soughtPubDate->sub(new \DateInterval('P1D'));
         }
         // Try to find the file in cache, otherwise download it
         if ($this->cachePath && ($cachedXml = $this->getCachedXml())) {
             $rawContent = $cachedXml;
         } else {
             $rawContent = $this->downloadXml();
         }
         // If a specific date is sought then break, otherwise continue
         if ($pubDate) {
             break;
         }
         $i++;
     } while (!$rawContent);
     if (!$rawContent) {
         throw new \Exception('Exchange rates file not found');
     }
     return $this->ratesTableFactory->getInstance($rawContent);
 }
 /**
  * This just setsup some events in the db for running certain tests that query getting events back.
  * @since 4.6.x
  */
 protected function _setup_events()
 {
     //setup some dates we'll use for testing with.
     $timezone = new DateTimeZone('America/Toronto');
     $upcoming_start_date = new DateTime("now +2hours", $timezone);
     $past_start_date = new DateTime("now -2days", $timezone);
     $current_end_date = new DateTime("now +2days", $timezone);
     $current = new DateTime("now", $timezone);
     $formats = array('Y-d-m', 'h:i a');
     $full_format = implode(' ', $formats);
     //setup some datetimes to attach to events.
     $datetimes = array('expired_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $past_start_date->format($full_format), 'DTT_EVT_end' => $past_start_date->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)), 'upcoming_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $upcoming_start_date->format($full_format), 'DTT_EVT_end' => $upcoming_start_date->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)), 'active_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $current->sub(new DateInterval("PT2H"))->format($full_format), 'DTT_EVT_end' => $current_end_date->add(new DateInterval("PT2H"))->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)), 'sold_out_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $upcoming_start_date->format($full_format), 'DTT_EVT_end' => $upcoming_start_date->format($full_format), 'DTT_reg_limit' => 10, 'DTT_sold' => 10, 'timezone' => 'America/Toronto', 'formats' => $formats)), 'inactive_datetime' => $this->factory->datetime->create(array('DTT_EVT_start' => $current->sub(new DateInterval("PT2H"))->format($full_format), 'DTT_EVT_end' => $current_end_date->add(new DateInterval("PT2H"))->format($full_format), 'timezone' => 'America/Toronto', 'formats' => $formats)));
     //setup some events
     $events = $this->factory->event->create_many('4');
     //add datetimes to the events.
     $events[0]->_add_relation_to($datetimes['expired_datetime'], 'Datetime');
     $events[0]->save();
     $events[1]->_add_relation_to($datetimes['upcoming_datetime'], 'Datetime');
     $events[1]->save();
     $events[2]->_add_relation_to($datetimes['active_datetime'], 'Datetime');
     $events[2]->save();
     $events[3]->_add_relation_to($datetimes['sold_out_datetime'], 'Datetime');
     $events[3]->save();
     foreach ($events as $event) {
         $event->set('status', 'publish');
         $event->save();
     }
     //one more event that is just going to be inactive
     $final_event = $this->factory->event->create();
     $final_event->_add_relation_to($datetimes['inactive_datetime'], 'Datetime');
     $final_event->save();
 }
 /**
  * @param BusContextInterface $busContext
  *
  * @throws UnexpectedValueException
  */
 public function start(BusContextInterface $busContext)
 {
     if ($this->daysToKeepDeduplicationData === null) {
         $this->daysToKeepDeduplicationData = 7;
     } elseif (!ctype_digit((string) $this->daysToKeepDeduplicationData)) {
         throw new UnexpectedValueException("Invalid value value used for days to keep deduplication data. Please ensure it is a positive integer.");
     }
     $this->outboxPersister->removeEntriesOlderThan($this->now->sub(new \DateInterval("P{$this->daysToKeepDeduplicationData}D")));
 }
 private function calculaFeriadosMoveis($ano)
 {
     $pascoa = new DateTime();
     $pascoa->setTimestamp(easter_date($ano));
     $this->feriados['pascoa'] = $pascoa->format('d/m');
     $this->feriados['terca_carnaval'] = $pascoa->sub(new DateInterval('P47D'))->format('d/m');
     $this->feriados['quarta_cinzas'] = $pascoa->sub(new DateInterval('P46D'))->format('d/m');
     $this->feriados['sexta_santa'] = $pascoa->sub(new DateInterval('P2D'))->format('d/m');
     $this->feriados['corpus_christi'] = $pascoa->sub(new DateInterval('P60D'))->format('d/m');
 }
Ejemplo n.º 6
0
 public function onPlainFilter_creation_date($filterName, $filterValue, $criteria)
 {
     $curDate = new DateTime();
     if ($filterValue === 'today') {
         $condition = 'created_ts >= "' . $curDate->format('Y-m-d') . '"';
     } elseif ($filterValue === 'week') {
         $condition = 'created_ts >= "' . $curDate->sub(new DateInterval('P1W'))->format('Y-m-d') . '"';
     } elseif ($filterValue === 'month') {
         $condition = 'created_ts >= "' . $curDate->sub(new DateInterval('P1M'))->format('Y-m-d') . '"';
     } else {
         return;
     }
     $criteria->mergeWith(array('condition' => $condition));
 }
Ejemplo n.º 7
0
 /**
  * @param array $audit
  *
  * @depends testGetAudits
  */
 public function testGetAuditsWithDateFilters($audit)
 {
     $loggedAt = new \DateTime('now', new \DateTimeZone('UTC'));
     $loggedAt->setTimestamp(strtotime($audit['loggedAt']));
     $loggedGTEFilter = '?loggedAt>=' . $loggedAt->format(\DateTime::ISO8601);
     $loggedGTFilter = '?loggedAt>' . $loggedAt->sub(new \DateInterval('PT1H'))->format(\DateTime::ISO8601);
     $loggedLTFilter = '?loggedAt<' . $loggedAt->sub(new \DateInterval('P1D'))->format(\DateTime::ISO8601);
     $this->client->request('GET', $this->getUrl('oro_api_get_audits') . $loggedGTEFilter);
     $this->assertCount(1, $this->getJsonResponseContent($this->client->getResponse(), 200));
     $this->client->request('GET', $this->getUrl('oro_api_get_audits') . $loggedGTFilter);
     $this->assertCount(1, $this->getJsonResponseContent($this->client->getResponse(), 200));
     $this->client->request('GET', $this->getUrl('oro_api_get_audits') . $loggedLTFilter);
     $this->assertEmpty($this->getJsonResponseContent($this->client->getResponse(), 200));
 }
 /**
  * @Given /^following run for "([^"]+)":$/
  */
 public function followingRunFor($name, TableNode $table)
 {
     $app = $this->getApplication();
     $project = $app['project_list']->get($name);
     $methods = array('created_at' => function (RunUnit $unit, $val) {
         $int = new \DateInterval($val);
         $now = new \DateTime();
         $unit->setCreatedAt($now->sub($int));
     }, 'started_at' => function (RunUnit $unit, $val) {
         $int = new \DateInterval($val);
         $now = new \DateTime();
         $unit->setStartedAt($now->sub($int));
     }, 'finished_at' => function (RunUnit $unit, $val) {
         $int = new \DateInterval($val);
         $now = new \DateTime();
         if (!$unit->getStartedAt()) {
             $unit->setStartedAt($now->sub($int));
         }
         $unit->setFinishedAt($now->sub($int));
     }, 'feature' => function (RunUnit $unit, $val) {
         $unit->setFeature($val);
     }, 'return_code' => function (RunUnit $unit, $val) {
         $unit->setReturnCode($val);
     });
     $headers = $table->getRow(0);
     foreach ($headers as $col) {
         if (!isset($methods[$col])) {
             throw new \RuntimeException(sprintf('No handler for column "%s".', $col));
         }
     }
     $run = new Run();
     $run->setProjectName($name);
     $units = $run->getUnits();
     foreach ($table->getRows() as $i => $row) {
         if ($i == 0) {
             continue;
         }
         $unit = new RunUnit();
         foreach ($headers as $i => $header) {
             $value = $row[$i];
             if ($value === '@null') {
                 continue;
             }
             $methods[$header]($unit, $row[$i]);
         }
         $units->add($unit);
     }
     $app['run_storage']->saveRun($run);
 }
 public function getEndDate(int $months, string $dateFormat = 'Y-m-d') : string
 {
     $date = new DateTime($this->format('Y-m-d'));
     $date->add(new DateInterval("P" . $months . "M"));
     $date->sub(new DateInterval("P1D"));
     return $date->format($dateFormat);
 }
Ejemplo n.º 10
0
 /**
  * Subtract given interval from current date time
  *
  * @param string $intervalString
  *
  * @return \DateTime
  */
 protected function prepareDateInterval($intervalString = null)
 {
     $date = new \DateTime('now', new \DateTimeZone('UTC'));
     $intervalString = $intervalString ?: $this->getContainer()->getParameter('oro_batch.cleanup_interval');
     $date->sub(\DateInterval::createFromDateString($intervalString));
     return $date;
 }
Ejemplo n.º 11
0
 public function save()
 {
     $data = $this->getData();
     unset($data['name']);
     if ($id = $this->getData('id')) {
         $data['id'] = $id;
     }
     if ($new = \Arr::get($data, 'since_new', null)) {
         if ($id) {
             $_date = new \DateTime($new);
             $_date->sub(new \DateInterval('P1D'));
             $close = ['id' => $id];
             $close['till'] = $_date->format('Y-m-d');
             $this->model('ManagerTimeSheet')->upsert($close);
             $id = 0;
             $data['since'] = $new;
             unset($data['id']);
         }
     }
     unset($data['since_new']);
     unset($data['till']);
     if (empty($data['id'])) {
         if (isset($data['id'])) {
             unset($data['id']);
         }
     }
     $_id = $this->model('ManagerTimeSheet')->upsert($data);
     $id = $id ? $id : $_id;
     return $this->model('ManagerTimeSheet')->getById($id);
 }
Ejemplo n.º 12
0
 /**
  * Checks if there are not too many login attempts using specified username in the specified number of seconds until now.
  * @param  string  $username
  * @param  integer $count_limit number of login attempts
  * @param  integer $time_limit  number of seconds
  * @return boolean
  */
 public static function hasTooManyFailedAttempts($username, $count_limit = 5, $time_limit = 1800)
 {
     $since = new DateTime();
     $since->sub(new DateInterval("PT{$time_limit}S"));
     $subquery = Yii::$app->db->createCommand()->select('is_successful')->from(self::tableName())->where('username = :username AND performed_on > :since')->order('performed_on DESC')->limit($count_limit)->getText();
     return $count_limit <= (int) Yii::$app->db->createCommand()->select('COUNT(NOT is_successful OR NULL)')->from("({$subquery}) AS t")->queryScalar([':username' => $username, ':since' => $since->format('Y-m-d H:i:s')]);
 }
Ejemplo n.º 13
0
 public function getOldPending()
 {
     $date = new \DateTime();
     $i = new \DateInterval('PT30M');
     $date->sub($i);
     return $this->createQueryBuilder('b')->where('b.created_at < :time')->andWhere('b.status = :status')->setParameter('time', $date)->setParameter('status', \Club\BookingBundle\Entity\Booking::PENDING)->getQuery()->getResult();
 }
Ejemplo n.º 14
0
 public function get_graph_url($name, $num_days = 40)
 {
     global $g_db;
     $select = $g_db->select()->from('stats', array('date', 'value'))->where('name = ?', $name)->order(array('date DESC'))->limit($num_days + 5);
     $values = array();
     $rows = $g_db->fetchAll($select);
     foreach ($rows as $row) {
         $values[$row['date']] = $row['value'];
     }
     $dates = array();
     $labels = array();
     $date = new DateTime();
     $one_day = new DateInterval("P1D");
     for ($i = 0; $i < $num_days; $i++) {
         $dates[] = $date->format('Y-m-d');
         if ($i % 5 == 0) {
             $labels[] = $date->format('d/m');
         }
         $date->sub($one_day);
     }
     $labels = array_reverse($labels);
     $max_value = max(array_values($values));
     $max_value += floor(0.1 * $max_value);
     $data = "";
     for ($i = 0; $i < $num_days; $i++) {
         $value = $values[$dates[$num_days - $i - 1]];
         $data .= is_null($value) ? "_" : self::encode_number_e($value, $max_value);
     }
     return "http://chart.apis.google.com/chart" . "?chxl=1:|" . implode("|", $labels) . "&chxr=0,0,{$max_value}" . "&chxt=y,x" . "&chs=460x150" . "&cht=lc" . "&chco=3D7930" . "&chd=e:{$data}" . "&chg=7.15,-1,1,0" . "&chm=B,C5D4B5BB,0,0,0";
 }
Ejemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     $userManager = $this->container->get('oro_user.manager');
     $admin = $userManager->findUserByEmail(LoadAdminUserData::DEFAULT_ADMIN_EMAIL);
     $organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();
     foreach ($this->orderData as $data) {
         $entity = new Order();
         $entity->setOwner($admin);
         $entity->setOrganization($organization);
         $created = new \DateTime('now', new \DateTimeZone('UTC'));
         $entity->setCreatedAt($created->sub(new \DateInterval($data['createdSub'])));
         $updated = new \DateTime('now', new \DateTimeZone('UTC'));
         $entity->setUpdatedAt($updated->sub(new \DateInterval($data['updatedSub'])));
         $data['channel'] = $this->getReference('integration');
         $data['dataChannel'] = $this->getReference('default_channel');
         $data['cart'] = $this->getReference('cart');
         $data['store'] = $this->getReference('store');
         $data['customer'] = $this->getReference('customer');
         $this->setEntityPropertyValues($entity, $data, ['reference', 'createdSub', 'updatedSub']);
         $this->setReference($data['reference'], $entity);
         $manager->persist($entity);
     }
     $manager->remove($this->getReference('order'));
     $manager->flush();
 }
Ejemplo n.º 16
0
 /**
  * Get a date after which user counts as active
  * @return \DateTime
  */
 protected function getActiveDate()
 {
     $lastActive = new \DateTime();
     $interval = new \DateInterval(sprintf("P%dM", UserType::ACTIVITY_SPAN));
     $lastActive->sub($interval);
     return $lastActive;
 }
Ejemplo n.º 17
0
 public function actionClearDeleted()
 {
     $time = new \DateTime();
     $days = Yii::$app->getModule('core')->daysToStoreSubmissions;
     $time->sub(new \DateInterval("P{$days}D"));
     Submission::deleteAll('UNIX_TIMESTAMP(`date_received`) < ' . $time->getTimestamp() . ' AND `is_deleted` = \'1\'');
 }
Ejemplo n.º 18
0
function createDigest(&$analytics)
{
    try {
        // Step 2. Get the user's first view (profile) ID.
        $profileId = '7631145';
        if (isset($profileId)) {
            $yesterday = new DateTime();
            $yesterday->sub(new DateInterval('P1D'));
            $yesterday_pageviews = pageviewsForDates($analytics, $profileId, $yesterday->format('Y-m-d'), $yesterday->format('Y-m-d'));
            $yesterday->sub(new DateInterval('P1D'));
            $lastweek = new DateTime();
            $lastweek->sub(new DateInterval('P8D'));
            $lastweek_pageviews = pageviewsForDates($analytics, $profileId, $lastweek->format('Y-m-d'), $lastweek->format('Y-m-d'));
            $message = "DAILY DIGEST: Yesterday (" . $yesterday->format('l') . "), we did <https://www.google.com/analytics/web/?hl=en#report/visitors-overview/" . GOOGLE_ANALYTICS_WEB_ID . "/%3F_u.date00%3D" . $yesterday->format('Ymd') . "%26_u.date01%3D" . $yesterday->format('Ymd') . "%26overview-graphOptions.selected%3Danalytics.nthHour/|" . floor($yesterday_pageviews / 1000) . "k pageviews>. Last " . $lastweek->format('l') . ", we did <https://www.google.com/analytics/web/?hl=en#report/visitors-overview/" . GOOGLE_ANALYTICS_WEB_ID . "/%3F_u.date00%3D" . $lastweek->format('Ymd') . "%26_u.date01%3D" . $lastweek->format('Ymd') . "%26overview-graphOptions.selected%3Danalytics.nthHour/|" . floor($lastweek_pageviews / 1000) . "k pageviews> (" . ($yesterday_pageviews - $lastweek_pageviews > 1000 ? "+" : "") . floor(($yesterday_pageviews - $lastweek_pageviews) / 1000) . "k).";
            // Step 4. Output the results.
            slackMessage($message, "#general");
            slackMessage($message, "#analytics");
        }
    } catch (apiServiceException $e) {
        // Error from the API.
        print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
    } catch (Exception $e) {
        print 'There wan a general error : ' . $e->getMessage();
    }
}
Ejemplo n.º 19
0
 /**
  * Displays a form to create a new Offering entity.
  *
  */
 public function newAction(Request $request, $id)
 {
     $entity = new Offering();
     // Defaults
     $entity->setStatus(Offering::START_DATES_KNOWN);
     $startDate = new \DateTime();
     $startDate->sub(new \DateInterval('P60D'));
     $entity->setStartDate($startDate);
     $endDate = new \DateTime();
     $endDate->sub(new \DateInterval('P30D'));
     $entity->setEndDate($endDate);
     $em = $this->getDoctrine()->getManager();
     // Cloning the entity
     if ($id) {
         $type = $request->query->get('type');
         if ($type == 'selfpaced') {
             // Get the course
             $course = $em->getRepository('ClassCentralSiteBundle:Course')->find($id);
             $entity->setStatus(Offering::COURSE_OPEN);
             $entity->setCourse($course);
         } else {
             $entity = $em->getRepository('ClassCentralSiteBundle:Offering')->find($id);
             $entity->setShortName(null);
             $entity->setUrl(null);
         }
     }
     $form = $this->createForm(new OfferingType(), $entity);
     return $this->render('ClassCentralSiteBundle:Offering:new.html.twig', array('entity' => $entity, 'form' => $form->createView()));
 }
Ejemplo n.º 20
0
 public function getDraw(\DateTime $date, $next_or_last, $frequency)
 {
     $day_of_month = (int) $date->format('d');
     $hour = $date->format("H:i:s");
     $leap_year = $date->format('L');
     $month = $date->format("m");
     if (!empty($next_or_last)) {
         if ($next_or_last == 'Next' && ($day_of_month < (int) $this->configParams || $day_of_month == (int) $this->configParams && $hour < $this->getDrawTime()) || $next_or_last == 'Last' && ($day_of_month > (int) $this->configParams || $day_of_month == (int) $this->configParams && $hour > $this->getDrawTime())) {
             if ($month != 2 || ($month == 2 && $this->configParams <= 28 || $this->configParams == 29 && $leap_year)) {
                 $date = new \DateTime($date->format("Y-m-{$this->configParams} {$this->getDrawTime()}"));
             } else {
                 if ($next_or_last == 'Next') {
                     $date = new \DateTime($date->format("Y-03-{$this->configParams} {$this->getDrawTime()}"));
                 } else {
                     $date = new \DateTime($date->format("Y-01-{$this->configParams} {$this->getDrawTime()}"));
                 }
             }
         } else {
             if ($next_or_last == 'Next') {
                 $next_month = $date->add(new \DateInterval('P1M'));
                 $date = new \DateTime($next_month->format("Y-m-{$this->configParams} {$this->getDrawTime()}"));
             } else {
                 if ($month != 3 || ($month == 3 && $this->configParams <= 28 || $this->configParams == 29 && $leap_year)) {
                     $previous_month = $date->sub(new \DateInterval('P1M'));
                     $date = new \DateTime($previous_month->format("Y-m-{$this->configParams} {$this->getDrawTime()}"));
                 } else {
                     $date = new \DateTime($date->format("Y-01-{$this->configParams} {$this->getDrawTime()}"));
                 }
             }
         }
     }
     return $date;
 }
Ejemplo n.º 21
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Sending pending notification and response emails to enabled users');
     $this->notificationService->setOutput($output->isVerbose() ? $output : NULL);
     $this->notificationService->setDryRun($input->getOption('dry-run'));
     $em = $this->doctrine->getManager();
     /**@var NotificationRepository $notificationRepository*/
     $notificationRepository = $em->getRepository('AppBundle:Notification');
     //Send all pending notification
     $notifications = $notificationRepository->findBy(['status' => 'pending', 'emailed' => NULL]);
     if (!empty($notifications)) {
         $output->writeln('Sending new notifications');
         $this->sendEmails($notifications, $output);
     }
     //Send all reminders
     $date = new \DateTime();
     $date->sub(new \DateInterval($this->notificationPendingTimeout));
     $notifications = $notificationRepository->findReminders($date);
     if (!empty($notifications)) {
         $output->writeln('Sending reminders');
         $this->sendEmails($notifications, $output);
     }
     //Send all response
     $notifications = $notificationRepository->findResponses();
     if (!empty($notifications)) {
         $output->writeln('Sending responses');
         $this->sendEmails($notifications, $output);
     }
 }
 private function getLastDayDate()
 {
     $oNow = new DateTime();
     $oNow->sub(new DateInterval('P1D'));
     $sStartDate = $oNow->format('Y-m-d H:i:s');
     return $sStartDate;
 }
Ejemplo n.º 23
0
 /**
  * List user meals..
  *
  * @return Response
  */
 public function getList()
 {
     $dateTime = new \DateTime();
     $lastWeekDate = $dateTime->sub(new \DateInterval('P3D'));
     $meals = Meal::where('user_id', Auth::user()->id)->where('datetime', '>=', $lastWeekDate)->orderBy('datetime', 'DESC')->get();
     return view('meal/list', ['meals' => $meals]);
 }
Ejemplo n.º 24
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $fileInfo = new \SplFileInfo($this->getContainer()->getParameter('kernel.root_dir') . '/../web/sitemap.xml');
     if ($fileInfo->isFile() && $fileInfo->isReadable()) {
         $output->write('Reading sitemap.xml...');
         $file = $fileInfo->openFile();
         $xml = '';
         while (!$file->eof()) {
             $xml .= $file->fgets();
         }
         $output->writeln(' done.');
         $output->write('Updating sitemap.xml...');
         $sitemap = new \SimpleXMLIterator($xml);
         $sitemap->rewind();
         $lastmodDate = new \DateTime();
         $lastmodDate->sub(new \DateInterval('P1D'));
         $lastmodDateFormatted = $lastmodDate->format('Y-m-d');
         while ($sitemap->valid()) {
             $sitemap->current()->lastmod = $lastmodDateFormatted;
             $sitemap->next();
         }
         $file = $file->openFile('w');
         $file->fwrite($sitemap->asXML());
         $output->writeln(' done.');
     } else {
         $output->writeln('Error: Cannot open file web/sitemap.xml');
     }
 }
Ejemplo n.º 25
0
 public function gc($maxAgeInSeconds)
 {
     $dt = new \DateTime();
     $dt->sub(new \DateInterval("PT{$maxAgeInSeconds}S"));
     $age = $dt->format(Model::DATETIME_FORMAT);
     $this->connection->query("DELETE FROM {$this->config[self::CONFIG_TABLE]} WHERE {$this->config[self::CONFIG_TIMESTAMP_FIELD]} < :age", array(":age" => $age), false);
 }
Ejemplo n.º 26
0
 public function testThisDayModify()
 {
     $expression = new ExpressionResult(new Token(Token::TYPE_VARIABLE, DateModifierInterface::VAR_THIS_DAY));
     $result = $expression->getValue();
     $this->assertInstanceOf('\\DateTime', $result);
     $dateTime = new \DateTime('now', new \DateTimeZone('UTC'));
     $expectedResult = $dateTime->format('d');
     $this->assertSame((int) $expectedResult, (int) $result->day);
     $dateTime->add(new \DateInterval('P3D'));
     $expectedResult = $dateTime->format('d');
     $expression->add(new ExpressionResult(3));
     $this->assertSame((int) $expectedResult, (int) $result->day);
     $dateTime->sub(new \DateInterval('P8D'));
     $expectedResult = $dateTime->format('d');
     $expression->subtract(new ExpressionResult(8));
     $this->assertSame((int) $expectedResult, (int) $result->day);
     $expression = new ExpressionResult(new Token(Token::TYPE_VARIABLE, DateModifierInterface::VAR_TODAY));
     $result = $expression->getValue();
     $this->assertInstanceOf('\\DateTime', $result);
     $dateTime = new \DateTime('now', new \DateTimeZone('UTC'));
     $expectedResult = $dateTime->format('d');
     $this->assertSame((int) $expectedResult, (int) $result->day);
     $this->assertEquals(0, (int) $result->hour);
     $this->assertEquals(0, (int) $result->minute);
 }
Ejemplo n.º 27
0
 public function listAction()
 {
     $repository = $this->getDoctrine()->getRepository('ProdekoIlmoBundle:Event');
     $now = new \DateTime();
     //Listaa tapahtumat, joiden ilmo on tulevaisuudessa
     $query = $repository->createQueryBuilder('e')->where('e.registrationStarts > :now')->setParameter('now', $now)->orderBy('e.registrationStarts', 'ASC')->getQuery();
     $upcomingEvents = $query->getResult();
     //Listaa tapahtumat, joiden ilmo on käynnissä
     $query = $repository->createQueryBuilder('e')->where('e.registrationStarts < :now')->andWhere('e.registrationEnds > :now')->setParameter('now', $now)->orderBy('e.takesPlace', 'ASC')->getQuery();
     $activeEvents = $query->getResult();
     //Listaa tapahtumia, joiden ilmo on jo sulkeutunut
     $pastEventTreshold = new \DateTime();
     $pastEventTreshold->sub(new \DateInterval('P2W'));
     //TODO: make configurable
     $query = $repository->createQueryBuilder('e')->where('e.registrationEnds < :now')->orderBy('e.takesPlace', 'DESC');
     $isAdmin = $this->get('security.context')->isGranted('ROLE_ADMIN');
     if (!$isAdmin) {
         $query = $query->andWhere('e.takesPlace > :treshold')->setParameters(array('treshold' => $pastEventTreshold, 'now' => $now));
     } else {
         $query = $query->setParameter('now', $now);
     }
     $query = $query->getQuery();
     $pastEvents = $query->getResult();
     //Hae tapahtumat, joissa on kiltisilmo paraikaa meneillään
     $kiltisNow = new \DateTime();
     $kiltisNow->add(new \DateInterval('PT3H'));
     $query = $repository->createQueryBuilder('e')->where('e.kiltisilmo = true')->andWhere('e.registrationStarts < :kiltisNow')->andWhere('e.registrationStarts > :now')->setParameters(array('now' => $now, 'kiltisNow' => $kiltisNow))->getQuery();
     $kiltisEvents = $query->getResult();
     return $this->render('ProdekoIlmoBundle:Ilmo:eventlist.html.twig', array('activeEvents' => $activeEvents, 'upcomingEvents' => $upcomingEvents, 'pastEvents' => $pastEvents, 'kiltisEvents' => $kiltisEvents));
 }
Ejemplo n.º 28
0
 /**
  * Prepares data structure of labels and values needed for datetime line graph.
  * fromDate variable can be used for SQL query as a limit.
  *
  * @param integer $amount        of units
  * @param string  $unit          php.net/manual/en/dateinterval.construct.php#refsect1-dateinterval.construct-parameters
  * @param array   $datasetLabels
  *
  * @return array
  */
 public static function prepareDatetimeLineGraphData($amount = 30, $unit = 'D', $datasetLabels = array('Dataset 1'))
 {
     $isTime = '';
     if ($unit == 'H') {
         $isTime = 'T';
     }
     $format = self::getDateLabelFormat($unit);
     $date = new \DateTime();
     $oneUnit = new \DateInterval('P' . $isTime . '1' . $unit);
     $data = array('labels' => array(), 'datasets' => array());
     $j = 0;
     // Prefill $data arrays
     foreach ($datasetLabels as $key => $label) {
         if (!isset(self::$colors[$j])) {
             $j = 0;
         }
         $data['datasets'][$key] = array('label' => $label, 'fillColor' => self::$colors[$j]['fill'], 'highlightFill' => self::$colors[$j]['highlight'], 'strokeColor' => self::$colors[$j]['fillStroke'], 'pointColor' => self::$colors[$j]['color'], 'pointStrokeColor' => '#fff', 'pointHighlightFill' => '#fff', 'pointHighlightStroke' => self::$colors[$j]['highlightStroke'], 'data' => array());
         $j++;
         for ($i = 0; $i < $amount; $i++) {
             if ($key === 0) {
                 $data['labels'][$i] = $date->format($format);
                 $date->sub($oneUnit);
             }
             $data['datasets'][$key]['data'][$i] = 0;
         }
     }
     $data['fromDate'] = $date;
     $data['labels'] = array_reverse($data['labels']);
     return $data;
 }
Ejemplo n.º 29
0
 public function index(Request $request, Application $app)
 {
     $now = new \DateTime();
     $lastMonth = new \DateTime();
     $lastMonth->sub(new \DateInterval("P1M"));
     return $this->render(["startdate" => $lastMonth->format("Y-m-d"), "enddate" => $now->format("Y-m-d"), "temperatureData" => $this->storageInterface->recentTemperature(new \DateInterval("P1D"))]);
 }
Ejemplo n.º 30
0
 public function getData()
 {
     $inStartDate = $this->getVal('startDate', date('Y-m-d'));
     $inEndDate = $this->getVal('endDate', date('Y-m-d'));
     $inParam = $this->getVal('param', '');
     $aAllOptions = array_merge($this->aAvailableLanguages, $this->aAvailableOtherOptions);
     $inParam = in_array($inParam, $aAllOptions) ? $inParam : '';
     $startDate = DateTime::createFromFormat('Y-m-d', $inStartDate);
     $endDate = DateTime::createFromFormat('Y-m-d', $inEndDate);
     unset($inStartDate, $inEndDate);
     if (!$startDate || !$endDate) {
         $endDate = new DateTime(date('Y-m-d'));
         $endDate->sub(new DateInterval('P1D'));
         $startDate = clone $endDate;
         $startDate->sub(new DateInterval('P1M'));
     }
     $oOutput = F::build('SpecialNewWikisGraphOutput');
     $oOutput->set($this->getReport($startDate, $endDate, $inParam));
     $mOut = $oOutput->getRaw();
     $this->setVal('chartId', $mOut->chartId);
     $this->setVal('datasets', $mOut->datasets);
     $this->setVal('fullTicks', $mOut->fullTicks);
     $this->setVal('hiddenSeries', $mOut->hiddenSeries);
     $this->setVal('monthly', $mOut->monthly);
     $this->setVal('ticks', $mOut->ticks);
 }