Created
March 16, 2018 11:20
-
-
Save thatside/8351a1474c615a15138997b35466de46 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Carbon\Carbon; | |
/** | |
* Trait PeriodMultiplier | |
* Used in cases when class has | |
*/ | |
trait PeriodMultiplierTrait | |
{ | |
/** | |
* Calculate float amount of months | |
* | |
* @param Carbon $startDate | |
* @param Carbon $endDate | |
* | |
* @return float | |
*/ | |
protected function calculatePeriodMultiplier(Carbon $startDate, Carbon $endDate) : float | |
{ | |
$startDay = $startDate->day; | |
$endDay = $endDate->day; | |
$startDateBase = (clone $startDate)->addDays(1 - $startDay); | |
$endDateBase = (clone $endDate)->addDays(1 - $endDay); | |
if ($startDay === 1 && $endDay === $endDate->daysInMonth && $startDate->month === $endDate->month) { | |
$diffInYears = $startDate->diff($endDate)->format('%r%y'); | |
return $diffInYears * 12 + 1; | |
} | |
$startDate->setTime(0, 0, 0); | |
$endDate->setTime(0, 0, 0); | |
if ($startDate->day <= $endDate->day && ($startDate->day !== $startDate->daysInMonth || $endDate->day !== $endDate->daysInMonth)) { //strange PHP DateInterval behaviour | |
$monthDiff = $startDate->diffInMonths($endDate, false); //TODO update this | |
} else { | |
$monthDiff = $startDate->diffInMonths($endDate, false) + 1; | |
} | |
$amount = $monthDiff - | |
($startDay - 1) / ($startDateBase->diffInDays((clone $startDateBase)->addMonth())) + | |
($endDay - 1) / ($endDateBase->diffInDays((clone $endDateBase)->addMonth())); | |
return round($amount, 3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment