Skip to content

Commit

Permalink
Rework descriptions.
Browse files Browse the repository at this point in the history
  • Loading branch information
timvandijck committed Mar 25, 2024
1 parent 19e2630 commit 552ada5
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/SimpleStat.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ class SimpleStat

protected ?string $label;

protected ?string $description;

protected bool $overWriteDescription = false;

public string $dateColumn = 'created_at';

public function __construct(private readonly string $model)
Expand All @@ -33,6 +37,14 @@ public function label(string $label): self
return $this;
}

public function description(string $description): self
{
$this->description = $description;
$this->overWriteDescription = true;

return $this;
}

public function dateColumn(string $dateColumn): self
{
$this->trend->dateColumn($dateColumn);
Expand All @@ -58,6 +70,10 @@ public function lastDays(int $days): self
end: now(),
);

if (!$this->overWriteDescription) {
$this->description = __('Last :days days', ['days' => $days]);
}

return $this;
}

Expand Down Expand Up @@ -118,7 +134,8 @@ private function buildAverageStat(Collection $trendData): Stat
private function buildStat(string $faceValue, Collection $chartValues, AggregateType $aggregateType): Stat
{
return Stat::make($this->buildLabel($aggregateType), $faceValue)
->chart($chartValues->map(fn (TrendValue $trend) => $trend->aggregate)->toArray());
->chart($chartValues->map(fn (TrendValue $trend) => $trend->aggregate)->toArray())
->description($this->description);
}

private function buildLabel(AggregateType $aggregateType): string
Expand Down
27 changes: 27 additions & 0 deletions tests/DescriptionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

use Carbon\CarbonPeriod;
use Illuminate\Support\Carbon;
use Spatie\FilamentSimpleStat\SimpleStat;
use Spatie\FilamentSimpleStat\Tests\Support\ExampleEvent;

beforeEach(function () {
Carbon::setTestNow(Carbon::parse('2024-02-22'));

$period = CarbonPeriod::create('2024-03-20', '2024-03-25');

foreach ($period as $date) {
ExampleEvent::factory()->count(rand(0, 2))->create(['created_at' => $date]);
}
});

it('constructs a description based on the interval', function () {
$simpleStat = SimpleStat::make(ExampleEvent::class)->last7Days()->dailyAverage();
expect($simpleStat->getDescription())->toBe('Last 7 days');

$simpleStat = SimpleStat::make(ExampleEvent::class)->last30Days()->dailyAverage();
expect($simpleStat->getDescription())->toBe('Last 30 days');

$simpleStat = SimpleStat::make(ExampleEvent::class)->lastDays(14)->dailyAverage();
expect($simpleStat->getDescription())->toBe('Last 14 days');
});

0 comments on commit 552ada5

Please sign in to comment.