Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

2.1 KB
Raw Blame
<?php

declare(strict_types=1);

namespace App\Actions\Analytics;

use App\Dto\Analytics\DateRange;
use Carbon\CarbonImmutable;

class ResolveAnalyticsDateRange
{
    /**
     * @param  array{min: ?string, max: ?string}  $bounds
     * @param  array{start?: string, end?: string, observed_through?: string, timezone?: string}  $selected
     */
    public function execute(array $bounds, array $selected, bool $clampToBounds = true): DateRange
    {
        $selectedStart = data_get($selected, 'start');
        $selectedEnd = data_get($selected, 'end');
        $timezone = data_get($selected, 'timezone', 'UTC');

        if (! $clampToBounds && $selectedStart !== null && $selectedEnd !== null) {
            $observedThrough = data_get($selected, 'observed_through');

            return new DateRange(
                CarbonImmutable::parse($selectedStart, 'UTC'),
                CarbonImmutable::parse($selectedEnd, 'UTC'),
                $observedThrough === null ? null : CarbonImmutable::parse($observedThrough, 'UTC'),
                $timezone,
            );
        }

        $minimumDate = data_get($bounds, 'min');
        $maximumDate = data_get($bounds, 'max');
        $end = $maximumDate ? CarbonImmutable::parse($maximumDate, 'UTC') : CarbonImmutable::parse(now($timezone)->toDateString(), 'UTC');
        $start = $end->subDays(29);

        if ($minimumDate !== null && $selectedStart !== null) {
            $start = CarbonImmutable::parse($selectedStart, 'UTC');
        }

        if ($maximumDate !== null && $selectedEnd !== null) {
            $end = CarbonImmutable::parse($selectedEnd, 'UTC');
        }

        if ($minimumDate !== null && $maximumDate !== null) {
            $minimum = CarbonImmutable::parse($minimumDate, 'UTC');
            $maximum = CarbonImmutable::parse($maximumDate, 'UTC');
            $start = $start->lessThan($minimum) ? $minimum : ($start->greaterThan($maximum) ? $maximum : $start);
            $end = $end->lessThan($minimum) ? $minimum : ($end->greaterThan($maximum) ? $maximum : $end);
        }

        return new DateRange($start->greaterThan($end) ? $end : $start, $end, timezone: $timezone);
    }
}