DateInterval example

private InMemoryStorage $storage;

    protected function setUp(): void
    {
        $this->storage = new InMemoryStorage();

        ClockMock::register(InMemoryStorage::class);
    }

    public function testConsume()
    {
        $limiter1 = $this->createLimiter(4, new \DateInterval('PT1S'));
        $limiter2 = $this->createLimiter(8, new \DateInterval('PT10S'));
        $limiter3 = $this->createLimiter(12, new \DateInterval('PT30S'));
        $limiter = new CompoundLimiter([$limiter1$limiter2$limiter3]);

        $this->assertEquals(0, $limiter->consume(4)->getRemainingTokens(), 'Limiter 1 reached the limit');
        sleep(1); // reset limiter1's window         $this->assertTrue($limiter->consume(3)->isAccepted());

        $this->assertEquals(0, $limiter->consume()->getRemainingTokens(), 'Limiter 2 has no remaining tokens left');
        sleep(10); // reset limiter2's window         $this->assertTrue($limiter->consume(3)->isAccepted());

        

    public static function getSubscribedEvents(): array
    {
        return [
            'Shopware_Cronjob_MailLogCleanup' => 'mailLogCleanup',
        ];
    }

    public function mailLogCleanup(): void
    {
        $now = new DateTime('now');
        $maximumAgeInterval = new DateInterval(sprintf('P%dD', $this->maximumAgeInDays));

        $this->logRepository->deleteByDate(null, $now->sub($maximumAgeInterval));
    }
}
use PHPUnit\Framework\TestCase;
use Symfony\Component\Notifier\Bridge\Ntfy\NtfyOptions;

