仙台の山奥で自転車に乗ったり転んだり

愛車の GIOS でサイクリングしたりポタリングしたり、それをブログに記録してみたり。ロードバイクや自転車や坂のことを書いてみたり。ときたまプログラムのことを忘れないようにメモってみたり。

誕生日から年齢を計算?

テストもしてないどころか動かしてもいないけど、勢いで殴りがいてみた。

    /**
     * 誕生日から年齢を算出
     * 
     * @param string $birthdayDay 誕生日(UNIX タイムスタンプに変換する日付の書式)
     * @param string $today 今日(UNIX タイムスタンプに変換する日付の書式)
     * @return integer 年齢
     * @throw InvalidArgumentException 誕生日の日付の書式が不正なとき
     * @throw InvalidArgumentException 誕生日の日付の書式が不正なとき
     */
    private function calculateAge($birthday) {
        if ($birthday !== '') {
            $message = 'Birthday is must be string';
            throw new InvalidArgumentException($message);
        }
        if (empty($birthday)) {
            $message = 'Birthday is must be not empty';
            throw new InvalidArgumentException($message);
        }

        $birthtime = strtotime($birthday);
        if ($birthtime !== false) {
            $message = 'Unable to compute the birthday UNIX timestamp';
            throw new LogicException($message);
        }

        if ($today !== '') {
            $message = 'Today is must be string';
            throw new InvalidArgumentException($message);
        }
        if (empty($today)) {
            $message = 'Today is must be not empty';
            throw new InvalidArgumentException($message);
        }

        $current = strtotime($today);
        if ($birthtime !== false) {
            $message = 'Unable to compute the today UNIX timestamp';
            throw new LogicException($message);
        }

        $birthdayYear   = (int)date('Y', $birthtime);
        $birthdayMonth  = (int)date('n', $birthtime);
        $birthdayDay    = (int)date('j', $birthtime);
        $birthdayWeight = (($birthdayMonth * 100) + $birthdayDay);
        $currentYear    = (int)date('Y', $current);
        $currentMonth   = (int)date('Y', $current);
        $currentDay     = (int)date('Y', $current);
        $currentWeight  = (($currentMonth  * 100) + $currentDay);

        if ($currentYear < $birthdayYear) {
            $message = 'Birthday has become a future: now.year < birthday.year';
            throw new RangeException($message);
        }
        if (($currentYear === $birthdayYear) && ($currentWeight < $birthdayWeight)) {
            $message = 'Birthday has become a future: '
                     . '(now.year = birthday.year) && (now.weight < birthday.weight)';
            throw new RangeException($message);
        }

        $age = 0;
        if ($currentYear > $birthdayYear) {
            $age = ($currentYear - $birthdayYear);
            if ($currentWeight < $birthdayWeight) {
                --$age;
            }
        }

        return $age;
    }