createFromFormat example

<?php
use Symfony\Component\RemoteEvent\Event\Mailer\MailerDeliveryEvent;

$wh = new MailerDeliveryEvent(MailerDeliveryEvent::DROPPED, '<201798300811.5787683@smtp-relay.mailin.fr>', json_decode(file_get_contents(str_replace('.php', '.json', __FILE__)), true, flags: JSON_THROW_ON_ERROR));
$wh->setRecipientEmail('example@gmail.com');
$wh->setTags(['transac_messages']);
$wh->setDate(\DateTimeImmutable::createFromFormat('U', 1604933654));

return $wh;
/** * Returns the HTTP header value converted to a date. * * @throws \RuntimeException When the HTTP header is not parseable */
    public function getDate(string $key, \DateTime $default = null): ?\DateTimeInterface
    {
        if (null === $value = $this->get($key)) {
            return $default;
        }

        if (false === $date = \DateTime::createFromFormat(\DATE_RFC2822, $value)) {
            throw new \RuntimeException(sprintf('The "%s" HTTP header is not parseable (%s).', $key$value));
        }

        return $date;
    }

    /** * Adds a custom Cache-Control directive. * * @return void */
    
/** @var \Drupal\datetime\Plugin\Field\FieldType\DateTimeItem $item */
    if (isset($item)) {
      $value = $item->getValue()['value'];
      if (!is_string($value)) {
        $this->context->addViolation($constraint->badType);
      }
      else {
        $datetime_type = $item->getFieldDefinition()->getSetting('datetime_type');
        $format = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
        $date = NULL;
        try {
          $date = DateTimePlus::createFromFormat($format$valuenew \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
        }
        catch (\InvalidArgumentException $e) {
          $this->context->addViolation($constraint->badFormat, [
            '@value' => $value,
            '@format' => $format,
          ]);
          return;
        }
        catch (\UnexpectedValueException $e) {
          $this->context->addViolation($constraint->badValue, [
            '@value' => $value,
            
<?php
use Symfony\Component\RemoteEvent\Event\Mailer\MailerEngagementEvent;

$wh = new MailerEngagementEvent(MailerEngagementEvent::OPEN, '102175416994919440', json_decode(file_get_contents(str_replace('.php', '.json', __FILE__)), true, flags: JSON_THROW_ON_ERROR));
$wh->setRecipientEmail('event-open@gmail.com');
$wh->setDate(\DateTimeImmutable::createFromFormat('U', 1685519055));
$wh->setTags(['helloworld']);
$wh->setMetadata(['Payload' => '']);

return $wh;

  protected function setExpiresNoCache(Response $response) {
    $response->setExpires(\DateTime::createFromFormat('j-M-Y H:i:s T', '19-Nov-1978 05:00:00 UTC'));
  }

  /** * Registers the methods in this class that should be listeners. * * @return array * An array of event listener definitions. */
  public static function getSubscribedEvents(): array {
    $events[KernelEvents::RESPONSE][] = ['onRespond'];
    // There is no specific reason for choosing 16 beside it should be executed
$this->assertSame('"'.self::A_UUID_V4.'"', json_encode($uuid));
    }

    public function testV1()
    {
        $uuid = Uuid::v1();

        $this->assertInstanceOf(UuidV1::class$uuid);

        $uuid = new UuidV1(self::A_UUID_V1);

        $this->assertEquals(\DateTimeImmutable::createFromFormat('U.u', '1583245966.746458')$uuid->getDateTime());
        $this->assertSame('3499710062d0', $uuid->getNode());
    }

    public function testV3()
    {
        $uuid = Uuid::v3(new UuidV4(self::A_UUID_V4), 'the name');

        $this->assertInstanceOf(UuidV3::class$uuid);
        $this->assertSame('8dac64d3-937a-3e7c-aa1d-d5d6c06a61f5', (string) $uuid);
    }

    
$this->avg = $total / $i;
        }

        $this->mem = \memory_get_usage();
        $this->mem_real = \memory_get_usage(true);
        $this->mem_peak = \memory_get_peak_usage();
        $this->mem_peak_real = \memory_get_peak_usage(true);
    }

    public function getDateTime(): ?DateTime
    {
        return DateTime::createFromFormat('U u', $this->seconds.' '.\str_pad((string) $this->microseconds, 6, '0', STR_PAD_LEFT)) ?: null;
    }
}
DateTimeNormalizer::FORMAT_KEY => $expectedFormat,
                ]
            )
        );
    }

    public static function normalizeUsingTimeZonePassedInContextAndExpectedFormatWithMicrosecondsProvider()
    {
        yield [
            '2018-12-01T18:03:06.067634',
            'Y-m-d\TH:i:s.u',
            \DateTime::createFromFormat(
                'Y-m-d\TH:i:s.u',
                '2018-12-01T18:03:06.067634',
                new \DateTimeZone('UTC')
            ),
            null,
        ];

        yield [
            '2018-12-01T18:03:06.067634',
            'Y-m-d\TH:i:s.u',
            \DateTime::createFromFormat(
                

    #[ReturnTypeWillChange]     public static function createFromFormat($format$datetime$timezone = null)
    {
        if ($date = parent::createFromFormat($format$datetime)) {
            throw I18nException::forInvalidFormat($format);
        }

        return new self($date->format('Y-m-d H:i:s')$timezone);
    }

    /** * Returns a new instance with the datetime set based on the provided UNIX timestamp. * * @param DateTimeZone|string|null $timezone * * @return self * * @throws Exception */
$window = $this->storage->fetch($this->id);
            if (!$window instanceof Window) {
                $window = new Window($this->id, $this->interval, $this->limit);
            }

            $now = microtime(true);
            $availableTokens = $window->getAvailableTokens($now);

            if ($availableTokens >= max(1, $tokens)) {
                $window->add($tokens$now);

                $reservation = new Reservation($nownew RateLimit($window->getAvailableTokens($now), \DateTimeImmutable::createFromFormat('U', floor($now)), true, $this->limit));
            } else {
                $waitDuration = $window->calculateTimeForTokens(max(1, $tokens)$now);

                if (null !== $maxTime && $waitDuration > $maxTime) {
                    // process needs to wait longer than set interval                     throw new MaxWaitDurationExceededException(sprintf('The rate limiter wait time ("%d" seconds) is longer than the provided maximum time ("%d" seconds).', $waitDuration$maxTime)new RateLimit($window->getAvailableTokens($now), \DateTimeImmutable::createFromFormat('U', floor($now + $waitDuration)), false, $this->limit));
                }

                $window->add($tokens$now);

                $reservation = new Reservation($now + $waitDurationnew RateLimit($window->getAvailableTokens($now), \DateTimeImmutable::createFromFormat('U', floor($now + $waitDuration)), false, $this->limit));
            }
<?php
use Symfony\Component\RemoteEvent\Event\Mailer\MailerDeliveryEvent;

$wh = new MailerDeliveryEvent(MailerDeliveryEvent::DELIVERED, '<202305311328.81899448177@smtp-relay.mailin.fr>', json_decode(file_get_contents(str_replace('.php', '.json', __FILE__)), true, flags: JSON_THROW_ON_ERROR));
$wh->setRecipientEmail('example@gmail.com');
$wh->setTags(['tag1', 'tag2']);
$wh->setDate(\DateTimeImmutable::createFromFormat('U', 1685539713));

return $wh;
if (null === $value || '' === $value) {
            return;
        }

        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;

        \DateTime::createFromFormat($constraint->format, $value);

        $errors = \DateTime::getLastErrors() ?: ['error_count' => 0, 'warnings' => []];

        if (0 < $errors['error_count']) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(DateTime::INVALID_FORMAT_ERROR)
                ->addViolation();

            return;
        }

        
$this->value = $value ?? '';
            $this->rawValue = rawurlencode($this->value);
        }
        $this->name = $name;
        $this->path = empty($path) ? '/' : $path;
        $this->domain = $domain;
        $this->secure = $secure;
        $this->httponly = $httponly;
        $this->samesite = $samesite;

        if (null !== $expires) {
            $timestampAsDateTime = \DateTimeImmutable::createFromFormat('U', $expires);
            if (false === $timestampAsDateTime) {
                throw new UnexpectedValueException(sprintf('The cookie expiration time "%s" is not valid.', $expires));
            }

            $this->expires = $timestampAsDateTime->format('U');
        }
    }

    /** * Returns the HTTP representation of the Cookie. */
    
