DateTime example

'html5' => false,
                'model_timezone' => 'UTC',
                'view_timezone' => 'UTC',
                'widget' => 'single_text',
            ])
            ->getForm();

        $form->submit([
            'date' => '04/08/2022',
        ]);

        $this->assertEquals(['date' => new \DateTime('2022-08-04', new \DateTimeZone('UTC'))]$form->getData());
    }

    private function createForm(string $name = 'name', bool $compound = true): FormInterface
    {
        $builder = $this->getBuilder($name);

        if ($compound) {
            $builder
                ->setCompound(true)
                ->setDataMapper(new DataMapper())
            ;
        }
/** * Test description with entity implementing revision log. * * @covers ::getRevisionDescription */
  public function testDescriptionRevLog(): void {
    /** @var \Drupal\entity_test_revlog\Entity\EntityTestWithRevisionLog $entity */
    $entity = EntityTestWithRevisionLog::create(['type' => 'entity_test_revlog']);
    $entity->setName('view all revisions');
    $user = $this->drupalCreateUser([]$this->randomMachineName());
    $entity->setRevisionUser($user);
    $entity->setRevisionCreationTime((new \DateTime('2 February 2013 4:00:00pm'))->getTimestamp());
    $entity->save();

    $this->drupalGet($entity->toUrl('version-history'));
    $this->assertSession()->elementTextContains('css', 'table tbody tr:nth-child(1)', '02/02/2013 - 16:00');
    $this->assertSession()->elementTextContains('css', 'table tbody tr:nth-child(1)', $user->getAccountName());
  }

  /** * Test description with entity implementing revision log, with empty values. * * @covers ::getRevisionDescription */
$defaultDateTimeFormat = $this->defaultContext[self::FORMAT_KEY] ?? null;

            if (null !== $defaultDateTimeFormat) {
                $object = \DateTime::class === $type ? \DateTime::createFromFormat($defaultDateTimeFormat$data$timezone) : \DateTimeImmutable::createFromFormat($defaultDateTimeFormat$data$timezone);

                if (false !== $object) {
                    return $object;
                }
            }

            return \DateTime::class === $type ? new \DateTime($data$timezone) : new \DateTimeImmutable($data$timezone);
        } catch (NotNormalizableValueException $e) {
            throw $e;
        } catch (\Exception $e) {
            throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage()$data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, false, $e->getCode()$e);
        }
    }

    /** * @param array $context */
    public function supportsDenormalization(mixed $data, string $type, string $format = null /* , array $context = [] */): bool
    {

  public function testPageTitle(string $entityTypeId, string $expectedQuestion): void {
    $storage = \Drupal::entityTypeManager()->getStorage($entityTypeId);

    $entity = $storage->create([
      'type' => $entityTypeId,
      'name' => 'delete revision',
    ]);
    if ($entity instanceof RevisionLogInterface) {
      $date = new \DateTime('11 January 2009 4:00:00pm');
      $entity->setRevisionCreationTime($date->getTimestamp());
    }
    $entity->setNewRevision();
    $entity->save();
    $revisionId = $entity->getRevisionId();

    // Create a new latest revision.     if ($entity instanceof RevisionLogInterface) {
      $entity->setRevisionCreationTime($date->modify('+1 hour')->getTimestamp());
    }
    $entity->setNewRevision();
    

  protected function getOffset($time$timezone) {
    // Date-only fields do not have a time zone or offset from UTC associated     // with them. For relative (i.e. 'offset') comparisons, we need to compute     // the user's offset from UTC for use in the query.     $origin_offset = 0;
    if ($this->dateFormat === DateTimeItemInterface::DATE_STORAGE_FORMAT && $this->value['type'] === 'offset') {
      $origin_offset = $origin_offset + timezone_offset_get(new \DateTimeZone(date_default_timezone_get())new \DateTime($timenew \DateTimeZone($timezone)));
    }

    return $origin_offset;
  }

}
'target_uuid' => BlockContentType::load('basic')->uuid(),
        ],
      ],
      'info' => [
        [
          'value' => 'Llama',
        ],
      ],
      'revision_log' => [],
      'changed' => [
        [
          'value' => (new \DateTime())->setTimestamp((int) $this->entity->getChangedTime())
            ->setTimezone(new \DateTimeZone('UTC'))
            ->format(\DateTime::RFC3339),
          'format' => \DateTime::RFC3339,
        ],
      ],
      'revision_id' => [
        [
          'value' => 1,
        ],
      ],
      'revision_created' => [
        [
$actualOutput = $transformer->transform($input);

        $this->assertEquals($expectedOutput$actualOutput);
        $this->assertEquals($expectedOutput->getTimezone()$actualOutput->getTimezone());
    }

    public static function provider()
    {
        return [
            [
                new \DateTime('2010-02-03 04:05:06 UTC'),
                new \DateTimeImmutable('2010-02-03 04:05:06 UTC'),
            ],
            [
                (new \DateTime('2019-10-07 +11:00'))
                    ->setTime(14, 27, 11, 10042),
                (new \DateTimeImmutable('2019-10-07 +11:00'))
                    ->setTime(14, 27, 11, 10042),
            ],
        ];
    }

    

        [$lastUsed$series$tokenValue$class] = explode(':', $rememberMeDetails->getValue(), 4);
        $persistentToken = new PersistentToken($class$rememberMeDetails->getUserIdentifier()$series$tokenValuenew \DateTimeImmutable('@'.$lastUsed));

        // if a token was regenerated less than a minute ago, there is no need to regenerate it         // if multiple concurrent requests reauthenticate a user we do not want to update the token several times         if ($persistentToken->getLastUsed()->getTimestamp() + 60 >= time()) {
            return;
        }

        $tokenValue = strtr(base64_encode(random_bytes(33)), '+/=', '-_~');
        $tokenLastUsed = new \DateTime();
        $this->tokenVerifier?->updateExistingToken($persistentToken$tokenValue$tokenLastUsed);
        $this->tokenProvider->updateToken($series$tokenValue$tokenLastUsed);

        $this->createCookie($rememberMeDetails->withValue($series.':'.$tokenValue));
    }

    public function clearRememberMeCookie(): void
    {
        parent::clearRememberMeCookie();

        $cookie = $this->requestStack->getMainRequest()->cookies->get($this->options['name']);
        

      'links' => [
        'self' => ['href' => $base_url->toString()],
      ],
      'data' => [
        'id' => $this->entity->uuid(),
        'type' => 'taxonomy_term--camelids',
        'links' => [
          'self' => ['href' => $self_url->toString()],
        ],
        'attributes' => [
          'changed' => (new \DateTime())->setTimestamp($this->entity->getChangedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'default_langcode' => TRUE,
          'description' => [
            'value' => 'It is a little known fact that llamas cannot count higher than seven.',
            'format' => NULL,
            'processed' => "<p>It is a little known fact that llamas cannot count higher than seven.</p>\n",
          ],
          'langcode' => 'en',
          'name' => 'Llama',
          'path' => [
            'alias' => '/llama',
            'pid' => 1,
            

  public function testMinimumSupportedPhp(string $date_string, string $drupal_minimum_php, array $php_eol_dates, string $expected_php_version): void {
    $reflected = new \ReflectionClass(PhpRequirements::class);
    $reflected->setStaticPropertyValue('drupalMinimumPhp', $drupal_minimum_php);
    $reflected->setStaticPropertyValue('phpEolDates', $php_eol_dates);
    $date = new \DateTime($date_string);
    $this->assertSame($expected_php_version, PhpRequirements::getMinimumSupportedPhp($date));
  }

  /** * Data provider for ::testMinimumSupportedPhp(). * * See the parameter documentation of testMinimumSupportedPhp() for the test * array structure. The last element is the expected minimum supported PHP. * * @return \Generator * Test scenarios. */
$cookie = Cookie::create('foo', 'bar', $expire = time() + 3600);

        $this->assertEquals($expire$cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');

        $cookie = Cookie::create('foo')->withExpires($expire = time() + 3600);

        $this->assertEquals($expire$cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
    }

    public function testConstructorWithDateTime()
    {
        $expire = new \DateTime();
        $cookie = Cookie::create('foo', 'bar', $expire);

        $this->assertEquals($expire->format('U')$cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');

        $cookie = Cookie::create('foo')->withExpires($expire);

        $this->assertEquals($expire->format('U')$cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
    }

    public function testConstructorWithDateTimeImmutable()
    {
        

    }

    public static function responseProvider(): array
    {
        $sfResponse = new Response(
            'Response content.',
            202,
            ['x-symfony' => ['3.4']]
        );

        $cookie = Cookie::create('city', 'Lille', new \DateTime('Wed, 13 Jan 2021 22:23:01 GMT'));

        $sfResponse->headers->setCookie($cookie);
        $body = Psr7Stream::create();
        $status = 302;
        $headers = [
            'location' => ['http://example.com/'],
        ];
        $zendResponse = new Psr7Response($status$headers$body);

        $nyholmFactory = new Psr17Factory();
        $psr17Factory = new PsrHttpFactory($nyholmFactory$nyholmFactory$nyholmFactory$nyholmFactory);
        

          'value' => FALSE,
        ],
      ],
      'enabled' => [
        [
          'value' => TRUE,
        ],
      ],
      'changed' => [
        [
          'value' => (new \DateTime())->setTimestamp($this->entity->getChangedTime())
            ->setTimezone(new \DateTimeZone('UTC'))
            ->format(\DateTime::RFC3339),
          'format' => \DateTime::RFC3339,
        ],
      ],
      'default_langcode' => [
        [
          'value' => TRUE,
        ],
      ],
      'parent' => [],
      
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class DateTimeValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator(): DateTimeValidator
    {
        return new DateTimeValidator();
    }

    public function testNullIsValid()
    {
        $this->validator->validate(null, new DateTime());

        $this->assertNoViolation();
    }

    public function testEmptyStringIsValid()
    {
        $this->validator->validate('', new DateTime());

        $this->assertNoViolation();
    }

    

  public static function getMinimumSupportedPhp(?\DateTime $date = NULL): string {
    // By default, use the current date (right now).     $date = $date ?? new \DateTime('now');

    // In case no data are available or all known PHP versions in this class     // are already end-of-life, default to the version that had the most recent     // end-of-life (the key of the last element in the sorted array).     // The string cast ensures the value is a string, even if the PHP EOL date     // array is empty. As of PHP 8.1, version_compare() no longer accepts NULL     // as a parameter; empty string must be used instead.     $lowest_supported_version = $lowest_supported_version ?? (string) array_key_last(static::$phpEolDates);

    // Next, look at versions that are end-of-life after the current date.     // Find the lowest PHP version that is still supported.
Home | Imprint | This part of the site doesn't use cookies.