/** * @return Template */ public function createTemplate(UI\Control $control = NULL) { $latte = $this->latteFactory->create(); $template = new Template($latte); $presenter = $control ? $control->getPresenter(FALSE) : NULL; if ($control instanceof UI\Presenter) { $latte->setLoader(new Loader($control)); } if ($latte->onCompile instanceof \Traversable) { $latte->onCompile = iterator_to_array($latte->onCompile); } array_unshift($latte->onCompile, function ($latte) use($control, $template) { $latte->getCompiler()->addMacro('cache', new Nette\Bridges\CacheLatte\CacheMacro($latte->getCompiler())); UIMacros::install($latte->getCompiler()); if (class_exists(Nette\Bridges\FormsLatte\FormMacros::class)) { Nette\Bridges\FormsLatte\FormMacros::install($latte->getCompiler()); } if ($control) { $control->templatePrepareFilters($template); } }); $latte->addFilter('url', 'rawurlencode'); // back compatiblity foreach (['normalize', 'toAscii', 'webalize', 'padLeft', 'padRight', 'reverse'] as $name) { $latte->addFilter($name, 'Nette\\Utils\\Strings::' . $name); } $latte->addFilter('null', function () { }); $latte->addFilter('modifyDate', function ($time, $delta, $unit = NULL) { return $time == NULL ? NULL : Nette\Utils\DateTime::from($time)->modify($delta . $unit); // intentionally == }); if (!isset($latte->getFilters()['translate'])) { $latte->addFilter('translate', function (Latte\Runtime\FilterInfo $fi) { throw new Nette\InvalidStateException('Translator has not been set. Set translator using $template->setTranslator().'); }); } // default parameters $template->user = $this->user; $template->baseUri = $template->baseUrl = $this->httpRequest ? rtrim($this->httpRequest->getUrl()->getBaseUrl(), '/') : NULL; $template->basePath = preg_replace('#https?://[^/]+#A', '', $template->baseUrl); $template->flashes = []; if ($control) { $template->control = $control; $template->presenter = $presenter; $latte->addProvider('uiControl', $control); $latte->addProvider('uiPresenter', $presenter); $latte->addProvider('snippetBridge', new Nette\Bridges\ApplicationLatte\SnippetBridge($control)); } $latte->addProvider('cacheStorage', $this->cacheStorage); // back compatibility $template->_control = $control; $template->_presenter = $presenter; $template->netteCacheStorage = $this->cacheStorage; if ($presenter instanceof UI\Presenter && $presenter->hasFlashSession()) { $id = $control->getParameterId('flash'); $template->flashes = (array) $presenter->getFlashSession()->{$id}; } return $template; }
public function formSucceeded(Form $form) { try { $p = $this->getPresenter(); $values = $form->getValues(); $latest = $this->wikiDraftRepository->getLatestByWiki($this->item); $start = DateTime::from($values->startTime); if ($latest && $start < $latest->createdAt) { throw new Exceptions\WikiDraftConflictException($this->translator->translate('locale.error.newer_draft_created_meanwhile')); } unset($values->name); unset($values->startTime); $this->wikiDraftRepository->create($values, $this->user, $this->item, new Entities\WikiDraftEntity()); $ent = $this->item; $p->flashMessage($this->translator->translate('locale.item.updated')); } catch (Exceptions\WikiDraftConflictException $e) { $this->newerDraftExists = true; $this->addFormError($form, $e); } catch (Exceptions\MissingTagException $e) { $this->addFormError($form, $e); } catch (PossibleUniqueKeyDuplicationException $e) { $this->addFormError($form, $e); } catch (\Exception $e) { $this->addFormError($form, $e, $this->translator->translate('locale.error.occurred')); } if (!empty($ent)) { $p->redirect('this'); } }
/** * @return Nette\Utils\DateTime|NULL */ public function getValue() { if ($this->value instanceof DateTime) { // clone return Nette\Utils\DateTime::from($this->value); } elseif (is_int($this->value)) { // timestamp return Nette\Utils\DateTime::from($this->value); } elseif (empty($this->value)) { return NULL; } elseif (is_string($this->value)) { $parsers = $this->parsers; $parsers[] = $this->getDefaultParser(); foreach ($parsers as $parser) { $value = $parser($this->value); if ($value instanceof DateTime) { return $value; } } try { // DateTime constructor throws Exception when invalid input given return Nette\Utils\DateTime::from($this->value); } catch (\Exception $e) { return NULL; } } return NULL; }
/** * @return UI\ITemplate */ protected function createTemplate() { /** @var Nette\Bridges\ApplicationLatte\Template $template */ $template = parent::createTemplate(); $latte = $template->getLatte(); $latte->addFilter('texy', function ($input) { $texy = $this->prepareTexy(); $html = new Nette\Utils\Html(); return $html::el()->setHtml($texy->process($input)); }); $latte->addFilter('vlna', function ($string) { $string = preg_replace('<([^a-zA-Z0-9])([ksvzaiou])\\s([a-zA-Z0-9]{1,})>i', "\$1\$2 \$3", $string); // === \xc2\xa0 return $string; }); $latte->addFilter('dateInWords', function ($time) { $time = Nette\Utils\DateTime::from($time); $months = [1 => 'leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec']; return $time->format('j. ') . $months[$time->format('n')] . $time->format(' Y'); }); $latte->addFilter('timeAgoInWords', function ($time) { $time = Nette\Utils\DateTime::from($time); $delta = round((time() - $time->getTimestamp()) / 60); if ($delta == 0) { return 'před okamžikem'; } if ($delta == 1) { return 'před minutou'; } if ($delta < 45) { return "před {$delta} minutami"; } if ($delta < 90) { return 'před hodinou'; } if ($delta < 1440) { return 'před ' . round($delta / 60) . ' hodinami'; } if ($delta < 2880) { return 'včera'; } if ($delta < 43200) { return 'před ' . round($delta / 1440) . ' dny'; } if ($delta < 86400) { return 'před měsícem'; } if ($delta < 525960) { return 'před ' . round($delta / 43200) . ' měsíci'; } if ($delta < 1051920) { return 'před rokem'; } return 'před ' . round($delta / 525960) . ' lety'; }); return $template; }
/** * @param array $data * @return \FlickrDownloadr\Photo\Photo */ public function fromPlainToEntity(array $data, $photoSizeName) { $code = $this->photoSizeHelper->getCode($photoSizeName); $url = $data['url_' . $code]; $width = $data['width_' . $code]; $height = $data['height_' . $code]; $date = \Nette\Utils\DateTime::from($data['datetaken']); return new Photo($data, $url, $width, $height, $date); }
/** * @param SplFileInfo $articleDirectory * @param string $relativePath * @return array */ private function getMeta($articleDirectory, $relativePath) { $filePath = sprintf('%s/%s', $articleDirectory->getRealPath(), self::META_FILE_NAME); $data = Neon::decode(file_get_contents($filePath)); $data['perex'] = $this->parsedown->text($data['perex']); $data['publishedAt'] = $data['publishedAt'] ? DateTime::from($data['publishedAt']) : null; $data['imagePath'] = "{$relativePath}/" . self::IMAGE_NAME; $data['keyIdentifier'] = $this->parseKeyIdentifier($relativePath); return $data; }
/** * @param \Nette\Application\UI\Form $form */ public function processForm(Form $form) { $values = $form->values; $event = $this->event ? $this->event : new Entity\Event($this->securityUser->getIdentity()); $event->name = $values->name; $event->date = DateTime::from($values->date); $event->place = $values->place; $event->note = $values->note; $this->eventFacade->save($event); }
/** * @return void * * Results of this function are periodically deleted * from production database. Update with caution! */ public function deleteOldEmpty() { $this->connection->query(' DELETE FROM [video_views] WHERE [percent] = 0 AND [time] = 0 AND [furthest] = 0 AND [events]::text = "[]" AND [created_at] < ? ', DateTime::from('7 days ago')); }
public function validate() { if ($this->createdAt < DateTime::from('- 3 days')) { throw new TokenExpiredException(); } if ($this->used) { throw new TokenAlreadyUsedException(); } if (!Passwords::verify($this->unsafe, $this->hash)) { throw new TokenNotValidException(); } }
/** * @subscribe * @param User $user */ public function onLogin(User $user) { if ($user->getBadges($this->getKey())->count() !== 0) { // already awarded return; } if ($user->createdAt < DateTime::from('-1 week')) { $this->awardTo($user, function (Badge $badge, User $user) { return new Bridges\UserOldWeek($badge, $user); }); } }
/** * @return Template */ public function createTemplate(UI\Control $control) { $latte = $this->latteFactory->create(); $template = new Template($latte); $presenter = $control->getPresenter(FALSE); if ($control instanceof UI\Presenter) { $latte->setLoader(new Loader($control)); } if ($latte->onCompile instanceof \Traversable) { $latte->onCompile = iterator_to_array($latte->onCompile); } array_unshift($latte->onCompile, function ($latte) use ($control, $template) { $latte->getParser()->shortNoEscape = TRUE; $latte->getCompiler()->addMacro('cache', new Nette\Bridges\CacheLatte\CacheMacro($latte->getCompiler())); UIMacros::install($latte->getCompiler()); if (class_exists('Nette\Bridges\FormsLatte\FormMacros')) { Nette\Bridges\FormsLatte\FormMacros::install($latte->getCompiler()); } $control->templatePrepareFilters($template); }); $latte->addFilter('url', 'rawurlencode'); // back compatiblity foreach (array('normalize', 'toAscii', 'webalize', 'padLeft', 'padRight', 'reverse') as $name) { $latte->addFilter($name, 'Nette\Utils\Strings::' . $name); } $latte->addFilter('null', function () {}); $latte->addFilter('length', function ($var) { return is_string($var) ? Nette\Utils\Strings::length($var) : count($var); }); $latte->addFilter('modifyDate', function ($time, $delta, $unit = NULL) { return $time == NULL ? NULL : Nette\Utils\DateTime::from($time)->modify($delta . $unit); // intentionally == }); // default parameters $template->control = $template->_control = $control; $template->presenter = $template->_presenter = $presenter; $template->user = $this->user; $template->netteHttpResponse = $this->httpResponse; $template->netteCacheStorage = $this->cacheStorage; $template->baseUri = $template->baseUrl = $this->httpRequest ? rtrim($this->httpRequest->getUrl()->getBaseUrl(), '/') : NULL; $template->basePath = preg_replace('#https?://[^/]+#A', '', $template->baseUrl); $template->flashes = array(); if ($presenter instanceof UI\Presenter && $presenter->hasFlashSession()) { $id = $control->getParameterId('flash'); $template->flashes = (array) $presenter->getFlashSession()->$id; } return $template; }
/** * Sets control's value. * * @return Date */ public function setValue($value) { if ($value instanceof \DateTime) { $this->value = $value; } else { if (is_numeric($value) || is_string($value)) { $this->value = Nette\Utils\DateTime::from($value); } else { $this->value = NULL; } } }
public function renderStats() { $totalDownloads = []; // Calculate total downloads if ($stats = $this->addon->github->extra->get('composer-stats')) { foreach ($stats['all']['labels'] as $key => $label) { $totalDownloads[] = ['x' => DateTime::from($label)->format('c'), 'y' => $stats['all']['values'][$key]]; } } $this->template->totalDownloads = json_encode($totalDownloads); $this->template->setFile(__DIR__ . '/templates/stats.latte'); $this->template->render(); }
/** * @param \DateTime * @return BaseDateTime */ public function setValue($value) { try { if ($value instanceof DateTime || $value instanceof \DibiDateTime) { parent::setValue($value->format($this->format)); } elseif ($value != '') { $date = DateTime::from($value); parent::setValue($date->format($this->format)); } } catch (\Exception $e) { return parent::setValue(NULL); } }
public function convertToPHPValue($value, AbstractPlatform $platform) { if ($value === NULL) { return NULL; } elseif ($value instanceof \DateTime) { return NetteDateTime::from($value); } $val = NetteDateTime::createFromFormat($platform->getDateTimeFormatString(), $value); if (!$val) { throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString()); } return NetteDateTime::from($val); }
/** * Special behaviour for json & \Nette\Utils\DateTime properties * @see parent * * @param string $name * @param mixed $value * */ public function &__set($name, $value) { $ref = static::getReflection(); if ($ref->getEntityProperty($name)->getDescription() == 'json') { if (is_array($value)) { $value = \Nette\Utils\Json::encode($value); } } if ($ref->getEntityProperty($name)->getType() == 'Nette\\Utils\\DateTime' && !is_null($value)) { $value = \Nette\Utils\DateTime::from($value); } $value = parent::__set($name, $value); return $value; }
/** * @return Nette\Application\UI\Form */ protected function createComponentConfigForm() { $form = new Nette\Application\UI\Form(); $form->addGroup('Server related'); $form->addText('ServerName', 'Server name')->setRequired(); $form->addSelect('timeZone', 'Time zone', ['Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe (Bucharest)', 'Europe (London)', 'Indian', 'Pacific']); $form->addText('speed', 'Speed')->setDefaultValue(1); $form->addText('troopSpeed', 'Troop speed')->setDefaultValue(1); $form->addText('evasionSpeed', 'Evasion speed')->setDefaultValue(1); $form->addText('traderMultiplier', 'Trader multiplier')->setDefaultValue(1); $form->addText('crannyMultiplier', 'Cranny multiplier')->setDefaultValue(1); $form->addText('storageMultiplier', 'Storage multiplier')->setDefaultValue(1); $form->addText('trapMultiplier', 'Trap multiplier')->setDefaultValue(1); $form->addText('natarMultiplier', 'Natar multiplier')->setDefaultValue(1); $form->addText('worldSize', 'World size (square)')->setDefaultValue(100); $form->addCheckbox('registrationOpen', 'Open registrations')->setDefaultValue(TRUE); $form->addSelect('beginnerProtection', 'Beginner protection', [Nette\Utils\DateTime::HOUR * 2 => '2 Hours', Nette\Utils\DateTime::HOUR * 6 => '6 Hour', Nette\Utils\DateTime::HOUR * 12 => '12 Hour', Nette\Utils\DateTime::DAY * 1 => '1 Day', Nette\Utils\DateTime::DAY * 2 => '2 Days', Nette\Utils\DateTime::DAY * 3 => '3 Days', Nette\Utils\DateTime::DAY * 7 => '7 Days']); $form->addSelect('plusLength', 'Plus length', [Nette\Utils\DateTime::HOUR * 12 => '12 Hour', Nette\Utils\DateTime::DAY * 1 => '1 Day', Nette\Utils\DateTime::DAY * 2 => '2 Days', Nette\Utils\DateTime::DAY * 3 => '3 Days', Nette\Utils\DateTime::DAY * 7 => '7 Days']); $form->addSelect('productionBoostLength', 'Production boost length', [Nette\Utils\DateTime::HOUR * 12 => '12 Hour', Nette\Utils\DateTime::DAY * 1 => '1 Day', Nette\Utils\DateTime::DAY * 2 => '2 Days', Nette\Utils\DateTime::DAY * 3 => '3 Days', Nette\Utils\DateTime::DAY * 7 => '7 Days']); $form->addSelect('natureRegeneration', 'Nature troops regeneration time', [Nette\Utils\DateTime::HOUR * 2 => '2 Hours', Nette\Utils\DateTime::HOUR * 6 => '6 Hour', Nette\Utils\DateTime::HOUR * 12 => '12 Hour', Nette\Utils\DateTime::DAY * 1 => '1 Day']); $form->addSelect('medalInterval', 'Medal interval', [Nette\Utils\DateTime::DAY * 1 => '1 Day', Nette\Utils\DateTime::DAY * 2 => '2 Days', Nette\Utils\DateTime::DAY * 3 => '3 Days', Nette\Utils\DateTime::DAY * 7 => '7 Days']); $form->addText('tourThreshold', 'Tour threshold')->setDefaultValue(20); $form->addCheckbox('greatWorkshop', 'Great workshop'); $form->addCheckbox('worldWonder', 'World wonder'); $form->addCheckbox('showNatarStatistics', 'Show natars in statistics'); $form->addSelect('peaceSystem', 'Peace system', ['None', 'Normal', 'Christmas', 'New year', 'Easter']); $form->addGroup('Admin account'); $form->addText('adminName', 'Admin name'); $form->addText('adminEmail', 'Admin email'); $form->addCheckbox('showAdminStatistics', 'Show admin in statistics'); $form->addGroup('Sql related'); $form->addText('hostname', 'Hostname'); $form->addText('username', 'Username'); $form->addPassword('password', 'Password'); $form->addText('dbName', 'Database name'); $form->addGroup('Other'); $form->addCheckbox('newsBoxOne', 'Newsbox 1'); $form->addCheckbox('newsBoxTwo', 'Newsbox 2'); $form->addCheckbox('newsBoxThree', 'Newsbox 3'); $form->addCheckbox('log', 'Log actions'); $form->addCheckbox('quest', 'Enable quests'); $form->addCheckbox('questExtended', 'Enable extended quests'); $form->addCheckbox('autoActivate', 'Auto activate accounts'); $form->addGroup('Start time'); $form->addText('startDate', 'Start date Year-month-day format')->setDefaultValue(Nette\Utils\DateTime::from('now')->format('Y-m-d')); $form->addText('startTime', 'Start time')->setDefaultValue(Nette\Utils\DateTime::from('now')->format('H:i')); $form->onSuccess[] = [$this, 'processConfig']; $form->addSubmit('Next', 'Next'); return $form; }
public function setInjectedValue($value) { if ($value === NULL) { if (!$this->isNullable) { throw new InvalidArgumentException('DateTime value cannot be a NULL.'); } else { $this->isModified = $this->value !== NULL; $this->value = NULL; } } else { $old = $this->value; $this->value = DateTime::from($value); $this->isModified = $old == $value; // intentionally == } }
/** * @return DateTime|NULL */ public function getValue() { if (!($value = $this->value)) { return NULL; } if ($value instanceof \DateTime || is_int($value)) { return DateTime::from($value); } try { return DateTime::createFromFormat($this->format, $this->value); } catch (\Exception $e) { } if ($time = strtotime($value)) { return DateTime::from($value); } return NULL; }
public function renderDefault() { $status = $this->cache->load('data', function (&$dependencies) { $dependencies[Cache::EXPIRE] = new DateTime('+30 minutes'); $dependencies[Cache::TAGS] = ['status', 'status.page']; $status = []; // Build addons status =========================================== $status['addons']['active']['composer'] = $this->addonRepository->findBy(['state' => Addon::STATE_ACTIVE, 'type' => Addon::TYPE_COMPOSER])->countStored(); $status['addons']['active']['bower'] = $this->addonRepository->findBy(['state' => Addon::STATE_ACTIVE, 'type' => Addon::TYPE_BOWER])->countStored(); $status['addons']['active']['untype'] = $this->addonRepository->findBy(['state' => Addon::STATE_ACTIVE, 'type' => Addon::TYPE_UNTYPE])->countStored(); $status['addons']['active']['unknown'] = $this->addonRepository->findBy(['state' => Addon::STATE_ACTIVE, 'type' => Addon::TYPE_UNKNOWN])->countStored(); $status['addons']['active']['total'] = $this->addonRepository->findBy(['state' => Addon::STATE_ACTIVE])->countStored(); $status['addons']['queued']['composer'] = $this->addonRepository->findBy(['state' => Addon::STATE_QUEUED, 'type' => Addon::TYPE_COMPOSER])->countStored(); $status['addons']['queued']['bower'] = $this->addonRepository->findBy(['state' => Addon::STATE_QUEUED, 'type' => Addon::TYPE_BOWER])->countStored(); $status['addons']['queued']['untype'] = $this->addonRepository->findBy(['state' => Addon::STATE_QUEUED, 'type' => Addon::TYPE_UNTYPE])->countStored(); $status['addons']['queued']['unknown'] = $this->addonRepository->findBy(['state' => Addon::STATE_QUEUED, 'type' => Addon::TYPE_UNKNOWN])->countStored(); $status['addons']['queued']['total'] = $this->addonRepository->findBy(['state' => Addon::STATE_QUEUED])->countStored(); $status['addons']['archived']['composer'] = $this->addonRepository->findBy(['state' => Addon::STATE_ARCHIVED, 'type' => Addon::TYPE_COMPOSER])->countStored(); $status['addons']['archived']['bower'] = $this->addonRepository->findBy(['state' => Addon::STATE_ARCHIVED, 'type' => Addon::TYPE_BOWER])->countStored(); $status['addons']['archived']['untype'] = $this->addonRepository->findBy(['state' => Addon::STATE_ARCHIVED, 'type' => Addon::TYPE_UNTYPE])->countStored(); $status['addons']['archived']['unknown'] = $this->addonRepository->findBy(['state' => Addon::STATE_ARCHIVED, 'type' => Addon::TYPE_UNKNOWN])->countStored(); $status['addons']['archived']['total'] = $this->addonRepository->findBy(['state' => Addon::STATE_ARCHIVED])->countStored(); $status['addons']['total']['composer'] = $this->addonRepository->findBy(['type' => Addon::TYPE_COMPOSER])->countStored(); $status['addons']['total']['bower'] = $this->addonRepository->findBy(['type' => Addon::TYPE_BOWER])->countStored(); $status['addons']['total']['untype'] = $this->addonRepository->findBy(['type' => Addon::TYPE_UNTYPE])->countStored(); $status['addons']['total']['unknown'] = $this->addonRepository->findBy(['type' => Addon::TYPE_UNKNOWN])->countStored(); $status['addons']['total']['total'] = $this->addonRepository->findAll()->countStored(); // Build github status ============================================= if ($response = $this->github->limit()) { $status['github']['core']['limit'] = $response['resources']['core']['limit']; $status['github']['core']['remaining'] = $response['resources']['core']['remaining']; $status['github']['core']['reset'] = DateTime::from($response['resources']['core']['reset']); $status['github']['search']['limit'] = $response['resources']['search']['limit']; $status['github']['search']['remaining'] = $response['resources']['search']['remaining']; $status['github']['search']['reset'] = DateTime::from($response['resources']['search']['reset']); } return $status; }); // Fill template $this->template->status = $status; }
/** * Returns HTTP valid date format. * @param string|int|\DateTimeInterface * @return string */ public static function formatDate($time) { $time = DateTime::from($time); $time->setTimezone(new \DateTimeZone('GMT')); return $time->format('D, d M Y H:i:s \\G\\M\\T'); }
/** * Sends a cookie. * @param string name of the cookie * @param string value * @param string|int|\DateTime expiration time, value 0 means "until the browser is closed" * @param string * @param string * @param bool * @param bool * @return self * @throws Nette\InvalidStateException if HTTP headers have been sent */ public function setCookie($name, $value, $time, $path = NULL, $domain = NULL, $secure = NULL, $httpOnly = NULL) { self::checkHeaders(); setcookie($name, $value, $time ? DateTime::from($time)->format('U') : 0, $path === NULL ? $this->cookiePath : (string) $path, $domain === NULL ? $this->cookieDomain : (string) $domain, $secure === NULL ? $this->cookieSecure : (bool) $secure, $httpOnly === NULL ? $this->cookieHttpOnly : (bool) $httpOnly); $this->removeDuplicateCookies(); return $this; }
/** * Sets the expiration of the section or specific variables. * @param string|int|\DateTime time, value 0 means "until the browser is closed" * @param mixed optional list of variables / single variable to expire * @return self */ public function setExpiration($time, $variables = NULL) { $this->start(); if (empty($time)) { $time = NULL; $whenBrowserIsClosed = TRUE; } else { $time = Nette\Utils\DateTime::from($time)->format('U'); $max = (int) ini_get('session.gc_maxlifetime'); if ($max !== 0 && $time - time() > $max + 3) { // 0 - unlimited in memcache handler, 3 - bulgarian constant trigger_error("The expiration time is greater than the session expiration {$max} seconds", E_USER_NOTICE); } $whenBrowserIsClosed = FALSE; } foreach (is_array($variables) ? $variables : array($variables) as $variable) { $this->meta[$variable]['T'] = $time; $this->meta[$variable]['B'] = $whenBrowserIsClosed; } return $this; }
/** * Enables log out after inactivity. * @param string|int|\DateTimeInterface Number of seconds or timestamp * @param int Log out when the browser is closed | Clear the identity from persistent storage? * @return self */ public function setExpiration($time, $flags = 0) { $section = $this->getSessionSection(TRUE); if ($time) { $time = Nette\Utils\DateTime::from($time)->format('U'); $section->expireTime = $time; $section->expireDelta = $time - time(); } else { unset($section->expireTime, $section->expireDelta); } $section->expireIdentity = (bool) ($flags & self::CLEAR_IDENTITY); $section->expireBrowser = (bool) ($flags & self::BROWSER_CLOSED); $section->browserCheck = TRUE; $section->setExpiration(0, 'browserCheck'); $section->setExpiration($time, 'foo'); // time check return $this; }
/** * Sets DatePicker value. * * @author Jan Tvrdík * @param DateTime|int|string * @return self */ public function setValue($value) { if ($value instanceof DateTime) { } elseif (is_int($value)) { // timestamp } elseif (empty($value)) { $rawValue = $value; $value = NULL; } elseif (is_string($value)) { $rawValue = $value; if (preg_match('#^(?P<dd>\\d{1,2})[. -] *(?P<mm>\\d{1,2})([. -] *(?P<yyyy>\\d{4})?)?$#', $value, $matches)) { $dd = $matches['dd']; $mm = $matches['mm']; $yyyy = isset($matches['yyyy']) ? $matches['yyyy'] : date('Y'); if (checkdate($mm, $dd, $yyyy)) { $value = "{$yyyy}-{$mm}-{$dd}"; } else { $value = NULL; } } } else { throw new \InvalidArgumentException(); } if ($value !== NULL) { // DateTime constructor throws Exception when invalid input given try { $value = DateTime::from($value); // clone DateTime when given } catch (\Exception $e) { $value = NULL; } } if (!isset($rawValue) && isset($value)) { $rawValue = $value->format(self::W3C_DATE_FORMAT); } $this->value = $value; $this->rawValue = $rawValue; return $this; }
/** * Date/time modification. * @param string|int|DateTime * @param string|int * @param string * @return Nette\Utils\DateTime */ public static function modifyDate($time, $delta, $unit = NULL) { return $time == NULL ? NULL : Nette\Utils\DateTime::from($time)->modify($delta . $unit); }
/** * Restricts the search by modified time. * @param string "[operator] [date]" example: >1978-01-23 * @param mixed * @return self */ public function date($operator, $date = NULL) { if (func_num_args() === 1) { // in $operator is predicate if (!preg_match('#^(?:([=<>!]=?|<>)\\s*)?(.+)\\z#i', $operator, $matches)) { throw new Nette\InvalidArgumentException('Invalid date predicate format.'); } list(, $operator, $date) = $matches; $operator = $operator ? $operator : '='; } $date = DateTime::from($date)->format('U'); return $this->filter(function (FilesystemIterator $file) use($operator, $date) { return Finder::compare($file->getMTime(), $operator, $date); }); }
/** * @param \DateTime $now * @return bool */ public function isExpired(\DateTime $now = NULL) { return $this->expiresAt <= DateTime::from($now); }
/** * Sets the amount of time allowed between requests before the session will be terminated. * @param string|int|\DateTimeInterface time, value 0 means "until the browser is closed" * @return self */ public function setExpiration($time) { if (empty($time)) { return $this->setOptions(['gc_maxlifetime' => self::DEFAULT_FILE_LIFETIME, 'cookie_lifetime' => 0]); } else { $time = Nette\Utils\DateTime::from($time)->format('U') - time(); return $this->setOptions(['gc_maxlifetime' => $time, 'cookie_lifetime' => $time]); } }
/** * Normalizes result row. * @param array * @return array */ public function normalizeRow($row) { if ($this->types === NULL) { $this->types = (array) $this->supplementalDriver->getColumnTypes($this->pdoStatement); } foreach ($this->types as $key => $type) { $value = $row[$key]; if ($value === NULL || $value === FALSE || $type === IStructure::FIELD_TEXT) { } elseif ($type === IStructure::FIELD_INTEGER) { $row[$key] = is_float($tmp = $value * 1) ? $value : $tmp; } elseif ($type === IStructure::FIELD_FLOAT) { if (($pos = strpos($value, '.')) !== FALSE) { $value = rtrim(rtrim($pos === 0 ? "0{$value}" : $value, '0'), '.'); } $float = (double) $value; $row[$key] = (string) $float === $value ? $float : $value; } elseif ($type === IStructure::FIELD_BOOL) { $row[$key] = (bool) $value && $value !== 'f' && $value !== 'F'; } elseif ($type === IStructure::FIELD_DATETIME || $type === IStructure::FIELD_DATE || $type === IStructure::FIELD_TIME) { $row[$key] = new Nette\Utils\DateTime($value); } elseif ($type === IStructure::FIELD_TIME_INTERVAL) { preg_match('#^(-?)(\\d+)\\D(\\d+)\\D(\\d+)\\z#', $value, $m); $row[$key] = new \DateInterval("PT{$m['2']}H{$m['3']}M{$m['4']}S"); $row[$key]->invert = (int) (bool) $m[1]; } elseif ($type === IStructure::FIELD_UNIX_TIMESTAMP) { $row[$key] = Nette\Utils\DateTime::from($value); } } return $this->supplementalDriver->normalizeRow($row); }