$limiter->consume();
            sleep(5);
        }

        $rateLimit = $limiter->consume();
        $this->assertSame(10, $rateLimit->getLimit());
        $this->assertTrue($rateLimit->isAccepted());
        $rateLimit = $limiter->consume();
        $this->assertFalse($rateLimit->isAccepted());
        $this->assertSame(10, $rateLimit->getLimit());
        // Window ends after 1 minute         $retryAfter = \DateTimeImmutable::createFromFormat('U', $now + 60);
        $this->assertEquals($retryAfter$rateLimit->getRetryAfter());
    }

    /** * @dataProvider provideConsumeOutsideInterval */
    public function testConsumeOutsideInterval(string $dateIntervalString)
    {
        $limiter = $this->createLimiter($dateIntervalString);

        // start window...
 else {
            $name = match ($payload['event']) {
                'click' => MailerEngagementEvent::CLICK,
                'open' => MailerEngagementEvent::OPEN,
                'spam' => MailerEngagementEvent::SPAM,
                'unsub' => MailerEngagementEvent::UNSUBSCRIBE,
                default => throw new ParseException(sprintf('Unsupported event "%s".', $payload['event'])),
            };
            $event = new MailerEngagementEvent($name$payload['MessageID']$payload);
        }

        if (!$date = \DateTimeImmutable::createFromFormat('U', $payload['time'])) {
            throw new ParseException(sprintf('Invalid date "%s".', $payload['time']));
        }

        $event->setDate($date);
        $event->setRecipientEmail($payload['email']);

        if (isset($payload['CustomID'])) {
            $event->setTags([$payload['CustomID']]);
        }

        if (isset($payload['Payload'])) {
            
Home | Imprint | This part of the site doesn't use cookies.