DateTimeImmutable example



    public static function exceptionData(): \Generator
    {
        yield 'consume 4 and expect 3' => [4, 3];
        yield 'consume 2, then consoume 2 and expect 1' => [2, 1, 2];
        yield 'consume 3, then consume 2 and expect 1' => [2, 1, 3];
    }

    private function intervalToSeconds(string $interval): int
    {
        return TimeUtil::dateIntervalToSeconds((new \DateTimeImmutable())->diff(new \DateTimeImmutable('+' . $interval)));
    }
}
EntityExistence $existence,
        KeyValuePair $data,
        WriteParameterBag $parameters
    ): \Generator {
        if (!$field instanceof DateTimeField) {
            throw DataAbstractionLayerException::invalidSerializerField(DateTimeField::class$field);
        }

        $value = $data->getValue();

        if (\is_string($value)) {
            $value = new \DateTimeImmutable($value);
        }

        if (\is_array($value) && \array_key_exists('date', $value)) {
            $value = new \DateTimeImmutable($value['date']);
        }

        $data->setValue($value);
        $this->validateIfNeeded($field$existence$data$parameters);

        if (!$value instanceof \DateTime && !$value instanceof \DateTimeImmutable) {
            yield $field->getStorageName() => null;

            

        if (isset($row[$root . '.mediaId'])) {
            $entity->mediaId = Uuid::fromBytesToHex($row[$root . '.mediaId']);
        }
        if (isset($row[$root . '.position'])) {
            $entity->position = (int) $row[$root . '.position'];
        }
        if (\array_key_exists($root . '.customFields', $row)) {
            $entity->customFields = $definition->decode('customFields', self::value($row$root, 'customFields'));
        }
        if (isset($row[$root . '.createdAt'])) {
            $entity->createdAt = new \DateTimeImmutable($row[$root . '.createdAt']);
        }
        if (isset($row[$root . '.updatedAt'])) {
            $entity->updatedAt = new \DateTimeImmutable($row[$root . '.updatedAt']);
        }
        $entity->product = $this->manyToOne($row$root$definition->getField('product')$context);
        $entity->media = $this->manyToOne($row$root$definition->getField('media')$context);

        $this->translate($definition$entity$row$root$context$definition->getTranslatedFields());
        $this->hydrateFields($definition$entity$root$row$context$definition->getExtensionFields());
        $this->customFields($definition$row$root$entity$definition->getField('customFields')$context);

        
            [new Envelope($apiMessage)],
        ]);

        $bus = $this->createMock(MessageBusInterface::class);

        $dispatcher = new EventDispatcher();
        $dispatcher->addSubscriber(new StopWorkerOnMessageLimitListener(5));

        $clock = new MockClock('2023-03-19 14:00:00+00:00');
        $worker = new Worker([$receiver]$bus$dispatcher, clock: $clock);
        $worker->run(['sleep' => 1000000]);
        $this->assertEquals(new \DateTimeImmutable('2023-03-19 14:00:03+00:00')$clock->now());
    }

    public function testWorkerWithMultipleReceivers()
    {
        // envelopes, in their expected delivery order         $envelope1 = new Envelope(new DummyMessage('message1'));
        $envelope2 = new Envelope(new DummyMessage('message2'));
        $envelope3 = new Envelope(new DummyMessage('message3'));
        $envelope4 = new Envelope(new DummyMessage('message4'));
        $envelope5 = new Envelope(new DummyMessage('message5'));
        $envelope6 = new Envelope(new DummyMessage('message6'));

        

    public function testSubject()
    {
        $e = new Email();
        $e->subject('Subject');
        $this->assertEquals('Subject', $e->getSubject());
    }

    public function testDate()
    {
        $e = new Email();
        $e->date($d = new \DateTimeImmutable());
        $this->assertEquals($d$e->getDate());
    }

    public function testReturnPath()
    {
        $e = new Email();
        $e->returnPath('fabien@symfony.com');
        $this->assertEquals(new Address('fabien@symfony.com')$e->getReturnPath());
    }

    public function testSender()
    {
yield 'operator_gt / not match / day passed / day' => [Rule::OPERATOR_GT, false, 1, $dayTest];
        yield 'operator_gt / match / day passed / day' => [Rule::OPERATOR_GT, true, -1, $dayTest];
        yield 'operator_empty / not match / day passed/ day' => [Rule::OPERATOR_EMPTY, false, 0, $dayTest];
        yield 'operator_empty / match / day passed / day' => [Rule::OPERATOR_EMPTY, true, 0, null];
        yield 'operator_eq / no match / no customer' => [Rule::OPERATOR_EQ, false, 0, $dayTest, true];
        yield 'operator_neq / match / no customer' => [Rule::OPERATOR_NEQ, true, 0, $dayTest, true];
        yield 'operator_empty / match / no customer' => [Rule::OPERATOR_EMPTY, true, 0, $dayTest, true];
    }

    private static function getTestTimestamp(): \DateTimeImmutable
    {
        return new \DateTimeImmutable('2020-03-10T15:00:00+00:00');
    }
}

        if (isset($row[$root . '.width'])) {
            $entity->width = (float) $row[$root . '.width'];
        }
        if (isset($row[$root . '.height'])) {
            $entity->height = (float) $row[$root . '.height'];
        }
        if (isset($row[$root . '.length'])) {
            $entity->length = (float) $row[$root . '.length'];
        }
        if (isset($row[$root . '.releaseDate'])) {
            $entity->releaseDate = new \DateTimeImmutable($row[$root . '.releaseDate']);
        }
        if (isset($row[$root . '.ratingAverage'])) {
            $entity->ratingAverage = (float) $row[$root . '.ratingAverage'];
        }
        if (\array_key_exists($root . '.categoryTree', $row)) {
            $entity->categoryTree = $definition->decode('categoryTree', self::value($row$root, 'categoryTree'));
        }
        if (\array_key_exists($root . '.propertyIds', $row)) {
            $entity->propertyIds = $definition->decode('propertyIds', self::value($row$root, 'propertyIds'));
        }
        if (\array_key_exists($root . '.optionIds', $row)) {
            
date: 2002-12-14T01:23:45.670000Z EOT;

        $this->assertSameData(['date' => 1039829025.67]$this->parser->parse($yaml));
    }

    public function testParseDateAsMappingValue()
    {
        $yaml = <<<'EOT' date: 2002-12-14 EOT;
        $expectedDate = (new \DateTimeImmutable())
            ->setTimeZone(new \DateTimeZone('UTC'))
            ->setDate(2002, 12, 14)
            ->setTime(0, 0, 0);

        $this->assertSameData(['date' => $expectedDate]$this->parser->parse($yaml, Yaml::PARSE_DATETIME));
    }

    /** * @dataProvider parserThrowsExceptionWithCorrectLineNumberProvider */
    public function testParserThrowsExceptionWithCorrectLineNumber($lineNumber$yaml)
    {

        parent::setUp();

        $this->connection = KernelLifecycleManager::getConnection();
        $this->migration = new Migration1669291632MigrateLineItemsInCartRule();

        $this->testRule = [
            'id' => Uuid::randomBytes(),
            'name' => 'testMigrateLineItemsInCartRule',
            'priority' => 1,
            'payload' => 'someValue',
            'created_at' => (new \DateTimeImmutable())->format('Y-m-d H:i:s'),
        ];
        $this->testCondition = [
            'id' => Uuid::randomBytes(),
            'rule_id' => $this->testRule['id'],
            'type' => 'cartLineItemsInCart',
            'value' => '{"operator":"=","identifiers":["001235290242435795391d026fa03b5b"]}',
            'created_at' => (new \DateTimeImmutable())->format('Y-m-d H:i:s'),
        ];
    }

    public function testUpdate(): void
    {
private readonly int $failureCount = 0
    ) {
    }

    public static function openState(): FrwState
    {
        return new FrwState();
    }

    public static function completedState(?\DateTimeImmutable $completedAt = null): FrwState
    {
        return new FrwState($completedAt ?? new \DateTimeImmutable());
    }

    public static function failedState(?\DateTimeImmutable $failedAt = null, int $failureCount = 0): FrwState
    {
        return new FrwState(null, $failedAt ?? new \DateTimeImmutable()$failureCount);
    }

    public function getCompletedAt(): ?\DateTimeImmutable
    {
        return $this->completedAt;
    }

    

    public function testSign(int $time, string $bodyCanon, string $headerCanon, string $header)
    {
        ClockMock::withClockMock($time);

        $message = (new Email())
            ->from(new Address('fabien@testdkim.symfony.net', 'Fabién'))
            ->to('fabien.potencier@gmail.com')
            ->subject('Tést')
            ->text("Some body \n \n This \r\n\r\n is really interesting and at the same time very long line to see if everything works as expected, does it?\r\n\r\n\r\n\r\n")
            ->date(new \DateTimeImmutable('2005-10-15', new \DateTimeZone('Europe/Paris')));

        $signer = new DkimSigner(self::$pk, 'testdkim.symfony.net', 'sf');
        $signedMessage = $signer->sign($message[
            'header_canon' => $headerCanon,
            'body_canon' => $bodyCanon,
            'headers_to_ignore' => ['Message-ID'],
        ]);

        $this->assertSame($message->getBody()->toString()$signedMessage->getBody()->toString());
        $this->assertTrue($signedMessage->getHeaders()->has('DKIM-Signature'));
        $this->assertEquals($header$signedMessage->getHeaders()->get('DKIM-Signature')->getBody());
    }
