public function hourAction() { //Define your file path based on the cache one $filename = $this->container->getParameter('kernel.cache_dir') . '/timestamps/hour.txt'; $data = @file_get_contents($filename); $now = new \DateTimeImmutable(); $min = (int) $now->format('i'); $timestamp = $now->getTimestamp(); $last = (int) $data ?? 0; $diff = $timestamp - $last; // can only run in the first 5 mins of an hour, // and cannot run again within 10 mins $withinMin = $min <= 5; if ($withinMin && $diff > 10 * 60) { $command = new StatusHourlyCommand(); $command->setContainer($this->container); $input = new ArrayInput([]); $output = new NullOutput(); $resultCode = $command->run($input, $output); //Create your own folder in the cache directory $fs = new Filesystem(); $fs->mkdir(dirname($filename)); file_put_contents($filename, $timestamp); } else { $resultCode = 1; } return new JsonResponse((object) ['status' => $resultCode, 'diff' => $diff, 'inWindow' => $withinMin]); }
/** * Get all the episodes for the current week. */ protected function getEpisodesForWeek(\DateTimeImmutable $start, \DateTimeImmutable $end) { $sorted_results = []; foreach ($this->getAllSeriesEpisodes() as $serie_imdb => $info) { /** @var \Moinax\TvDb\Episode $episode */ foreach (array_reverse($info['episodes']) as $episode) { // If we don't have a timestamp we don't know what to do. if (!$episode->firstAired) { continue; } // Add a day to allow for the US delay. $episode->firstAired->add(new \DateInterval('P1D')); // We're going backwards so if we have a timestamp that is before the // start of our week then we don't have an episode. if ($episode->firstAired->getTimestamp() < $start->getTimestamp()) { break; } // If the episode falls within our week then we're good. $episode_timestamp = $episode->firstAired->getTimestamp(); if ($episode_timestamp > $start->getTimestamp() && $episode_timestamp < $end->getTimestamp()) { $day = $episode->firstAired->format('N'); $sorted_results[$day][] = [$info['serie'], $episode]; } } } ksort($sorted_results); return $sorted_results; }
public function authenticate(array $credentials) { $mcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, ''); $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($mcrypt), MCRYPT_DEV_RANDOM); mcrypt_generic_init($mcrypt, $this->cryptPassword, $iv); $url = $this->getUrl($credentials[self::USERNAME], $credentials[self::PASSWORD], $mcrypt, $iv); try { $res = $this->httpClient->get($url)->send(); } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) { if ($e->getResponse()->getStatusCode() === 403) { throw new \Nette\Security\AuthenticationException("User '{$credentials[self::USERNAME]}' not found.", self::INVALID_CREDENTIAL); } elseif ($e->getResponse()->getStatusCode() === 404) { throw new \Nette\Security\AuthenticationException("Invalid password.", self::IDENTITY_NOT_FOUND); } else { throw $e; } } $responseBody = trim(mdecrypt_generic($mcrypt, $res->getBody(TRUE))); $apiData = Json::decode($responseBody); $user = $this->db->table('users')->where('id = ?', $apiData->id)->fetch(); $registered = new \DateTimeImmutable($apiData->registered->date, new \DateTimeZone($apiData->registered->timezone)); $userData = array('username' => $credentials[self::USERNAME], 'password' => $this->calculateAddonsPortalPasswordHash($credentials[self::PASSWORD]), 'email' => $apiData->email, 'realname' => $apiData->realname, 'url' => $apiData->url, 'signature' => $apiData->signature, 'language' => $apiData->language, 'num_posts' => $apiData->num_posts, 'apiToken' => $apiData->apiToken, 'registered' => $registered->getTimestamp()); if (!$user) { $userData['id'] = $apiData->id; $userData['group_id'] = 4; $this->db->table('users')->insert($userData); $user = $this->db->table('users')->where('username = ?', $credentials[self::USERNAME])->fetch(); } else { $user->update($userData); } return $this->createIdentity($user); }
/** * Return the given ratio of the given interval. * @param \DateInterval $interval * @param number $ratio 0 to 1 * @return string */ public static function ratioIntervalString(\DateInterval $interval, $ratio) { $reference = new \DateTimeImmutable(); $endTime = $reference->add($interval); $seconds = $endTime->getTimestamp() - $reference->getTimestamp(); $seconds = $seconds * $ratio; return sprintf("PT%dS", $seconds); }
/** * Initialize instance from date/time string. * * @param string $time <code>strtotime</code> compatible time string * @param string $tz Default timezone * @throws \RuntimeException * @return static */ public static function fromString($time, $tz = "UTC") { try { $dt = new \DateTimeImmutable($time, self::_createTimeZone($tz)); return new static($dt->getTimestamp()); } catch (\Exception $e) { throw new \RuntimeException("Failed to create DateTime: " . self::_getLastDateTimeImmutableErrorsStr(), 0, $e); } }
/** * @test */ public function it_publishes_messages() { $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); $producer = $this->prophesize(Producer::class); $producer->publish(['message_name' => 'test-message', 'uuid' => 'ccefedef-85e1-4fd0-b247-ed13d378b050', 'version' => 1, 'payload' => [], 'metadata' => [], 'created_at' => $now->format('Y-m-d\\TH:i:s.u')], 'test-message', Constants::AMQP_NOPARAM, ['app_id' => 'test_app', 'timestamp' => $now->getTimestamp(), 'type' => 'test-message'])->shouldBeCalled(); $message = $this->prophesize(Message::class); $message->createdAt()->willReturn($now)->shouldBeCalled(); $message->messageName()->willReturn('test-message')->shouldBeCalled(); $messageConverter = $this->prophesize(MessageConverter::class); $messageConverter->convertToArray($message)->willReturn(['message_name' => 'test-message', 'uuid' => 'ccefedef-85e1-4fd0-b247-ed13d378b050', 'version' => 1, 'payload' => [], 'metadata' => [], 'created_at' => $now])->shouldBeCalled(); $messageProducer = new AmqpMessageProducer($producer->reveal(), $messageConverter->reveal(), 'test_app'); $messageProducer($message->reveal()); }
public function setExpires($expires) { if ($expires === NULL) { $this->expires = NULL; } else { if (is_numeric($expires)) { $expires = new \DateTimeImmutable('@' . $expires); } elseif ($expires instanceof \DateTimeInterface) { $expires = new \DateTimeImmutable('@' . $expires->getTimestamp(), $expires->getTimezone()); } else { $expires = \DateTimeImmutable::createFromFormat(Http::DATE_COOKIE, $expires); } $this->expires = $expires->setTimezone(new \DateTimeZone('UTC')); } }
protected function generateRandomDate($is_future, $day_of_week) { // Generate a random timestamp. if ($is_future) { $time = rand(time() + 86400, getrandmax()); } else { $time = rand(0, time() - 86400); } $date = new \DateTimeImmutable($time); if ($day_of_week) { $days_diff = 7 - $day_of_week; $time = $date->getTimestamp() - $days_diff * 86400; return new \DateTimeImmutable($time); } return $date; }
protected function getFormattedDateTime(Episode $episode) { if (!$episode->firstAired) { return 'N/A'; } $today = new \DateTimeImmutable(); $format = 'red'; // If the episode comes out today, then make it green. if ($episode->firstAired->format('d/m/y') === $today->format('d/m/y')) { $format = 'info'; } elseif ($episode->firstAired->getTimestamp() > $today->getTimestamp()) { // Episode in the future. $format = 'comment'; } $date_time = $episode->firstAired->format('D - d/m/Y'); return $format ? "<{$format}>{$date_time}</{$format}>" : $date_time; }
public function it_can_receive_due_scheduled_commands() { $date = new \DateTimeImmutable(); $timestamp = $date->getTimestamp(); $lua = $this->getLua('receive_due_messages'); $this->adapter->evalLua($lua, ['test', 0, $timestamp, SchedulerWorker::DEFAULT_THROTTLE])->shouldBeCalled()->willReturn([['test', 'test', 'test', $timestamp]]); $commandsWrapper = $this->receiveDueCommands($date); $commands = $commandsWrapper->getWrappedObject(); \PHPUnit_Framework_Assert::assertArrayHasKey(0, $commands); \PHPUnit_Framework_Assert::assertArrayNotHasKey(1, $commands); \PHPUnit_Framework_Assert::assertEquals('test', $commands[0]->getId()); }
public function testAsDatetime() { $value = time(); $this->assertSame(date('M j, Y g:i:s A', $value), $this->formatter->asDatetime($value)); $this->assertSame(date('Y/m/d h:i:s A', $value), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A')); $value = new DateTime(); $this->assertSame(date('M j, Y g:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value)); $this->assertSame(date('Y/m/d h:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A')); if (version_compare(PHP_VERSION, '5.5.0', '>=')) { $value = new \DateTimeImmutable(); $this->assertSame(date('M j, Y g:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value)); $this->assertSame(date('Y/m/d h:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A')); } // empty input $this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime('')); $this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(0)); $this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(false)); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asDatetime(null)); }
/** * Create a TimeValue from a \DateInterval object * * @param \DateInterval $interval * @return TimeValue */ public static function createFromDateInterval(\DateInterval $interval) { $utc = new \DateTimeZone('UTC'); $start = new \DateTimeImmutable(null, $utc); $end = $start->add($interval); return new TimeValue($end->getTimestamp() - $start->getTimestamp(), 's'); }
public function updateProperty(ResourceInterface $resource, XmlName $prop, \DOMElement $value) { if (!$resource instanceof FilesystemResource) { throw new \InvalidArgumentException(sprintf('Expecting a filesystem resource, given %s', get_class($resource))); } if ($prop->getNamespaceUri() == WebDav::NS_DAV) { switch ($prop->getLocalName()) { case 'getlastmodified': $text = trim($value->textContent); $date = new \DateTimeImmutable(is_numeric($text) ? '@' . $text : $text); touch($resource->getFileInfo()->getPathname(), $date->getTimestamp()); return; } } if ($prop->getNamespaceUri() == WebDav::NS_WIN32) { switch ($prop->getLocalName()) { case 'Win32LastModifiedTime': $text = trim($value->textContent); $date = new \DateTimeImmutable(is_numeric($text) ? '@' . $text : $text); touch($resource->getFileInfo()->getPathname(), $date->getTimestamp()); return; } } return parent::updateProperty($resource, $prop, $value); }
/** * Returns the PeriodLib duration as expressed in seconds * * @return float */ public function getTimestampInterval() { $end = $this->endDate->getTimestamp() + (int) $this->endDate->format('u') * 1.0E-6; $start = $this->startDate->getTimestamp() + (int) $this->startDate->format('u') * 1.0E-6; return (double) sprintf('%f', $end - $start); }
public static function canEditEvent(self $event, User $user) { $now = new \DateTimeImmutable(); if ($event->start->getTimestamp() < $now->getTimestamp()) { // Too Old return false; } $isCouncil = $user->rank >= User::RANK_LIEUTENANT; $isLeader = is_null($event->leader) ? false : $event->leader->id == $user->id; return $isCouncil || $isLeader; }
/** * Sets the expiration time this cache item. * * @param \DateTime|\DateTimeImmutable $expiration * The point in time after which the item MUST be considered expired. * If null is passed explicitly, a default value MAY be used. If none is set, * the value should be stored permanently or for as long as the * implementation allows. * * @return static Called object. * * @throws \JoeBengalen\Cache\InvalidArgumentException If $expiration is not of type \DataTime or \DateTimeImmutable */ public function expiresAt($expiration) { if ($expiration instanceof DateTime) { $this->expiration = $expiration; } elseif ($expiration instanceof DateTimeImmutable) { $this->expiration = new DateTime(); $this->expiration->setTimestamp($expiration->getTimestamp()); } else { throw new InvalidArgumentException(printf("Expiration must be of type \\DateTime or \\DateTimeImmutable, %s given.", gettype($expiration))); } return $this; }
/** * @return bool */ public function hasExpired() { return $this->expiry->getTimestamp() < time(); }
<?php require __DIR__ . "/../vendor/autoload.php"; /** * This file is part of the frost package. * * Unless required by applicable law or agreed to in writing, software * distributed under the LICENSE is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use SeerUK\Frost\Feature; use SeerUK\Frost\FeatureDirector; use SeerUK\Frost\Condition\CallableCondition; $feature = new Feature("example.context", new CallableCondition(function (array $context) : bool { $requiredDate = new DateTimeImmutable("2015-01-01"); return $context["created"] > $requiredDate->getTimestamp(); })); $director = new FeatureDirector(); $director->addFeature($feature); $users = [["username" => "A", "created" => 1428842585], ["username" => "B", "created" => 1321639398]]; foreach ($users as $user) { if ($director->isEnabled("example.context", $user)) { echo "Feature 'example.context' is enabled for user '{$user["username"]}'.\n"; } else { echo "Feature 'example.context' is not enabled for user '{$user["username"]}'.\n"; } }