@@ -30,13 +30,18 @@ public function __construct(private PanConfiguration $config)
3030 */
3131 public function all (): array
3232 {
33+ [
34+ 'tenant_field ' => $ tenantField ,
35+ ] = $ this ->config ->toArray ();
36+
3337 /** @var array<int, Analytic> $all */
3438 $ all = DB ::table ('pan_analytics ' )->get ()->map (fn (mixed $ analytic ): Analytic => new Analytic (
35- id: (int ) $ analytic ->id , // @phpstan-ignore-line
36- name: $ analytic ->name , // @phpstan-ignore-line
37- impressions: (int ) $ analytic ->impressions , // @phpstan-ignore-line
38- hovers: (int ) $ analytic ->hovers , // @phpstan-ignore-line
39- clicks: (int ) $ analytic ->clicks , // @phpstan-ignore-line
39+ id: (int ) $ analytic ->id ,
40+ tenant: ($ tenantField ) ? $ analytic ->{$ tenantField } : null ,
41+ name: $ analytic ->name ,
42+ impressions: (int ) $ analytic ->impressions ,
43+ hovers: (int ) $ analytic ->hovers ,
44+ clicks: (int ) $ analytic ->clicks ,
4045 ))->toArray ();
4146
4247 return $ all ;
@@ -50,21 +55,38 @@ public function increment(string $name, EventType $event): void
5055 [
5156 'allowed_analytics ' => $ allowedAnalytics ,
5257 'max_analytics ' => $ maxAnalytics ,
58+ 'tenant_field ' => $ tenantField ,
59+ 'tenant_id ' => $ tenantId ,
5360 ] = $ this ->config ->toArray ();
5461
5562 if (count ($ allowedAnalytics ) > 0 && ! in_array ($ name , $ allowedAnalytics , true )) {
5663 return ;
5764 }
5865
59- if (DB ::table ('pan_analytics ' )->where ('name ' , $ name )->count () === 0 ) {
60- if (DB ::table ('pan_analytics ' )->count () < $ maxAnalytics ) {
61- DB ::table ('pan_analytics ' )->insert (['name ' => $ name , $ event ->column () => 1 ]);
66+ // Restrict query to tenant if tenant field and id are set
67+ $ baseQuery = DB ::table ('pan_analytics ' );
68+
69+ if ($ tenantField !== null && $ tenantId !== null ) {
70+ $ baseQuery ->where ($ tenantField , $ tenantId );
71+ }
72+
73+ $ fieldQuery = clone $ baseQuery ;
74+ $ fieldQuery = $ fieldQuery ->where ('name ' , $ name );
75+
76+ if ($ fieldQuery ->count () === 0 ) {
77+ if ($ baseQuery ->count () < $ maxAnalytics ) {
78+ $ baseQuery ->insert (array_filter ([
79+ 'name ' => $ name ,
80+ $ event ->column () => 1 ,
81+ 'tenant_field ' => $ tenantField ,
82+ 'tenant_id ' => $ tenantId ,
83+ ]));
6284 }
6385
6486 return ;
6587 }
6688
67- DB :: table ( ' pan_analytics ' )-> where ( ' name ' , $ name ) ->increment ($ event ->column ());
89+ $ fieldQuery ->increment ($ event ->column ());
6890 }
6991
7092 /**
0 commit comments