DateInterval example



    public function checkHash(string $hash, Context $context): bool
    {
        $criteria = new Criteria();
        $criteria->addFilter(
            new EqualsFilter('hash', $hash)
        );

        $recovery = $this->getUserRecovery($criteria$context);

        $validDateTime = (new \DateTime())->sub(new \DateInterval('PT2H'));

        return $recovery && $validDateTime < $recovery->getCreatedAt();
    }

    public function updatePassword(string $hash, string $password, Context $context): bool
    {
        if (!$this->checkHash($hash$context)) {
            return false;
        }

        $criteria = new Criteria();
        

                'id' => $hashId,
                'customerId' => $customer->getId(),
                'hash' => $hash,
            ],
        ], Context::createDefaultContext());

        if ($expired) {
            $this->getContainer()->get(Connection::class)->update(
                'customer_recovery',
                [
                    'created_at' => (new \DateTime())->sub(new \DateInterval('PT3H'))->format(
                        Defaults::STORAGE_DATE_TIME_FORMAT
                    ),
                ],
                [
                    'id' => Uuid::fromHexToBytes($hashId),
                ]
            );
        }

        return ['customer' => $customer, 'hash' => $hash, 'hashId' => $hashId];
    }
}
public function testGetCustomerRecoveryExpired(): void
    {
        $customerRecoveryRoute = $this->getContainer()->get(CustomerRecoveryIsExpiredRoute::class);

        $token = Uuid::randomHex();

        $context = $this->getContainer()->get(SalesChannelContextFactory::class)->create($token, TestDefaults::SALES_CHANNEL);

        $this->getContainer()->get(Connection::class)->update(
            'customer_recovery',
            [
                'created_at' => (new \DateTime())->sub(new \DateInterval('PT3H'))->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            ],
            [
                'id' => Uuid::fromHexToBytes($this->hashId),
            ]
        );

        $customerRecoveryResponse = $customerRecoveryRoute->load(new RequestDataBag(['hash' => $this->hash])$context);

        static::assertTrue($customerRecoveryResponse->isExpired());
    }
}
$this->validator->validate($data->all()$definition);
    }

    private function dispatchValidationEvent(DataValidationDefinition $definition, DataBag $data, Context $context): void
    {
        $validationEvent = new BuildValidationEvent($definition$data$context);
        $this->eventDispatcher->dispatch($validationEvent$validationEvent->getName());
    }

    private function isExpired(CustomerRecoveryEntity $customerRecovery): bool
    {
        $validDateTime = (new \DateTime())->sub(new \DateInterval('PT2H'));

        return $validDateTime > $customerRecovery->getCreatedAt();
    }
}
$this->definitionInstanceRegistry = $this->createMock(DefinitionInstanceRegistry::class);
        $this->validator = $this->createMock(ValidatorInterface::class);

        $this->dateIntervalFieldSerializer = new DateIntervalFieldSerializer(
            $this->validator,
            $this->definitionInstanceRegistry
        );
    }

    public function testEncodeMethodWithCorrectDataWillReturnDateIntervalString(): void
    {
        $data = new KeyValuePair('key', new \DateInterval('P2Y5D'), false);

        $iterator = $this->dateIntervalFieldSerializer->encode(
            new DateIntervalField('fake', 'fake'),
            $this->createStub(EntityExistence::class),
            $data,
            $this->createMock(WriteParameterBag::class)
        );

        $dateIntervalString = $iterator->current();

        \iterator_to_array($iterator);

        
static::assertEquals($primaryQuery->getField(), 'product.' . $filter['field']);

        static::assertContains($secondaryRangeOperatorarray_keys($result->getQueries()[1]->getParameters()));

        $now = (new \DateTimeImmutable())->setTime(0, 0, 0);

        if ($primaryOperator === 'eq' || $primaryOperator === 'neq') {
            $then = new \DateTimeImmutable();

            static::assertArrayHasKey('value', $filter);

            $dateInterval = new \DateInterval($filter['value']);
            if ($filter['type'] === 'since') {
                $dateInterval->invert = 1;
            }
            $start = $then->add($dateInterval)->setTime(0, 0, 0)->format(Defaults::STORAGE_DATE_TIME_FORMAT);
            $end = $then->add($dateInterval)->setTime(23, 59, 59)->format(Defaults::STORAGE_DATE_TIME_FORMAT);

            static::assertEquals($start$primaryQuery->getParameters()[RangeFilter::GTE]);
            static::assertEquals($end$primaryQuery->getParameters()[RangeFilter::LTE]);

            return;
        }

        
$this->latest->add($interval)
        );
    }

    public function getApiAlias(): string
    {
        return 'cart_delivery_date';
    }

    private static function create(string $interval): \DateTime
    {
        return (new \DateTime())->add(new \DateInterval($interval));
    }
}
public function testGetCacheKey(): void
    {
        static::assertEquals(
            $this->script->getName(),
            $this->scriptLoader->getCacheKey($this->script->getName())
        );
    }

    public function testIsFresh(): void
    {
        $beforeLastModified = $this->script->getLastModified()->sub(new \DateInterval('PT1S'));
        $afterLastModified = $this->script->getLastModified()->add(new \DateInterval('PT1S'));

        static::assertFalse($this->scriptLoader->isFresh($this->script->getName()$beforeLastModified->getTimestamp()));
        static::assertTrue($this->scriptLoader->isFresh($this->script->getName()$afterLastModified->getTimestamp()));

        static::assertFalse($this->scriptLoader->isFresh('doesNotExist', $afterLastModified->getTimestamp()));
    }

    public function testExists(): void
    {
        static::assertTrue($this->scriptLoader->exists($this->script->getName()));
        


    private function checkHash(string $hash, Context $context): bool
    {
        $criteria = new Criteria();
        $criteria->addFilter(
            new EqualsFilter('hash', $hash)
        );

        $recovery = $this->customerRecoveryRepository->search($criteria$context)->first();

        $validDateTime = (new \DateTime())->sub(new \DateInterval('PT2H'));

        return $recovery && $validDateTime < $recovery->getCreatedAt();
    }
}
/** * @param array<string> $mediaIds * * @return array<string> */
    private function filterOutNewMedia(array $mediaIds, int $gracePeriodDays): array
    {
        if ($gracePeriodDays === 0) {
            return $mediaIds;
        }

        $threeDaysAgo = (new \DateTime())->sub(new \DateInterval(sprintf('P%dD', $gracePeriodDays)));
        $rangeFilter = new RangeFilter('uploadedAt', ['lt' => $threeDaysAgo->format(Defaults::STORAGE_DATE_TIME_FORMAT)]);

        $criteria = new Criteria($mediaIds);
        $criteria->addFilter($rangeFilter);

        /** @var array<string> $ids */
        $ids = $this->mediaRepo->searchIds($criteria, Context::createDefaultContext())->getIds();

        return $ids;
    }

    
