-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathDatabaseAnalyticsRepository.php
More file actions
85 lines (73 loc) · 2.44 KB
/
DatabaseAnalyticsRepository.php
File metadata and controls
85 lines (73 loc) · 2.44 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?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\PanConfiguration;
use Pan\ValueObjects\Analytic;
/**
* @internal
*/
final readonly class DatabaseAnalyticsRepository implements AnalyticsRepository
{
/**
* Creates a new analytics repository instance.
*/
public function __construct(private PanConfiguration $config)
{
//
}
/**
* 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: (int) $analytic->id, // @phpstan-ignore-line
name: $analytic->name, // @phpstan-ignore-line
impressions: (int) $analytic->impressions, // @phpstan-ignore-line
hovers: (int) $analytic->hovers, // @phpstan-ignore-line
clicks: (int) $analytic->clicks, // @phpstan-ignore-line
))->toArray();
return $all;
}
/**
* Increments the given event for the given analytic.
*/
public function increment(string $name, EventType $event): void
{
[
'allowed_analytics' => $allowedAnalytics,
'max_analytics' => $maxAnalytics,
] = $this->config->toArray();
if (count($allowedAnalytics) > 0 && ! in_array($name, $allowedAnalytics, true)) {
return;
}
DB::transaction(function () use ($name, $event, $maxAnalytics) {
// Lock the table for this name to prevent race conditions
$existing = DB::table('pan_analytics')
->where('name', $name)
->lockForUpdate()
->first();
if ($existing === null) {
// Check total count with lock to prevent race condition on max analytics
if (DB::table('pan_analytics')->lockForUpdate()->count() < $maxAnalytics) {
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();
}
}