1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Libraries\Notification;
7
8use App\Models\Notification;
9
10class BatchIdentities
11{
12 private $notificationIds;
13 private $identities;
14
15 public static function fromParams(array $params)
16 {
17 $obj = new static();
18
19 if ($params['notifications'] ?? null) {
20 $obj->notificationIds = [];
21 $obj->identities = [];
22
23 $identities = static::scrubIdentities($params['notifications']);
24 foreach ($identities as $identity) {
25 if (isset($identity['id'])) {
26 $obj->notificationIds[] = $identity['id'];
27 $obj->identities[] = $identity;
28 }
29 }
30 } else {
31 // TODO: just use array of ids instead of subquery?
32 $obj->identities = static::scrubIdentities($params['identities'] ?? null);
33
34 foreach ($obj->identities as $identity) {
35 $query = Notification::byIdentity($identity)->select('id');
36 if ($obj->notificationIds === null) {
37 $obj->notificationIds = $query;
38 } else {
39 $obj->notificationIds->union($query);
40 }
41 }
42 }
43
44 return $obj;
45 }
46
47 public static function scrubIdentities($params): array
48 {
49 if (!is_array($params)) {
50 return [];
51 }
52
53 $identities = [];
54 foreach ($params as $param) {
55 if (is_array($param)) {
56 $identities[] = static::scrubIdentity($param);
57 }
58 }
59
60 return $identities;
61 }
62
63 public static function scrubIdentity(array $identity)
64 {
65 return get_params($identity, null, [
66 'category',
67 'id:int',
68 'object_id:int',
69 'object_type',
70 ]);
71 }
72
73 /**
74 * @return array
75 */
76 public function getIdentities()
77 {
78 return $this->identities;
79 }
80
81 /**
82 * Returns object suitable to be passed to `whereIn` query.
83 *
84 * @return array|\Illuminate\Database\Eloquent\Builder
85 */
86 public function getNotificationIds()
87 {
88 return $this->notificationIds;
89 }
90}