/** * @author Mickael Perraud <mikaelkael.fr@gmail.com> */
class NtfyOptionsTest extends TestCase
{
    public function testNtfyOptions()
    {
        $delay = (new \DateTime())->add(new \DateInterval('PT1M'));
        $ntfyOptions = (new NtfyOptions())
            ->setMessage('test message')
            ->setTitle('message title')
            ->setPriority(NtfyOptions::PRIORITY_URGENT)
            ->setTags(['tag1', 'tag2'])
            ->addTag('tag3')
            ->setDelay($delay)
            ->setActions([['action' => 'view', 'label' => 'View', 'url' => 'https://test.com']])
            ->addAction(['action' => 'http', 'label' => 'Open', 'url' => 'https://test2.com'])
            ->setClick('https://test3.com')
            ->setAttachment('https://filesrv.lan/space.jpg')
            
$signPattern = '-?';
                $dateIntervalFormat = substr($dateIntervalFormat, 2);
                break;
        }
        $valuePattern = '/^'.$signPattern.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?:(?P<$1>\d+)$2)?', preg_replace('/(T.*)$/', '($1)?', $dateIntervalFormat)).'$/';
        if (!preg_match($valuePattern$data)) {
            throw new UnexpectedValueException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $data$dateIntervalFormat));
        }

        try {
            if ('-' === $data[0]) {
                $interval = new \DateInterval(substr($data, 1));
                $interval->invert = 1;

                return $interval;
            }

            if ('+' === $data[0]) {
                return new \DateInterval(substr($data, 1));
            }

            return new \DateInterval($data);
        } catch (\Exception $e) {
            
$limiter->consume(9);

        for ($i = 0; $i < 2; ++$i) {
            $rateLimit = $limiter->consume(0);
            $this->assertTrue($rateLimit->isAccepted());
            $this->assertSame(10, $rateLimit->getLimit());
        }
    }

    private function createLimiter(): SlidingWindowLimiter
    {
        return new SlidingWindowLimiter('test', 10, new \DateInterval('PT12S')$this->storage);
    }
}


    public function handle(ConditionInterface $condition, QueryBuilder $query)
    {
        $this->addCondition($condition$query);
    }

    private function addCondition(OrderedInLastDaysCondition $condition, QueryBuilder $query): void
    {
        $query->andWhere('customer.last_order_time >= :OrderedInLastDaysCondition');
        $date = new DateTime();
        $date->sub(new DateInterval('P' . $condition->getLastDays() . 'D'));
        $query->setParameter(':OrderedInLastDaysCondition', $date->format('Y-m-d H:i:s'));
    }
}
yield [new PeriodicalTrigger('24 hours', $from$until)];
        yield [new PeriodicalTrigger('1440 minutes', $from$until)];
        yield [new PeriodicalTrigger('86400 seconds', $from$until)];
        yield [new PeriodicalTrigger('1day', $from$until), false];
        yield [new PeriodicalTrigger('24hours', $from$until)];
        yield [new PeriodicalTrigger('1440minutes', $from$until)];
        yield [new PeriodicalTrigger('86400seconds', $from$until)];
        yield [new PeriodicalTrigger('P1D', $from$until), false];
        yield [new PeriodicalTrigger('PT24H', $from$until)];
        yield [new PeriodicalTrigger('PT1440M', $from$until)];
        yield [new PeriodicalTrigger('PT86400S', $from$until)];
        yield [new PeriodicalTrigger(new \DateInterval('P1D')$now$farFuture), false];
        yield [new PeriodicalTrigger(new \DateInterval('P1D')$now), false];
    }

    /** * @dataProvider getInvalidIntervals */
    public function testInvalidInterval($interval)
    {
        $this->expectException(InvalidArgumentException::class);

        new PeriodicalTrigger($interval$now = new \DateTimeImmutable()$now->modify('1 day'));
    }


    /** * Gets the turnover and visitors amount for the * chart and the grid in the "Turnover - Yesterday and today"-widget. * * @return void */
    public function getTurnOverVisitorsAction()
    {
        $startDate = new DateTime();
        $startDate->setTime(0, 0, 0)->sub(new DateInterval('P7D'));

        // Get turnovers         /** @var array $fetchAmount */
        $fetchAmount = $this->get('db')->fetchRow(
            'SELECT ( SELECT sum(invoice_amount/currencyFactor) AS amount FROM s_order WHERE TO_DAYS(ordertime) = TO_DAYS(now()) AND status != 4 AND status != -1 ) AS today, ( SELECT sum(invoice_amount/currencyFactor) AS amount FROM s_order WHERE TO_DAYS(ordertime) = (TO_DAYS( NOW( ) )-1) AND status != 4 AND status != -1 ) AS yesterday '
$this->forward('index');

            return;
        }

        $toDate = $this->Request()->get('toDate');
        $fromDate = $this->Request()->get('fromDate');

        // If a "fromDate" is passed, format it over the \DateTime object. Otherwise, create a new date with today         if (empty($fromDate) || !Zend_Date::isDate($fromDate, 'Y-m-d')) {
            $fromDate = new DateTime();
            $fromDate = $fromDate->sub(new DateInterval('P1M'));
        } else {
            $fromDate = new DateTime($fromDate);
        }

        // If a "toDate" is passed, format it over the \DateTime object. Otherwise, create a new date with today         if (empty($toDate) || !Zend_Date::isDate($toDate, 'Y-m-d')) {
            $toDate = new DateTime();
        } else {
            $toDate = new DateTime($toDate);
        }

        
$doSet = function D$name$value, \DateInterval $expiresAfter = null) use ($cache) {
            $item = $cache->getItem($name);
            $item->set($value);

            if ($expiresAfter) {
                $item->expiresAfter($expiresAfter);
            }

            $cache->save($item);
        };

        $doSet('foo', 'foo-val', new \DateInterval('PT05S'));
        $doSet('bar', 'bar-val', new \DateInterval('PT10S'));
        $doSet('baz', 'baz-val', new \DateInterval('PT15S'));
        $doSet('qux', 'qux-val', new \DateInterval('PT20S'));

        sleep(30);
        $this->assertTrue($cache->prune());
        $this->assertTrue($this->isPruned($cache, 'foo'));
        $this->assertTrue($this->isPruned($cache, 'bar'));
        $this->assertTrue($this->isPruned($cache, 'baz'));
        $this->assertTrue($this->isPruned($cache, 'qux'));

        
