Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
13 / 13
MonthCalc
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
13 / 13
 calc
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
13 / 13
<?php
namespace Puyo\Date;
/**
 * 月内の日数の差を考慮した月計算クラス
 *
 * たとえば 3/31 の1ヶ月前は 2/28 とする。
 */
class MonthCalc
{
    /**
     *
     * @param \DateTime $dt
     * @param int $offset
     * @return \DateTime
     */
    public function calc(\DateTime $dt, $offset) {
        if($offset === null) {
            $offset = 1;
        }
        $result = clone $dt;
        $day = $dt->format('j');
        if($offset >= 0) {
            $dayOfNextMonth = $result->add(new \DateInterval('P'.$offset.'M'))->format('j');
        } else {
            $dayOfNextMonth = $result->sub(new \DateInterval('P'.abs($offset).'M'))->format('j');
        }
        
        if($day !== $dayOfNextMonth) {
            $result->sub(new \DateInterval('P'.$dayOfNextMonth.'D'));
        }
        return $result;
    }
}