簡體   English   中英

CarbonPeriod 檢查周期是否有限

[英]CarbonPeriod checks whether period is finite or not

我寫了一個 class ,它通過迭代從某個時期收集一些信息,我需要檢查這個時期是否是有限的。 我這樣做是這樣的:

foreach ($cabonPeriod as $date) {
    // #some action
}

有限的,我的意思是這個時期是否有結束/開始並且不是時間的結束/開始,以及迭代次數是否不是無限的,但可能第一個條件會滿足第二個條件,所以我的循環不會永遠持續下去。

我找不到合適的方法,所以我寫了自己的方法,它對我有用,但它可能無法解決所有更晚期的情況,我沒有。

這是我的方法:

private static function checkPeriod(CarbonPeriod $period)
{
    $start = $period->getStartDate();
    if ($start->isStartOfTime() || $start->isEndOfTime()) {
        throw new LengthException('Period has no defined beginning');
    }
    $end = $period->calculateEnd();
    if (!$end || $end->isStartOfTime() || $end->isEndOfTime()) {
        throw new LengthException('Period has no defined end');
    }
}

在我看來,這似乎是一個微不足道的案例,所以我想知道是否有任何內置方法可以讓您以更少/更多的計算工作實現相同或類似於我的效果。

足以確保您的期間是可迭代的並且不會無限期地循環。

但是你可以有不滿足這一點的有限時期。 如果它有很多重復,那么它沒有結束,如果你想接受那些:

$end = $period->calculateEnd();
if ($end && ($end->isStartOfTime() || $end->isEndOfTime())) {
    throw new LengthException('Period has no finite end');
}

if (!$end && ($period->getRecurrences() === null || $period->getRecurrences() === INF) {
    throw new LengthException('Period has no defined end');
}

最后,您可以在一個周期內使用過濾器,過濾器無法將有限周期轉換為無限周期,因此您處於安全的一面,但隨后可以使一個周期在實踐中成為有限的,而它沒有盡頭也沒有重復。

您可能還想限制期限。 實際上,如果循環時間過長,也可能會造成麻煩(例如從 1970 年到 2060 年的間隔為 1 秒)。

對於這些情況,您可以估計周期數並確定最大值:

$end = $period->calculateEnd();
if ($end && ($end->isStartOfTime() || $end->isEndOfTime())) {
    throw new LengthException('Period has no finite end');
}

$recurrences = $period->getRecurrences();
if (!$end && ($recurrences === null || $recurrences === INF) {
    throw new LengthException('Period has no defined end');
}

$maxRecurrences = 2000;
if ($recurrences > $maxRecurrences) {
    throw new LengthException('Period is too long');
}

$seconds = $period->getDateInterval()->totalSeconds;
if ($end->diffInSeconds($start, true) / $seconds > $maxRecurrences) {
    throw new LengthException('Period is too long');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM