/** * {@inheritdoc} */ public function isValidDate($month_day, $month, $year, &$errors = null) { // Create a DateTime object directly. $datetime = \DateTimeImmutable::createFromFormat('n/j/Y', sprintf('%d/%d/%d', $month, $month_day, $year)); $errors = $datetime->getLastErrors(); return empty($errors['warning_count']) && empty($errors['error_count']); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'date') { throw new InvalidArgumentException(); } return new Date(new DateValue(\DateTimeImmutable::createFromFormat(\DateTime::RFC1123, (string) $value))); }
/** * @test */ public function itShouldDeserializeADateTimeImmutable() { $customSerializer = new DateTimeCustomSerializer(); $serialized = [1469787919, new \DateTimeZone('+00:00')]; $object = $customSerializer->deserialize($serialized, \DateTimeImmutable::class); $this->assertEquals($object, \DateTimeImmutable::createFromFormat('U', 1469787919, new \DateTimeZone('+00:00'))); }
/** * @param string $messageName * @param array $messageData * @throws \UnexpectedValueException * @return DomainMessage */ public function createMessageFromArray($messageName, array $messageData) { if (!class_exists($messageName)) { throw new \UnexpectedValueException('Given message name is not a valid class: ' . (string) $messageName); } if (!is_subclass_of($messageName, DomainMessage::class)) { throw new \UnexpectedValueException(sprintf('Message class %s is not a sub class of %s', $messageName, DomainMessage::class)); } if (!isset($messageData['message_name'])) { $messageData['message_name'] = $messageName; } if (!isset($messageData['uuid'])) { $messageData['uuid'] = Uuid::uuid4(); } if (!isset($messageData['version'])) { $messageData['version'] = 0; } if (!isset($messageData['created_at'])) { $time = microtime(true); if (false === strpos($time, '.')) { $time .= '.0000'; } $messageData['created_at'] = \DateTimeImmutable::createFromFormat('U.u', $time); } if (!isset($messageData['metadata'])) { $messageData['metadata'] = []; } return $messageName::fromArray($messageData); }
public function __invoke($value) { if ($value === NULL) { return NULL; } return \DateTimeImmutable::createFromFormat('U.u', sprintf('%.03f', (double) $value / 1000)); }
protected static function _decodeFromDER(Identifier $identifier, $data, &$offset) { $idx = $offset; $length = Length::expectFromDER($data, $idx); $str = substr($data, $idx, $length->length()); $idx += $length->length(); if (!preg_match(self::REGEX, $str, $match)) { throw new DecodeException("Invalid GeneralizedTime format."); } list(, $year, $month, $day, $hour, $minute, $second) = $match; if (isset($match[7])) { $frac = $match[7]; // DER restricts trailing zeroes in fractional seconds component if ($frac[strlen($frac) - 1] === '0') { throw new DecodeException("Fractional seconds must omit trailing zeroes."); } $frac = (int) $frac; } else { $frac = 0; } $time = $year . $month . $day . $hour . $minute . $second . "." . $frac . self::TZ_UTC; $dt = \DateTimeImmutable::createFromFormat("!YmdHis.uT", $time, self::_createTimeZone(self::TZ_UTC)); if (!$dt) { throw new DecodeException("Failed to decode GeneralizedTime: " . self::_getLastDateTimeImmutableErrorsStr()); } $offset = $idx; return new self($dt); }
/** * {@inheritdoc} */ public function fromDatabase($value) { if ($this->immutable) { return \DateTimeImmutable::createFromFormat($this->format, $value); } return \DateTime::createFromFormat($this->format, $value); }
/** * @param RouteCandidateDto $aRouteCandidate * @return Itinerary */ public function toItinerary(RouteCandidateDto $aRouteCandidate) { $legs = array(); foreach ($aRouteCandidate->getLegs() as $legDto) { $legs[] = new Leg($legDto->getLoadLocation(), $legDto->getUnloadLocation(), \DateTimeImmutable::createFromFormat(\DateTime::ATOM, $legDto->getLoadTime()), \DateTimeImmutable::createFromFormat(\DateTime::ATOM, $legDto->getUnloadTime())); } return new Itinerary($legs); }
public function testCreateFromFormatFailure() { $time = 'foo'; $immutable = DateTimeImmutable::createFromFormat(DateTime::RFC3339, $time); $mutable = DateTime::createFromFormat(DateTime::RFC3339, $time); $this->assertFalse($immutable); $this->assertSame(DateTime::getLastErrors(), DateTimeImmutable::getLastErrors()); }
/** * Create a new audi event (timestamp is initialized here). * * @param ProcessEngine $engine * @param boolean $delay Delay creation of timestamp by 1 millisecond? */ public function __construct(ProcessEngine $engine, $delay = false) { if ($delay) { usleep(1000); } $this->engine = $engine; $this->timestamp = \DateTimeImmutable::createFromFormat('U.u', sprintf('%0.3f', microtime(true))); }
/** * Get date as a datetime object. * * @param string $tz Timezone * @throws \RuntimeException * @return \DateTimeImmutable */ public function dateTime($tz = "UTC") { $dt = \DateTimeImmutable::createFromFormat("!U", $this->value(), self::_createTimeZone($tz)); if (false === $dt) { throw new \RuntimeException("Failed to create DateTime: " . self::_getLastDateTimeImmutableErrorsStr()); } return $dt; }
/** * @param $serialized * @return Envelope */ public function unserialize($serialized) { $data = json_decode($serialized, true); $messageData = $data['message']; $messageData['created_at'] = \DateTimeImmutable::createFromFormat('Y-m-d\\TH:i:s.u', $messageData['created_at'], new \DateTimeZone('UTC')); $proophMessage = $this->messageFactory->createMessageFromArray($messageData['message_name'], $messageData); $envelope = new Envelope(BernardMessage::fromProophMessage($proophMessage)); return $envelope; }
public function findByToken($accessTokenId) { $qb = $this->dbalConnection->createQueryBuilder(); $stmt = $qb->select('*')->from($this->tableConfiguration->getAccessTokenTableName())->where($qb->expr()->like('access_token', ':accessToken'))->setMaxResults(1)->setParameter('accessToken', $accessTokenId)->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); if (1 !== count($rows)) { throw new AccessTokenNotFound($accessTokenId); } return new AccessToken($rows[0]['access_token'], \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $rows[0]['expires_at'], new \DateTimeZone('UTC')), $rows[0]['client_id'], $rows[0]['resource_owner_id'] && $rows[0]['resource_owner_type'] ? new ResourceOwner($rows[0]['resource_owner_id'], $rows[0]['resource_owner_type']) : null, explode(',', $rows[0]['scopes'])); }
private function parseDateTime($data, array $type) { $timezone = isset($type['params'][1]) ? new \DateTimeZone($type['params'][1]) : $this->defaultTimezone; $format = $this->getFormat($type); $datetime = \DateTimeImmutable::createFromFormat($format, (string) $data, $timezone); if (false === $datetime) { throw new \RuntimeException(sprintf('Invalid datetime "%s", expected format %s.', $data, $format)); } return $datetime; }
/** * @param string $format * @param string $time * @param \DateTimeZone $timezone * * @return \Staffim\DateTime\DateTime */ public static function createFromFormat($format, $time, $timezone = null) { /** * @see https://bugs.php.net/bug.php?id=69565 */ if ($timezone) { return static::createFromNativeDate(parent::createFromFormat($format, $time, $timezone)); } else { return static::createFromNativeDate(parent::createFromFormat($format, $time)); } }
public function __construct($month_day, $month, $year) { $errors = []; $algorithm = new GregorianAlgorithm(); if (!$algorithm->isValidDate($month_day, $month, $year, $errors)) { throw new InvalidDateException($errors); } // Create a DateTime object directly. $this->datetime = \DateTimeImmutable::createFromFormat('n/j/Y', sprintf('%d/%d/%d', $month, $month_day, $year)); parent::__construct($month_day, $month, $year); }
public function testConvertDateTimeImmutable() { if (!class_exists('DateTimeImmutable')) { $this->markTestSkipped('DateTimeImmutable class does not exist in your PHP version'); } $type = Type::getType(Type::DATE); $timestamp = 100000000.123; $mongoDate = new \MongoDate(100000000, 123000); $dateTimeImmutable = \DateTimeImmutable::createFromFormat('U.u', $timestamp); $this->assertEquals($mongoDate, $type->convertToDatabaseValue($dateTimeImmutable), 'DateTimeImmutable objects are converted to MongoDate objects'); }
public static function fromData($task) { $app = array_key_exists("objectId", $task) ? $task["objectId"] : "n-a"; $status = array_key_exists("status", $task) ? $task["status"] : "n-a"; $startTime = null; if (array_key_exists("startTime", $task)) { $startTime = \DateTimeImmutable::createFromFormat("Y-m-d\\TH:i:s\\Z", $task["startTime"]); } $taskName = array_key_exists("name", $task) ? $task["name"] : ''; return new AsgardTask($app, $taskName, $status, $startTime); }
protected function sanitize($value) { if (empty($value) || !$this->isScalar()) { return null; } if (!is_string($value)) { return new \DateTimeImmutable("@" . intval($value)); } $value = \DateTimeImmutable::createFromFormat(\DateTimeImmutable::DATE_ATOM, $value); return $value ? $value : null; }
/** * @return Message */ public function current() { $current = $this->innerIterator->current(); $metadata = []; foreach ($current as $key => $value) { if (!in_array($key, $this->standardColumns)) { $metadata[$key] = $value; } } $createdAt = \DateTimeImmutable::createFromFormat('Y-m-d\\TH:i:s.u', $current['created_at'], new \DateTimeZone('UTC')); return $this->messageFactory->createMessageFromArray($current['event_name'], ['uuid' => $current['_id'], 'version' => (int) $current['version'], 'created_at' => $createdAt, 'payload' => $current['payload'], 'metadata' => $metadata]); }
/** * @param $value * @return null|\DateTime|\DateTimeInterface */ public function parseDate($value) { if (class_exists('\\DateTimeImmutable')) { $date = \DateTimeImmutable::createFromFormat($this->format, $value, $this->timezone); } else { $date = \DateTime::createFromFormat($this->format, $value, $this->timezone); } if ($date === false) { return null; } return $date; }
/** * Get the aggregate root if it exists otherwise null * * @param AggregateType $aggregateType * @param string $aggregateId * @return Snapshot */ public function get(AggregateType $aggregateType, $aggregateId) { $queryBuilder = $this->connection->createQueryBuilder(); $table = $this->getTable($aggregateType); $queryBuilder->select('*')->from($table, $table)->where('aggregate_type = :aggregate_type')->andWhere('aggregate_id = :aggregate_id')->orderBy('last_version', 'DESC')->setParameter('aggregate_type', $aggregateType->toString())->setParameter('aggregate_id', $aggregateId)->setMaxResults(1); $stmt = $queryBuilder->execute(); $result = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$result) { return; } return new Snapshot($aggregateType, $aggregateId, unserialize($result['aggregate_root']), (int) $result['last_version'], \DateTimeImmutable::createFromFormat('Y-m-d\\TH:i:s.u', $result['created_at'], new \DateTimeZone('UTC'))); }
public static function craftDateTime($seconds, $microseconds = 0) { // Override \Doctrine\ODM\MongoDB\Types\DateType::craftDateTime to return a DateTimeImmutable object // in the 'UTC' timezone instead the current PHP one (date_default_timezone_get()) $datetime = new \DateTimeImmutable(); $datetime->setTimezone(new \DateTimeZone('UTC')); $datetime->setTimestamp($seconds); if ($microseconds > 0) { $datetime = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . $microseconds, new \DateTimeZone('UTC')); } return $datetime; }
/** * @param string $value * @param AbstractPlatform $platform * @return Leg[] */ public function convertToPhpValue($value, AbstractPlatform $platform) { if (null === $value) { return []; } $legsData = json_decode($value, true); $legs = array(); foreach ($legsData as $legData) { $legs[] = new Leg($legData['load_location'], $legData['unload_location'], \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $legData['load_time']), \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $legData['unload_time'])); } return $legs; }
/** * {@inheritdoc} */ public function denormalize($data) { try { $data = \DateTimeImmutable::createFromFormat($this->format, $data); if (!$data instanceof \DateTimeInterface) { throw new \Exception(); } return $data; } catch (\Throwable $e) { throw new DenormalizationException('The value must be a date'); } }
public function loadBookingCalendar() { $selectedDay = new \DateTimeImmutable(); $paramDay = Util\Converter::toString('selectedDay', 'get'); if (isset($paramDay)) { $selectedDay = \DateTimeImmutable::createFromFormat('Y-m-d', $paramDay); } $selectedDay = $selectedDay->setTime(0, 0, 0); $options = []; $options['where'][] = 'status = 1'; $courts = \Own\Bus\Court\Data::loadAll($options); $options = []; $options['where'][] = ['booking_date BETWEEN ? AND ?', $selectedDay->format('Y-m-d 00:00:00'), $selectedDay->format('Y-m-d 23:00:00')]; $options['order'][] = 'booking_date'; $bookings = \Own\Bus\Book\Data::loadAll($options); $options = []; $options['where'][] = ['player1_id = ? OR player2_id = ?', $this->player->getId(), $this->player->getId()]; $options['where'][] = 'booking_date > NOW()'; $futureBookings = Book\Data::count($options); $rule = \Own\Bus\Rule\Data::loadById(1, true); $timeLength = $rule->getTimeLength(); $minTime = 24 * 60; $maxTime = 0; $courtStart = []; foreach ($courts as $court) { $startTime = (int) $court->getStartTime()->format('H') * 60 + (int) $court->getStartTime()->format('i'); $endTime = (int) $court->getEndTime()->format('H') * 60 + (int) $court->getEndTime()->format('i'); $courtStart[] = $startTime % $timeLength; $minTime = min($startTime, $minTime); $maxTime = max($endTime, $maxTime); } $timeDiff = min(array_merge(array_diff($courtStart, [0]), [$timeLength])); // layout $tplCal = new Util\Template(Util\Template::MODULE, ['bus', 'book']); $tplCal->set('isAllowed', Util\Auth::isAuthorized($this->signedUser, 'member', false)); $tplCal->set('isAdmin', $this->signedUser->getIsAdmin()); $tplCal->set('playerId', $this->player->getId()); $tplCal->set('maxBooking', $this->player->getMaxBooking()); $tplCal->set('futureBookings', $futureBookings); $tplCal->set('courts', $courts); $tplCal->set('selectedDay', $selectedDay); $tplCal->set('bookings', $bookings); $tplCal->set('timeLength', $timeLength); $tplCal->set('timeDiff', $timeDiff); $tplCal->set('minTime', $minTime); $tplCal->set('maxTime', $maxTime); $json['html'] = $tplCal->render('booking-calendar'); $json['message'] = 'Booking calendar loaded'; $json['selectedDay'] = $selectedDay->format('Y-m-d'); $json['result'] = \Rebond\Core\ResultType::SUCCESS; return json_encode($json); }
/** * @test */ public function it_converts_from_and_to_array() { $time = (string) microtime(true); if (false === strpos($time, '.')) { $time .= '.0000'; } $now = \DateTimeImmutable::createFromFormat('U.u', $time); $messageData = ['message_name' => 'test-delayed-command', 'uuid' => 'ccefedef-85e1-4fd0-b247-ed13d378b050', 'version' => 1, 'payload' => [], 'metadata' => ['execute_at' => $now->modify('+10 seconds')->format('Y-m-d\\TH:i:s.u')], 'created_at' => $now]; $command = $this->delayedComamnd(); $delayedCommand = $command::fromArray($messageData); $this->assertEquals(10000, $delayedCommand->delay()); $this->assertEquals($messageData, $delayedCommand->toArray()); }
public function convertToPHPValue($value, AbstractPlatform $platform) { if ($value === null || $value instanceof \DateTimeImmutable) { return $value; } elseif ($value instanceof \DateTime) { return \DateTimeImmutable::createFromMutable($value); } $val = \DateTimeImmutable::createFromFormat($platform->getDateTimeFormatString(), $value, self::getUtc()); if (!$val) { throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString()); } return $val; }
public function testReturnsActorUpdated() { $actorUpdated = $this->deserializer->deserialize(new StringLiteral('{ "actorId": "foo", "time": "2015-02-20T20:39:09+0100", "author": "*****@*****.**", "url": "http://foo.bar/event/foo" }')); $this->assertInstanceOf(ActorUpdated::class, $actorUpdated); $this->assertEquals(new StringLiteral('foo'), $actorUpdated->getactorId()); $this->assertEquals(new StringLiteral('*****@*****.**'), $actorUpdated->getAuthor()); $this->assertEquals(\DateTimeImmutable::createFromFormat(DateTime::ISO8601, '2015-02-20T20:39:09+0100'), $actorUpdated->getTime()); $this->assertEquals(Url::fromNative('http://foo.bar/event/foo'), $actorUpdated->getUrl()); }
public static function fromString(string $tokenString) : Token { $rawToken = base64_decode($tokenString, true); if ($rawToken !== false) { $parts = explode(self::DELIMITER, $rawToken); $token = new self(); $token->token = $parts[0]; if (count($parts) == 2) { $token->expiry = \DateTimeImmutable::createFromFormat(self::DATE_FORMAT, $parts[1]); } return $token; } throw (new InvalidTokenString())->withTokenString($tokenString); }