public function testConvertTimestampToDbFormatDateTimeAndBackToTimeStamp() { $time = time(); $timeZone = date_default_timezone_get(); date_default_timezone_set('GMT'); $gmtDbFormatDateTime = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateTimeFormat(), $time); date_default_timezone_set('America/New_York'); $dbFormatDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($time); $timeStamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($dbFormatDateTime); $this->assertEquals($gmtDbFormatDateTime, $dbFormatDateTime); $this->assertEquals($time, $timeStamp); date_default_timezone_set($timeZone); }
/** * Utilized to create or update model attribute values after a workflow's triggers are fired as true. * @param WorkflowActionProcessingModelAdapter $adapter * @param $attribute * @throws NotSupportedException */ public function resolveValueAndSetToModel(WorkflowActionProcessingModelAdapter $adapter, $attribute) { assert('is_string($attribute)'); if ($this->type == static::TYPE_STATIC) { $adapter->getModel()->{$attribute} = $this->value; } elseif ($this->type == self::TYPE_DYNAMIC_FROM_TRIGGERED_DATETIME) { $newTimeStamp = $this->resolveNewTimeStampForDuration(time()); $adapter->getModel()->{$attribute} = DateTimeUtil::convertTimestampToDbFormatDateTime($newTimeStamp); } elseif ($this->type == self::TYPE_DYNAMIC_FROM_EXISTING_DATETIME) { if (!DateTimeUtil::isDateTimeStringNull($adapter->getModel()->{$attribute})) { $existingTimeStamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($adapter->getModel()->{$attribute}); $newTimeStamp = $this->resolveNewTimeStampForDuration($existingTimeStamp); $newDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($newTimeStamp); $adapter->getModel()->{$attribute} = $newDateTime; } } else { throw new NotSupportedException(); } }
public function testCalculateNew() { //Test Today. $todayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TODAY, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()))); $todayDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())); $today = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $todayDateTime->getTimeStamp()); $this->assertEquals($today, $todayDateStamp); //Test Tomorrow. $tomorrowDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TOMORROW, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()))); $tomorrowDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())); $tomorrow = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $tomorrowDateTime->getTimeStamp() + 60 * 60 * 24); $this->assertEquals($tomorrow, $tomorrowDateStamp); //Test Yesterday. $yesterdayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::YESTERDAY, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()))); $yesterdayDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())); $yesterday = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $yesterdayDateTime->getTimeStamp() - 60 * 60 * 24); $this->assertEquals($yesterday, $yesterdayDateStamp); //Test Now. $nowDateTimeStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::NOW, new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser()))); $nowDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())); $this->assertWithinTolerance($nowDateTime->getTimeStamp(), DateTimeUtil::convertDbFormatDateTimeToTimestamp($nowDateTimeStamp), 1); //Now test all calculations using a different time zone. $this->assertNotEquals('Europe/Malta', Yii::app()->timeZoneHelper->getForCurrentUser()); //Test Today. $todayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TODAY, new DateTime(null, new DateTimeZone('Europe/Malta'))); $todayDateTime = new DateTime(null, new DateTimeZone('Europe/Malta')); $today = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $todayDateTime->getTimeStamp()); $this->assertEquals($today, $todayDateStamp); //Test Tomorrow. $tomorrowDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::TOMORROW, new DateTime(null, new DateTimeZone('Europe/Malta'))); $tomorrowDateTime = new DateTime(null, new DateTimeZone('Europe/Malta')); $tomorrow = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $tomorrowDateTime->getTimeStamp() + 60 * 60 * 24); $this->assertEquals($tomorrow, $tomorrowDateStamp); //Test Yesterday. $yesterdayDateStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::YESTERDAY, new DateTime(null, new DateTimeZone('Europe/Malta'))); $yesterdayDateTime = new DateTime(null, new DateTimeZone('Europe/Malta')); $yesterday = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateFormat(), $yesterdayDateTime->getTimeStamp() - 60 * 60 * 24); $this->assertEquals($yesterday, $yesterdayDateStamp); //Test Now. $nowDateTimeStamp = DateTimeCalculatorUtil::calculateNew(DateTimeCalculatorUtil::NOW, new DateTime(null, new DateTimeZone('Europe/Malta'))); $nowDateTime = new DateTime(null, new DateTimeZone('Europe/Malta')); $this->assertWithinTolerance($nowDateTime->getTimeStamp(), DateTimeUtil::convertDbFormatDateTimeToTimestamp($nowDateTimeStamp), 1); }
/** * Validates a date time attribute on a model. Compares either an attribute value is larger or smaller * than another date time attribute. * If there is any error, the error message is added to the model. * @param RedBeanModel $model the model being validated * @param string $attribute the attribute being validated */ protected function validateAttribute($object, $attribute) { assert('$object instanceof RedBeanModel'); assert('$this->type == "after" || $this->type == "before"'); assert('is_string($this->compareAttribute)'); if ($object->{$attribute} != null && $object->{$this->compareAttribute} != null && $object->{$attribute} != '0000-00-00 00:00:00' && $object->{$this->compareAttribute} != '0000-00-00 00:00:00') { $firstDateTime = DateTimeUtil::convertDbFormatDateTimeToTimestamp($object->{$attribute}); $secondDateTime = DateTimeUtil::convertDbFormatDateTimeToTimestamp($object->{$this->compareAttribute}); if ($this->type === 'before') { if ($firstDateTime > $secondDateTime) { $this->addError($object, $attribute, Zurmo::t('Core', 'firstDateTime must occur before secondDateTime'), array('firstDateTime' => $object->getAttributeLabel($attribute), 'secondDateTime' => $object->getAttributeLabel($this->compareAttribute))); } } elseif ($this->type === 'after') { if ($firstDateTime < $secondDateTime) { $this->addError($object, $attribute, Zurmo::t('Core', 'firstDateTime must occur after secondDateTime'), array('firstDateTime' => $object->getAttributeLabel($attribute), 'secondDateTime' => $object->getAttributeLabel($this->compareAttribute))); } } } }
/** * @param CEvent $event */ public function scoreCompletedOnTime(CEvent $event) { $model = $event->sender; assert('$model instanceof Item'); if (!$model->getIsNewModel() && array_key_exists('completed', $model->originalAttributeValues) && $model->completed == true && $model->dueDateTime != null) { $completedTimestamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($model->completedDateTime); $dueTimestamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($model->dueDateTime); if ($completedTimestamp <= $dueTimestamp) { $scoreType = static::SCORE_TYPE_COMPLETED_TASK_ON_TIME; $category = static::SCORE_CATEGORY_TIME_SENSITIVE_ACTION; $gameScore = GameScore::resolveToGetByTypeAndPerson($scoreType, Yii::app()->user->userModel); $gameScore->addValue(); $saved = $gameScore->save(); if (!$saved) { throw new FailedToSaveModelException(); } GamePointUtil::addPointsByPointData(Yii::app()->user->userModel, static::getPointTypeAndValueDataByCategory($category)); } } }
protected function setAndGetDateTimeAttribute($attributeName, $withDefaultData) { $this->assertTrue(isset($attributeName) && $attributeName != ''); $this->assertTrue(isset($withDefaultData) && is_bool($withDefaultData)); $attributeForm = new DateTimeAttributeForm(); $attributeForm->attributeName = $attributeName; $attributeForm->attributeLabels = array('de' => 'Test DateTime 2 de', 'en' => 'Test DateTime 2 en', 'es' => 'Test DateTime 2 es', 'fr' => 'Test DateTime 2 fr', 'it' => 'Test DateTime 2 it'); $attributeForm->isAudited = true; $attributeForm->isRequired = true; if ($withDefaultData) { $attributeForm->defaultValueCalculationType = DateTimeCalculatorUtil::NOW; } else { $attributeForm->defaultValueCalculationType = null; } $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData(); $adapter = new $modelAttributesAdapterClassName(new Account()); try { $adapter->setAttributeMetadataFromForm($attributeForm); } catch (FailedDatabaseSchemaChangeException $e) { echo $e->getMessage(); $this->fail(); } $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName(new Account(), $attributeName . 'Cstm'); $this->assertEquals('DateTime', $attributeForm->getAttributeTypeName()); $this->assertEquals($attributeName . 'Cstm', $attributeForm->attributeName); $compareAttributeLabels = array('de' => 'Test DateTime 2 de', 'en' => 'Test DateTime 2 en', 'es' => 'Test DateTime 2 es', 'fr' => 'Test DateTime 2 fr', 'it' => 'Test DateTime 2 it'); $this->assertEquals($compareAttributeLabels, $attributeForm->attributeLabels); $this->assertEquals(true, $attributeForm->isAudited); $this->assertEquals(true, $attributeForm->isRequired); if ($withDefaultData) { $this->assertEquals(DateTimeCalculatorUtil::NOW, $attributeForm->defaultValueCalculationType); //Confirm default calculation loads correct default value for Account. $account = new Account(); $nowDateTime = new DateTime(null, new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser())); $this->assertWithinTolerance($nowDateTime->getTimeStamp(), DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->{$attributeName . 'Cstm'}), 1); } else { $this->assertEquals(null, $attributeForm->defaultValueCalculationType); //Confirm default calculation loads correct default value (null) for Account. $account = new Account(); $this->assertEquals(null, $account->{$attributeName . 'Cstm'}); } }
/** * Called by ajax action when the calendar month is changed. Needed to render additional events. */ public function renderMonthEvents() { $month = str_pad($_GET['month'], 2, '0', STR_PAD_LEFT); $year = $_GET['year']; $dayEvents = $this->makeDataProvider($year . '-' . $month . '-01')->getData(); foreach ($dayEvents as $event) { $dateTimestamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($event['dbDate']); $dateForJavascript = date('M j, Y', $dateTimestamp); echo "console.log('" . $dateForJavascript . "');calendarEvents[new Date('" . $dateForJavascript . "')] = new CalendarEvent('" . $event['label'] . "', '" . $event['className'] . "'); \n"; } }
/** * For a given model, and dateTime attribute, resolve to add a job by the job type. The delay is calculated * based on the value of the dateTime attribute * @param RedBeanModel $model * @param $attributeName * @param $jobType */ public function resolveToAddJobTypeByModelByDateTimeAttribute(RedBeanModel $model, $attributeName, $jobType) { assert('is_string($attributeName)'); assert('is_string($jobType)'); if ($model->getIsNewModel() || isset($model->originalAttributeValues[$attributeName])) { if (DateTimeUtil::isDateTimeStringNull($model->{$attributeName})) { $secondsFromNow = 0; } else { $processDateTimeStamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($model->{$attributeName}); $secondsFromNow = $processDateTimeStamp - time(); } if ($secondsFromNow <= 0) { $delay = 0; } else { $delay = $secondsFromNow; } Yii::app()->jobQueue->add($jobType, $delay + 5); } }
protected function renderEvents($id) { $script = "var calendarEvents = {}; \n"; if (count($this->dayEvents) > 0) { foreach ($this->dayEvents as $event) { $dateTimestamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($event['dbDate']); $dateForJavascript = date('M j, Y', $dateTimestamp); $script .= "calendarEvents[new Date('" . $dateForJavascript . "')] = new CalendarEvent('" . $event['label'] . "', '" . $event['className'] . "'); \n"; } } $cs = Yii::app()->getClientScript(); $cs->registerScript(__CLASS__ . '#' . $id . 'dayEvents', $script); }
/** * @depends testCreateAndGetCampaignListById */ public function testRequiredAttributes() { $campaign = new Campaign(); $this->assertFalse($campaign->save()); $errors = $campaign->getErrors(); $this->assertNotEmpty($errors); $this->assertCount(7, $errors); $this->assertArrayHasKey('name', $errors); $this->assertEquals('Name cannot be blank.', $errors['name'][0]); $this->assertArrayHasKey('supportsRichText', $errors); $this->assertEquals('Supports HTML cannot be blank.', $errors['supportsRichText'][0]); $this->assertArrayHasKey('subject', $errors); $this->assertEquals('Subject cannot be blank.', $errors['subject'][0]); $this->assertArrayHasKey('fromName', $errors); $this->assertEquals('From Name cannot be blank.', $errors['fromName'][0]); $this->assertArrayHasKey('fromAddress', $errors); $this->assertEquals('From Address cannot be blank.', $errors['fromAddress'][0]); $this->assertArrayHasKey('textContent', $errors); $this->assertEquals("You choose not to support HTML but didn't set any text content.", $errors['textContent'][0]); $this->assertEquals('Please provide at least one of the contents field.', $errors['textContent'][1]); $this->assertArrayHasKey('marketingList', $errors); $this->assertEquals('Marketing List cannot be blank.', $errors['marketingList'][0]); $campaign->name = 'Test Campaign Name2'; $campaign->supportsRichText = 0; $campaign->status = Campaign::STATUS_ACTIVE; $campaign->fromName = 'From Name2'; $campaign->fromAddress = '*****@*****.**'; $campaign->subject = 'Test Subject2'; $campaign->htmlContent = 'Test Html Content2'; $campaign->textContent = 'Test Text Content2'; $campaign->fromName = 'From Name2'; $campaign->fromAddress = '*****@*****.**'; $campaign->marketingList = self::$marketingList; $this->assertTrue($campaign->save()); $id = $campaign->id; unset($campaign); $campaign = Campaign::getById($id); $this->assertEquals('Test Campaign Name2', $campaign->name); $this->assertEquals(0, $campaign->supportsRichText); $this->assertEquals(Campaign::STATUS_ACTIVE, $campaign->status); $this->assertEquals('From Name2', $campaign->fromName); $this->assertEquals('*****@*****.**', $campaign->fromAddress); $this->assertEquals('Test Subject2', $campaign->subject); $this->assertEquals('Test Html Content2', $campaign->htmlContent); $this->assertEquals('Test Text Content2', $campaign->textContent); $this->assertTrue(time() + 15 > DateTimeUtil::convertDbFormatDateTimeToTimestamp($campaign->sendOnDateTime)); }
/** * Given a model of a jobInProcess and the 'type' of job, determine if the job has been running too * long. Jobs have defined maximum run times that they are allowed to be in process. * @param JobInProcess $jobInProcess * @param string $type * @return true/false - true if the job is over the allowed amount of time to run for. */ public static function isJobInProcessOverThreshold(JobInProcess $jobInProcess, $type) { assert('is_string($type) && $type != ""'); $createdTimeStamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($jobInProcess->createdDateTime); $nowTimeStamp = time(); $jobClassName = $type . 'Job'; $thresholdSeconds = $jobClassName::getRunTimeThresholdInSeconds(); if ($nowTimeStamp - $createdTimeStamp > $thresholdSeconds) { return true; } return false; }
public function testCreationAndModificationTimes() { $user = UserTestHelper::createBasicUser('Billy'); $account = new Account(); $createdTime = time(); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->modifiedDateTime), 2); sleep(3); // Sleeps are bad in tests, but I need some time to pass // to test these time stamps. The 3's here just need to be more // than the 2's in the asserts. Using 2 and 1 meant it failed // occasionally because the second would tick over just at the // wrong time. $account->owner = $user; $account->name = 'Test Account'; $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertWithinTolerance(time(), DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->modifiedDateTime), 2); sleep(3); $account->officePhone = '1234567890'; $lastModifiedTime = time(); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertWithinTolerance($lastModifiedTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->modifiedDateTime), 2); $this->assertTrue($account->save()); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertWithinTolerance($lastModifiedTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->modifiedDateTime), 2); $id = $account->id; unset($account); sleep(2); $account = Account::getById($id); $this->assertEquals('Test Account', $account->name); $this->assertEquals('1234567890', $account->officePhone); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertWithinTolerance($lastModifiedTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->modifiedDateTime), 2); unset($account); sleep(3); $account = Account::getById($id); $this->assertEquals('Test Account', $account->name); $this->assertEquals('1234567890', $account->officePhone); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertWithinTolerance($lastModifiedTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->modifiedDateTime), 2); unset($account); sleep(3); $account = Account::getById($id); $contact = ContactTestHelper::createContactByNameForOwner('contactTest', $user); $account->contacts->add($contact); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertTrue($account->save()); $this->assertWithinTolerance($createdTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->createdDateTime), 2); $this->assertNotEquals($lastModifiedTime, DateTimeUtil::convertDbFormatDateTimeToTimestamp($account->modifiedDateTime)); }
/** * @param TimeTriggerForWorkflowForm $trigger * @param RedBeanModel $model * @return int * @throws ValueForProcessDateTimeIsNullException */ protected static function resolveTimeStampForDateTimeAttributeForProcessDateTime(TimeTriggerForWorkflowForm $trigger, RedBeanModel $model) { $dateTime = static::resolveModelValueByTimeTrigger($trigger, $model); if (DateTimeUtil::isDateTimeStringNull($dateTime)) { throw new ValueForProcessDateTimeIsNullException(); } else { return $trigger->resolveNewTimeStampForDuration(DateTimeUtil::convertDbFormatDateTimeToTimestamp($dateTime)); } }
/** * * Given a db formatted date string, return the db formatted dateTime stamp representing the last minute of * the provided date. This will be adjusted for the current user's timezone. * Example: date provided is 1980-06-03, the first minute is '1980-06-03 23:59:59'. If the user is in Chicago * then the time needs to be adjusted 5 or 6 hours forward depending on daylight savings time * @param string $dateValue - db formatted */ public static function convertDateIntoTimeZoneAdjustedDateTimeEndOfDay($dateValue) { assert('is_string($dateValue) && DateTimeUtil::isValidDbFormattedDate($dateValue)'); $lessThanValue = $dateValue . ' 23:59:59'; $adjustedTimeStamp = Yii::app()->timeZoneHelper->convertFromLocalTimeStampForCurrentUser(DateTimeUtil::convertDbFormatDateTimeToTimestamp($lessThanValue)); return DateTimeUtil::convertTimestampToDbFormatDateTime($adjustedTimeStamp); }
/** * Get array of modified items since beginning or since datetime in past * @param $params * @return ApiResult * @throws ApiException */ public function processGetModifiedItems($params) { try { $modelClassName = $this->getModelName(); $stateMetadataAdapterClassName = $this->resolveStateMetadataAdapterClassName(); if (!isset($params['sinceDateTime'])) { $sinceTimestamp = 0; } else { if (DateTimeUtil::isValidDbFormattedDateTime($params['sinceDateTime'])) { $sinceTimestamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($params['sinceDateTime']); } else { $message = 'sinceDateTime format is not correct. sinceDateTime should be in "YYYY-MM-DD HH:MM:SS" format'; throw new ApiException($message); } } $pageSize = Yii::app()->pagination->getGlobalValueByType('apiListPageSize'); if (isset($params['pagination']['pageSize'])) { $pageSize = (int) $params['pagination']['pageSize']; } // Get offset. Please note that API client provide page number, and we need to convert it into offset, // which is parameter of RedBeanModel::getSubset function if (isset($params['pagination']['page']) && (int) $params['pagination']['page'] > 0) { $currentPage = (int) $params['pagination']['page']; } else { $currentPage = 1; } $offset = $this->getOffsetFromCurrentPageAndPageSize($currentPage, $pageSize); $models = ModelStateChangesSubscriptionUtil::getUpdatedModels($modelClassName, $pageSize, $offset, $sinceTimestamp, $stateMetadataAdapterClassName, Yii::app()->user->userModel); $totalItems = ModelStateChangesSubscriptionUtil::getUpdatedModelsCount($modelClassName, $sinceTimestamp, $stateMetadataAdapterClassName, Yii::app()->user->userModel); $data = array('totalCount' => $totalItems, 'pageSize' => $pageSize, 'currentPage' => $currentPage); if (is_array($models) && !empty($models)) { foreach ($models as $model) { $data['items'][] = static::getModelToApiDataUtilData($model); } $result = new ApiResult(ApiResponse::STATUS_SUCCESS, $data, null, null); } else { $result = new ApiResult(ApiResponse::STATUS_SUCCESS, $data, null, null); } } catch (Exception $e) { $message = $e->getMessage(); throw new ApiException($message); } return $result; }