return $this->collectors[$name];
    }

    private function getTimestamp(?string $value): ?int
    {
        if (null === $value || '' === $value) {
            return null;
        }

        try {
            $value = new \DateTimeImmutable(is_numeric($value) ? '@'.$value : $value);
        } catch (\Exception) {
            return null;
        }

        return $value->getTimestamp();
    }
}

        $cyclesRequired = ceil($tokens / $this->refillAmount);

        return TimeUtil::dateIntervalToSeconds($this->refillTime) * $cyclesRequired;
    }

    /** * Calculates the next moment of token availability. */
    public function calculateNextTokenAvailability(): \DateTimeImmutable
    {
        return (new \DateTimeImmutable())->add($this->refillTime);
    }

    /** * Calculates the number of new free tokens during $duration. * * @param float $duration interval in seconds */
    public function calculateNewTokensDuringInterval(float $duration): int
    {
        $cycles = floor($duration / TimeUtil::dateIntervalToSeconds($this->refillTime));

        

    public function testWithoutApp(array $criteria, string $method, IdsCollection $ids, callable $expectation): void
    {
        $this->ids = $ids;
        $this->createProducts();

        $facade = $this->factory->factory(
            new TestHook('test', Context::createDefaultContext()),
            new Script('test', '', new \DateTimeImmutable())
        );

        $result = $facade->$method('product', $criteria); /* @phpstan-ignore-line */

        $expectation($result);
    }

    /** * @return array<string, array<int, mixed>> */
    public static function withoutAppTestCases(): array
    {
/** @var array<string, mixed> $role */
            foreach ($roles as $role) {
                $currentPrivileges = \json_decode((string) $role['privileges'], true, 512, \JSON_THROW_ON_ERROR);
                $newPrivileges = $this->fixRolePrivileges($privileges$currentPrivileges);

                if ($currentPrivileges === $newPrivileges) {
                    continue;
                }

                $role['privileges'] = \json_encode($newPrivileges, \JSON_THROW_ON_ERROR);
                $role['updated_at'] = (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_FORMAT);

                $connection->update('acl_role', $role['id' => $role['id']]);
            }

            $connection->commit();
        } catch (\Exception $e) {
            $connection->rollBack();

            throw $e;
        }
    }

    
Home | Imprint | This part of the site doesn't use cookies.