44
55use App \StoredEvents \Projector ;
66use App \Web \Analytics \PackageDownloadsListed ;
7+ use PDOException ;
78use Tempest \Database \Builder \QueryBuilders \QueryBuilder ;
8- use Tempest \Database \Query ;
99use Tempest \EventBus \EventHandler ;
10+ use function Tempest \Database \query ;
1011
1112final readonly class PackageDownloadsPerDayProjector implements Projector
1213{
@@ -15,6 +16,7 @@ public function clear(): void
1516 {
1617 new QueryBuilder (PackageDownloadsPerDay::class)
1718 ->delete ()
19+ ->allowAll ()
1820 ->execute ();
1921 }
2022
@@ -29,19 +31,28 @@ public function replay(object $event): void
2931 #[EventHandler]
3032 public function onPackageDownloadsListed (PackageDownloadsListed $ event ): void
3133 {
34+ $ date = $ event ->date ->setTime (0 , 0 );
35+
3236 $ count = $ event ->total ;
3337
3438 $ count = max ($ count , 0 );
3539
36- PackageDownloadsPerDay::updateOrCreate (
37- [
38- 'date ' => $ event ->date ,
39- 'package ' => $ event ->package ,
40- ],
41- [
42- 'total ' => $ event ->total ,
43- 'count ' => $ count ,
44- ],
45- );
40+ $ packageDownloadsPerDay = query (PackageDownloadsPerDay::class)
41+ ->select ()
42+ ->where ('date = ? AND package = ? ' , $ date , $ event ->package )
43+ ->first ();
44+
45+ if (!$ packageDownloadsPerDay ) {
46+ $ packageDownloadsPerDay = new PackageDownloadsPerDay (
47+ date: $ date ,
48+ package: $ event ->package ,
49+ count: 0 ,
50+ total: 0 ,
51+ );
52+ }
53+
54+ $ packageDownloadsPerDay ->total = $ event ->total ;
55+ $ packageDownloadsPerDay ->count = $ count ;
56+ $ packageDownloadsPerDay ->save ();
4657 }
4758}
0 commit comments