Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Business Days Bundle Laravel Package

chaplean/business-days-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chaplean/business-days-bundle
    

    (Note: The README mentions Chaplean\Bundle\MailerBundle, but the package is actually ChapleanBusinessDaysBundle. Verify this in composer.json.)

  2. Register the Bundle In config/bundles.php (Symfony 4+), add:

    return [
        // ...
        Chaplean\BusinessDaysBundle\ChapleanBusinessDaysBundle::class => ['all' => true],
    ];
    
  3. First Use Case Inject the BusinessDaysCalculator service into a controller or service:

    use Chaplean\BusinessDaysBundle\Calculator\BusinessDaysCalculator;
    
    class OrderController extends Controller
    {
        public function __construct(private BusinessDaysCalculator $businessDays)
        {
        }
    
        public function estimateDelivery(DateTimeInterface $orderDate)
        {
            $businessDays = $this->businessDays->calculate(
                $orderDate,
                new DateTime('now'),
                ['Sat', 'Sun'] // Non-business days
            );
            return $businessDays;
        }
    }
    

Implementation Patterns

Core Workflows

  1. Basic Business Days Calculation

    $calculator = $this->container->get('chaplean_business_days.calculator');
    $days = $calculator->calculate(
        new DateTime('2023-10-01'), // Start date
        new DateTime('2023-10-10'), // End date
        ['Sat', 'Sun']              // Non-business days
    );
    
  2. Holiday Exclusions Extend the calculator to exclude holidays dynamically:

    $holidays = ['2023-12-25', '2024-01-01']; // Christmas, New Year's
    $days = $calculator->calculate(
        $startDate,
        $endDate,
        ['Sat', 'Sun'],
        $holidays
    );
    
  3. Recurring Events Use a BusinessDaysCalculatorInterface implementation to handle recurring holidays (e.g., monthly):

    $calculator->addRecurringHoliday(
        '2023-12-25', // Base date
        'P1M'         // Recurrence rule (monthly)
    );
    
  4. Integration with Laravel Bind the service in AppServiceProvider:

    public function register()
    {
        $this->app->bind('businessDays', function ($app) {
            return new \Chaplean\BusinessDaysBundle\Calculator\BusinessDaysCalculator();
        });
    }
    
  5. Command-Line Usage Create an Artisan command for batch processing:

    use Chaplean\BusinessDaysBundle\Calculator\BusinessDaysCalculator;
    
    class CalculateBusinessDaysCommand extends Command
    {
        protected $calculator;
    
        public function __construct(BusinessDaysCalculator $calculator)
        {
            parent::__construct();
            $this->calculator = $calculator;
        }
    
        protected function handle()
        {
            $days = $this->calculator->calculate(
                new DateTime($this->argument('start')),
                new DateTime($this->argument('end'))
            );
            $this->info("Business days: {$days}");
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Bundle Registration

    • The README references MailerBundle, but the package is BusinessDaysBundle. Double-check the namespace in composer.json and config/bundles.php.
    • If using Symfony <4, ensure AppKernel.php includes the bundle in the correct environment (e.g., prod, dev).
  2. Time Zone Sensitivity

    • The calculator uses the system's default time zone. Explicitly set it in your DateTime objects:
      $date = new DateTime('now', new DateTimeZone('America/New_York'));
      
  3. Holiday Handling

    • The package does not natively support country-specific holidays. Extend the BusinessDaysCalculator or use a third-party library like spatie/holidays for dynamic holiday lists.
  4. Edge Cases

    • Same-Day Start/End: The calculator may return 0 if $startDate and $endDate are the same. Handle this in your logic:
      if ($startDate >= $endDate) {
          return 0;
      }
      
    • Weekend Inclusions: Ensure non-business days (e.g., ['Sat', 'Sun']) are passed correctly. Defaults may vary.
  5. Performance

    • For large date ranges (e.g., years), consider caching results or using a more optimized library like carbon/carbon with custom logic.

Debugging

  1. Verify Inputs Log the $startDate, $endDate, and non-business days to ensure they match expectations:

    \Log::debug('Calculating between', [
        'start' => $startDate->format('Y-m-d H:i:s'),
        'end' => $endDate->format('Y-m-d H:i:s'),
        'nonBusinessDays' => json_encode($nonBusinessDays),
    ]);
    
  2. Test with Known Values Use a fixed date range to validate:

    $days = $calculator->calculate(
        new DateTime('2023-10-02'), // Monday
        new DateTime('2023-10-06')  // Friday
    );
    // Expected: 4 business days (Mon-Fri)
    

Extension Points

  1. Custom Calculators Implement Chaplean\BusinessDaysBundle\Calculator\BusinessDaysCalculatorInterface to add logic (e.g., partial-day handling):

    class CustomBusinessDaysCalculator implements BusinessDaysCalculatorInterface
    {
        public function calculate(DateTimeInterface $start, DateTimeInterface $end, array $nonBusinessDays, array $holidays = [])
        {
            // Custom logic here
        }
    }
    
  2. Event Listeners Dispatch events for business day calculations (e.g., logging or notifications):

    $dispatcher->addListener(
        'chaplean.business_days.calculate',
        function ($event) {
            \Log::info('Business days calculated', $event->getData());
        }
    );
    
  3. Configuration Override defaults in config/packages/chaplean_business_days.yaml:

    chaplean_business_days:
        default_non_business_days: ['Sat', 'Sun']
        time_zone: 'UTC'
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui