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;
7
8use App\Models\Comment;
9use App\Models\User;
10use App\Models\UserProfileCustomization;
11
12class CommentBundleParams
13{
14 const DEFAULT_PAGE = 1;
15 const DEFAULT_LIMIT = 50;
16
17 public ?int $after = null;
18 public $userId;
19 public $commentableId;
20 public $commentableType;
21 public $parentId;
22 public $cursor;
23 public $cursorRaw;
24 public $cursorHelper;
25 public $limit;
26 public $page;
27 public $sort;
28
29 /**
30 * @param array $params The params from request().
31 * @param User|null $user The user viewing the comments.
32 */
33 public function __construct(array $params, ?User $user)
34 {
35 $this->userId = null;
36 $this->parentId = null;
37 $this->cursor = null;
38 $this->limit = static::DEFAULT_LIMIT;
39 $this->page = static::DEFAULT_PAGE;
40 $this->sort = UserProfileCustomization::forUser($user)['comments_sort'];
41
42 $this->setAll($params);
43 }
44
45 public function setAll($params)
46 {
47 if (array_key_exists('user_id', $params)) {
48 $this->userId = get_int($params['user_id']);
49 }
50
51 if (array_key_exists('parent_id', $params)) {
52 $this->parentId = get_int($params['parent_id']);
53 }
54
55 if (array_key_exists('limit', $params)) {
56 $this->limit = \Number::clamp(get_int($params['limit']) ?? 50, 1, 100);
57 }
58
59 if (array_key_exists('page', $params)) {
60 $this->page = max(get_int($params['page']), 1);
61 }
62
63 $this->commentableId = $params['commentable_id'] ?? null;
64 $this->commentableType = $params['commentable_type'] ?? null;
65
66 $this->cursorHelper = Comment::makeDbCursorHelper($params['sort'] ?? $this->sort);
67 $this->cursor = get_arr($params['cursor'] ?? null);
68 $this->sort = $this->cursorHelper->getSortName();
69 $this->after = get_int($params['after'] ?? null);
70 }
71
72 public function filterByParentId()
73 {
74 return $this->parentId !== null;
75 }
76
77 public function forUrl()
78 {
79 $params = [
80 'commentable_id' => $this->commentableId,
81 'commentable_type' => $this->commentableType,
82 'cursor' => $this->cursor,
83 ];
84
85 if ($this->userId !== null) {
86 $params['user_id'] = $this->userId;
87 }
88
89 if ($this->parentId !== null) {
90 $params['parent_id'] = $this->parentId;
91 }
92
93 if ($this->page !== static::DEFAULT_PAGE) {
94 $params['page'] = $this->page;
95 }
96
97 if ($this->limit !== static::DEFAULT_LIMIT) {
98 $params['limit'] = $this->limit;
99 }
100
101 if ($this->sort !== Comment::DEFAULT_SORT) {
102 $params['sort'] = $this->sort;
103 }
104
105 return $params;
106 }
107
108 public function parentIdForWhere()
109 {
110 return $this->parentId === 0 ? null : $this->parentId;
111 }
112}