yield 'Both accepted with different count of remaining tokens' => [
            [
                $expected = new RateLimit(0, $now, true, 1), // less remaining tokens                 new RateLimit(1, $now, true, 1),
            ],
            $expected,
        ];

        yield 'Both accepted with same count of remaining tokens' => [
            [
                $expected = new RateLimit(0, $now->add(new \DateInterval('P1D')), true, 1), // longest wait time                 new RateLimit(0, $now, true, 1),
            ],
            $expected,
        ];

        yield 'Accepted and denied' => [
            [
                new RateLimit(0, $now, true, 1),
                $expected = new RateLimit(0, $now, false, 1), // denied             ],
            $expected,
        ];

    public function getOrderTime($interval = 365)
    {
        trigger_error(sprintf('%s:%s is deprecated since Shopware 5.6 and will be removed with 5.7. Will be removed without replacement.', __CLASS__, __METHOD__), E_USER_DEPRECATED);

        $orderTime = new DateTime();
        $orderTime->sub(new DateInterval('P' . (int) $interval . 'D'));

        return $orderTime;
    }
}
if ('' === $value) {
            return null;
        }
        if (!$this->isISO8601($value)) {
            throw new TransformationFailedException('Non ISO 8601 date strings are not supported yet.');
        }
        $valuePattern = '/^'.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?P<$1>\d+)$2', $this->format).'$/';
        if (!preg_match($valuePattern$value)) {
            throw new TransformationFailedException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $value$this->format));
        }
        try {
            $dateInterval = new \DateInterval($value);
        } catch (\Exception $e) {
            throw new TransformationFailedException($e->getMessage()$e->getCode()$e);
        }

        return $dateInterval;
    }

    private function isISO8601(string $string): bool
    {
        return preg_match('/^P(?=\w*(?:\d|%\w))(?:\d+Y|%[yY]Y)?(?:\d+M|%[mM]M)?(?:(?:\d+D|%[dD]D)|(?:\d+W|%[wW]W))?(?:T(?:\d+H|[hH]H)?(?:\d+M|[iI]M)?(?:\d+S|[sS]S)?)?$/', $string);
    }
}
$this->assertEquals(40, $typed_data->getDuration()->d, 'DurationIso8601 value was changed and set by duration string.');
    $this->assertIsString($typed_data->getString());
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue(NULL);
    $this->assertNull($typed_data->getValue(), 'DurationIso8601 wrapper is null-able.');
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue('invalid');
    $this->assertEquals(1, $typed_data->validate()->count(), 'Validation detected invalid value.');
    // Check implementation of DurationInterface.     $typed_data = $this->createTypedData(['type' => 'duration_iso8601'], 'PT20S');
    $this->assertInstanceOf(\DateInterval::class$typed_data->getDuration());
    $typed_data->setDuration(new \DateInterval('P40D'));
    // @todo: Should we make this "nicer"?     $this->assertEquals('P0Y0M40DT0H0M0S', $typed_data->getValue());
    $typed_data->setValue(NULL);
    $this->assertNull($typed_data->getDuration());

    // Time span type.     $value = 20;
    $typed_data = $this->createTypedData(['type' => 'timespan']$value);
    $this->assertInstanceOf(DurationInterface::class$typed_data);
    $this->assertSame($value$typed_data->getValue(), 'Time span value was fetched.');
    $this->assertEquals(0, $typed_data->validate()->count());
    
ShopContextInterface $context
    ) {
        $search->addPostFilter(
            $this->getQuery($criteriaPart)
        );
    }

    private function getQuery(CreateDateCondition $criteriaPart): RangeQuery
    {
        $date = new DateTime();
        $intervalSpec = 'P' . $criteriaPart->getDays() . 'D';
        $interval = new DateInterval($intervalSpec);
        $date->sub($interval);

        return new RangeQuery('formattedCreatedAt', [
            'gte' => $date->format('Y-m-d'),
        ]);
    }
}
Home | Imprint | This part of the site doesn't use cookies.