Skip to content

Commit

Permalink
Merge pull request #133 from kylekatarnls/fix/year-condition
Browse files Browse the repository at this point in the history
Fix handling for holidays occurring only on a specific year
  • Loading branch information
kylekatarnls authored Oct 17, 2024
2 parents ced4e2c + c007cfe commit b8efade
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/Cmixin/BusinessDay/Calculator/HolidayCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,11 @@ protected function parseHolidaysString(string $holiday): ?array
[$holiday, $onConditions['on']] = array_pad(explode(' on ', $holiday, 2), 2, null);
[$holiday, $condition] = array_pad(explode(' if ', $holiday, 2), 2, null);

if (strpos($holiday, "$year") === false) {
if (
!preg_match('/\d{4}-/', $holiday)
&& !preg_match('/\/\d{4}/', $holiday)
&& strpos($holiday, "$year") === false
) {
$holiday .= " $year";
}

Expand Down
5 changes: 3 additions & 2 deletions src/Cmixin/BusinessDay/Util/YearCondition.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@ trait YearCondition
*/
protected function matchYearCondition($dateTime, ?string &$condition): bool
{
$value = (int) $dateTime->format('Y');

if (!$condition || !preg_match(
'/^\s*year(?:\s*%\s*(?<modulo>\d+))?\s*(?<operator>>=?|<=?|={1,3}|!={1,2}|<>)\s*(?<expected>\d+)/',
$condition,
$match
)) {
return true;
return $this->year === $value;
}

$condition = null;
$value = (int) $dateTime->format('Y');
$expected = (int) $match['expected'];

if (!empty($match['modulo'])) {
Expand Down
28 changes: 28 additions & 0 deletions tests/Cmixin/Holidays/SgTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Tests\Cmixin\Holidays;

use Cmixin\BusinessDay;
use PHPUnit\Framework\TestCase;

class SgTest extends TestCase
{
const CARBON_CLASS = 'Carbon\Carbon';

protected function setUp(): void
{
BusinessDay::enable(static::CARBON_CLASS);
$carbon = static::CARBON_CLASS;
$carbon::resetHolidays();
}

public function testHolidays(): void
{
$carbon = static::CARBON_CLASS;
$carbon::resetHolidays();
$carbon::setHolidaysRegion('sg-national');

self::assertFalse($carbon::parse('2024-10-17')->getHolidayId());
self::assertSame('2028-10-17', $carbon::parse('2028-10-17')->getHolidayId());
}
}

0 comments on commit b8efade

Please sign in to comment.