forked from panphp/pan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseAnalyticsRepository.php
More file actions
69 lines (58 loc) · 1.77 KB
/
Copy pathDatabaseAnalyticsRepository.php
File metadata and controls
69 lines (58 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
declare(strict_types=1);
namespace Pan\Adapters\Laravel\Repositories;
use Illuminate\Support\Facades\DB;
use Pan\Contracts\AnalyticsRepository;
use Pan\Enums\EventType;
use Pan\ValueObjects\Analytic;
/**
* @internal
*/
final readonly class DatabaseAnalyticsRepository implements AnalyticsRepository
{
/**
* Returns all analytics.
*
* @return array<int, Analytic>
*/
public function all(): array
{
/** @var array<int, Analytic> $all */
$all = DB::table('pan_analytics')->get()->map(fn (mixed $analytic): Analytic => new Analytic(
id: $analytic->id, // @phpstan-ignore-line
name: $analytic->name, // @phpstan-ignore-line
impressions: $analytic->impressions, // @phpstan-ignore-line
hovers: $analytic->hovers, // @phpstan-ignore-line
clicks: $analytic->clicks, // @phpstan-ignore-line
))->toArray();
return $all;
}
/**
* Increments the given event for the given analytic.
*/
public function increment(string $name, EventType $event): void
{
$query = DB::table('pan_analytics')->get();
if ($query->where('name', $name)->count() === 0) {
if ($query->count() < 50) {
DB::table('pan_analytics')->insert(['name' => $name, $event->column() => 1]);
}
return;
}
DB::table('pan_analytics')->where('name', $name)->increment($event->column());
}
/**
* Flush all analytics.
*/
public function flush(): void
{
DB::table('pan_analytics')->truncate();
}
/**
* Delete a specific analytic by ID.
*/
public function delete(int $id): int
{
return DB::table('pan_analytics')->where('id', $id)->delete();
}
}