-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathDatabaseAnalyticsRepository.php
More file actions
99 lines (83 loc) · 2.57 KB
/
DatabaseAnalyticsRepository.php
File metadata and controls
99 lines (83 loc) · 2.57 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?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
{
[
'tenant_field' => $tenantField,
] = $this->config->toArray();
/** @var array<int, Analytic> $all */
$all = DB::table('pan_analytics')->get()->map(fn (mixed $analytic): Analytic => new Analytic(
id: (int) $analytic->id,
tenant: ($tenantField) ? $analytic->{$tenantField} : null,
name: $analytic->name,
impressions: (int) $analytic->impressions,
hovers: (int) $analytic->hovers,
clicks: (int) $analytic->clicks,
))->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,
'tenant_field' => $tenantField,
'tenant_id' => $tenantId,
] = $this->config->toArray();
if (count($allowedAnalytics) > 0 && ! in_array($name, $allowedAnalytics, true)) {
return;
}
// Restrict query to tenant if tenant field and id are set
$baseQuery = DB::table('pan_analytics');
if ($tenantField !== null && $tenantId !== null) {
$baseQuery->where($tenantField, $tenantId);
}
$fieldQuery = clone $baseQuery;
$fieldQuery = $fieldQuery->where('name', $name);
if ($fieldQuery->count() === 0) {
if ($baseQuery->count() < $maxAnalytics) {
$baseQuery->insert(array_filter([
'name' => $name,
$event->column() => 1,
'tenant_field' => $tenantField,
'tenant_id' => $tenantId,
]));
}
return;
}
$fieldQuery->increment($event->column());
}
/**
* Flush all analytics.
*/
public function flush(): void
{
DB::table('pan_analytics')->truncate();
}
}