-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathDatabaseAnalyticsRepository.php
More file actions
86 lines (73 loc) · 2.3 KB
/
DatabaseAnalyticsRepository.php
File metadata and controls
86 lines (73 loc) · 2.3 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
<?php
declare(strict_types=1);
namespace Pan\Adapters\Laravel\Repositories;
use Illuminate\Database\Connection;
use Illuminate\Database\DatabaseManager;
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 DatabaseManager $db,
private PanConfiguration $config
) {}
/**
* Returns all analytics.
*
* @return array<int, Analytic>
*/
public function all(): array
{
/** @var array<int, Analytic> $all */
$all = $this->connection()->table('pan_analytics')->get()->map(fn (mixed $analytic): Analytic => new Analytic(
id: (int) $analytic->id,
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,
] = $this->config->toArray();
if (count($allowedAnalytics) > 0 && ! in_array($name, $allowedAnalytics, true)) {
return;
}
if ($this->connection()->table('pan_analytics')->where('name', $name)->count() === 0) {
if ($this->connection()->table('pan_analytics')->count() < $maxAnalytics) {
$this->connection()->table('pan_analytics')->insert(['name' => $name, $event->column() => 1]);
}
return;
}
$this->connection()->table('pan_analytics')->where('name', $name)->increment($event->column());
}
/**
* Flush all analytics.
*/
public function flush(): void
{
$this->connection()->table('pan_analytics')->truncate();
}
/**
* Resolve the database connection.
*/
private function connection(): Connection
{
return $this->db->connection($this->config->getDatabaseConnection());
}
}