public function testIsNotNewCustomer(): void
    {
        Feature::skipTestIfActive('v6.6.0.0', $this);

        $rule = new IsNewCustomerRule();

        $cart = new Cart('test');

        $customer = new CustomerEntity();
        $customer->setFirstLogin(
            (new \DateTime())->sub(
                new \DateInterval('P' . 10 . 'D')
            )
        );

        $context = $this->createMock(SalesChannelContext::class);

        $context
            ->method('getCustomer')
            ->willReturn($customer);

        static::assertFalse(
            $rule->match(new CartRuleScope($cart$context))
        );
$data = $qb->executeQuery()->fetchAllAssociative();

        if (empty($data)) {
            return [];
        }

        $customerContext = $salesChannelId && $customerId ? $this->getCustomerContext($data$salesChannelId$customerId) : null;

        $context = $customerContext ?? array_shift($data);

        $updatedAt = new \DateTimeImmutable($context['updated_at']);
        $expiredTime = $updatedAt->add(new \DateInterval($this->lifetimeInterval));

        $payload = array_filter(json_decode((string) $context['payload'], true, 512, \JSON_THROW_ON_ERROR));
        $now = new \DateTimeImmutable();
        if ($expiredTime < $now) {
            // context is expired             $payload = ['expired' => true];
        } else {
            $payload['expired'] = false;
        }

        $payload['token'] = $context['token'];

        
'validateRequest', KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_PRIORITY_AUTH_VALIDATE],
            ],
        ];
    }

    public function setupOAuth(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $accessTokenInterval = new \DateInterval($this->accessTokenTtl);
        $refreshTokenInterval = new \DateInterval($this->refreshTokenTtl);

        $passwordGrant = new PasswordGrant($this->userRepository, $this->refreshTokenRepository);
        $passwordGrant->setRefreshTokenTTL($refreshTokenInterval);

        $refreshTokenGrant = new RefreshTokenGrant($this->refreshTokenRepository);
        $refreshTokenGrant->setRefreshTokenTTL($refreshTokenInterval);

        $this->authorizationServer->enableGrantType($passwordGrant$accessTokenInterval);
        $this->authorizationServer->enableGrantType($refreshTokenGrant$accessTokenInterval);
        $this->authorizationServer->enableGrantType(new ClientCredentialsGrant()$accessTokenInterval);
    }
static::assertSame($expectedResult$this->userRecoveryService->checkHash($hash$this->context));
    }

    /** * @return array<array<int, \DateInterval|string|bool>> */
    public static function dataProviderTestCheckHash(): array
    {
        return [
            [
                new \DateInterval('PT0H'),
                Random::getAlphanumericString(32),
                true,
            ],
            [
                new \DateInterval('PT3H'),
                Random::getAlphanumericString(32),
                false,
            ],
            [
                new \DateInterval('PT1H'),
                Random::getAlphanumericString(32),
                
foreach ($positions as $position) {
            $date = $position->getDeliveryDate();

            // detect the latest delivery date             $earliest = $max->getEarliest() > $date->getEarliest() ? $max->getEarliest() : $date->getEarliest();

            $latest = $max->getLatest() > $date->getLatest() ? $max->getLatest() : $date->getLatest();

            // if earliest and latest is same date, add one day buffer             if ($earliest->format('Y-m-d') === $latest->format('Y-m-d')) {
                $latest = $latest->add(new \DateInterval('P1D'));
            }

            $max = new DeliveryDate($earliest$latest);
        }

        return $max;
    }

    private function buildPositions(
        LineItemCollection $items,
        DeliveryPositionCollection $positions,
        ?
Home | Imprint | This part of the site doesn't use cookies.