Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): Add endpoint for GetComments #2552

Merged
merged 39 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
fabe6a8
adding comment factory
ioslife Jul 10, 2024
b11ab6a
adding endpoint to get comments
ioslife Jul 10, 2024
cca9d3b
pint
ioslife Jul 10, 2024
3852c6f
composer analyse
ioslife Jul 10, 2024
7aa8b5a
composer analyse
ioslife Jul 10, 2024
b77f9ab
stop using class for ArticleType and ArticleID
ioslife Jul 10, 2024
a80b370
stop using class for ArticleType and ArticleID
ioslife Jul 10, 2024
29d3e2f
Update public/API/API_GetComments.php
ioslife Jul 10, 2024
b86a4fb
adding validation to username
ioslife Jul 10, 2024
ce062ab
fixing broken tests
ioslife Jul 10, 2024
dc9d366
Merge branch 'api_get_comments' of https://github.com/ioslife/RAWeb i…
ioslife Jul 10, 2024
50cc249
initial banned policy changes
ioslife Jul 10, 2024
699b221
pint
ioslife Jul 10, 2024
9b6a3fe
Merge branch 'master' into api_get_comments
ioslife Jul 29, 2024
8667609
removing blank line
ioslife Jul 31, 2024
1fa0bcd
removing debug func and refactoring tests to have full expected JSON
ioslife Jul 31, 2024
6797787
refactoring endpoint for efficiency
ioslife Jul 31, 2024
8baae83
Merge branch 'master' into api_get_comments
ioslife Jul 31, 2024
9250aba
Merge branch 'master' into api_get_comments
ioslife Aug 6, 2024
cc29d38
adding newFactory func to Comment model
ioslife Aug 7, 2024
f638a7e
renaming comments test
ioslife Aug 7, 2024
6d27361
add random user, remove commentableId/Type, add ArticleID/Type to Com…
ioslife Aug 7, 2024
38340b5
rename comments test
ioslife Aug 7, 2024
a5c5280
pint
ioslife Aug 7, 2024
f837d4b
Add `withTrashed()` to Comment queries to prevent issues with deleted…
ioslife Aug 13, 2024
3b45090
Merge branch 'master' into api_get_comments
ioslife Aug 13, 2024
edb1320
Merge branch 'master' into api_get_comments
ioslife Aug 16, 2024
452ee8f
Update GetComments to return 404 when invalid username or user wall i…
ioslife Aug 21, 2024
b49e7ae
Merge branch 'master' into api_get_comments
ioslife Aug 21, 2024
d2fd54b
Merge branch 'master' into api_get_comments
ioslife Aug 25, 2024
65f5868
Remove duplicate newFactory method in Comment
ioslife Aug 25, 2024
c4d8ca7
Run pint
ioslife Aug 25, 2024
b0e1a11
Refactor Comment endpoint to no longer need 'u' param and handle it a…
ioslife Sep 5, 2024
cac5104
Merge branch 'master' into api_get_comments
ioslife Sep 5, 2024
64c8773
Remove check for if calling user is banned
ioslife Sep 5, 2024
42c4c41
Add wall and banned check to UserCommentPolicy
ioslife Sep 12, 2024
ca72bca
Use UserCommentPolicy viewAll in GetComments API
ioslife Sep 12, 2024
bb42e71
Merge branch 'master' into api_get_comments
ioslife Sep 13, 2024
e0b0416
Merge branch 'master' into api_get_comments
wescopeland Sep 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions app/Models/Comment.php
ioslife marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
namespace App\Models;

use App\Support\Database\Eloquent\BaseModel;
use Database\Factories\CommentFactory;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
Expand All @@ -16,6 +18,7 @@ class Comment extends BaseModel
{
use Searchable;
use SoftDeletes;
use HasFactory;

// TODO rename Comment table to comments
// TODO rename ID column id
Expand Down Expand Up @@ -96,4 +99,9 @@ public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id', 'ID')->withDefault(['username' => 'Deleted User']);
}

protected static function newFactory(): CommentFactory
{
return CommentFactory::new();
}
}
2 changes: 1 addition & 1 deletion app/Policies/CommentPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function manage(User $user): bool

public function view(?User $user, Comment $comment): bool
{
return true;
return $user->isNotBanned();
wescopeland marked this conversation as resolved.
Show resolved Hide resolved
}

public function create(User $user, ?Model $commentable = null, ?int $articleType = null): bool
Expand Down
31 changes: 31 additions & 0 deletions database/factories/CommentFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\Comment;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
* @extends Factory<Comment>
*/
class CommentFactory extends Factory
{
protected $model = Comment::class;

public function definition(): array
{
$user = User::inRandomOrder()->first();

return [
'Payload' => $this->faker->paragraph,
'Submitted' => $this->faker->dateTimeBetween('-1 year', 'now'),
'Edited' => $this->faker->dateTimeBetween('now', '+1 year'),
wescopeland marked this conversation as resolved.
Show resolved Hide resolved
'user_id' => $user->ID,
'ArticleID' => $this->faker->numberBetween(1, 100),
'ArticleType' => $this->faker->numberBetween(1, 3),
];
}
}
85 changes: 85 additions & 0 deletions public/API/API_GetComments.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

use App\Models\Achievement;
use App\Models\Comment;
use App\Models\User;
use App\Policies\CommentPolicy;
use App\Support\Rules\CtypeAlnum;
use Illuminate\Support\Facades\Validator;

/*
* API_GetComments - returns the comments associated to a game or achievement
* i : game or achievement id
* u : username
* t : 1 = game, 2 = achievement, 3 = user
wescopeland marked this conversation as resolved.
Show resolved Hide resolved
* o : offset - number of entries to skip (default: 0)
* c : count - number of entries to return (default: 100, max: 500)
*
* int Count number of comment records returned in the response
* int Total number of comment records the game/achievement/user actually has overall
* array Results
* object [value]
* int User username of the commenter
* string Submitted date time the comment was submitted
* string CommentText text of the comment
*/

$input = Validator::validate(Arr::wrap(request()->query()), [
'i' => ['sometimes', 'integer'],
't' => ['required', 'integer'],
'u' => ['sometimes', 'min:2', 'max:20', new CtypeAlnum()],
'o' => ['sometimes', 'integer', 'min:0', 'nullable'],
'c' => ['sometimes', 'integer', 'min:1', 'max:500', 'nullable'],
]);

$offset = $input['o'] ?? 0;
$count = $input['c'] ?? 100;

$gameOrAchievementId = (int) request()->query('i');
$username = (string) request()->query('u');
$commentType = (int) request()->query('t');

$user = null;

if ($username) {
$user = User::firstWhere('User', $username);
if (!$user || !$user->UserWallActive) {
return response()->json(['Count' => 0, 'Total' => 0, 'Results' => []]);
}
}

$articleId = $user ? $user->ID : $gameOrAchievementId;

$comments = Comment::withTrashed()
wescopeland marked this conversation as resolved.
Show resolved Hide resolved
->where('ArticleType', $commentType)
->where('ArticleID', $articleId)
->offset($offset)
->limit($count)
->with('user')
->get();

$totalComments = Comment::withTrashed()
->where('ArticleType', $commentType)
->where('ArticleID', $articleId)
->whereHas('user', function ($query) {
$query->whereNull('banned_at');
})
->count();

$policy = new CommentPolicy();

$results = $comments->filter(function ($nextComment) use ($policy) {
return $policy->view($nextComment->user, $nextComment);
})->map(function ($nextComment) {
return [
'User' => $nextComment->user->username,
'Submitted' => $nextComment->Submitted,
'CommentText' => $nextComment->Payload,
];
});

return response()->json([
'Count' => $results->count(),
'Total' => $totalComments,
'Results' => $results,
]);
215 changes: 215 additions & 0 deletions tests/Feature/Api/V1/CommentsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
<?php

use App\Models\Achievement;
use App\Models\Comment;
use App\Models\Game;
use App\Models\System;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Carbon;
use Tests\Feature\Api\V1\BootstrapsApiV1;
use Tests\TestCase;

class CommentsTest extends TestCase
{
use RefreshDatabase; use WithFaker;
use BootstrapsApiV1;

public function testItValidates(): void
{
$this->get($this->apiUrl('GetComments', ['u' => '1', 't' => 1]))
->assertJsonValidationErrors([
'u',
]);
}

public function testGetCommentsUnknownUser(): void
{
$this->get($this->apiUrl('GetComments', ['u' => 'nonExistant', 't' => 3]))
->assertSuccessful()
->assertJson([]);
}

public function testGetCommentsForAchievement(): void
{
// Arrange
$system = System::factory()->create();
$game = Game::factory()->create(['ConsoleID' => $system->ID]);
$user1 = User::factory()->create();
$user2 = User::factory()->create();
$bannedUser = User::factory()->create(['ID' => 309, 'banned_at' => Carbon::now()->subDay()]);

$achievement = Achievement::factory()->create(['GameID' => $game->ID, 'user_id' => $user1->ID]);
$comment1 = Comment::factory()->create([
'ArticleID' => $achievement->ID,
'ArticleType' => 2,
'user_id' => $user1->ID,
'Payload' => 'This is a great achievement!',
]);
$comment2 = Comment::factory()->create([
'ArticleID' => $achievement->ID,
'ArticleType' => 2,
'user_id' => $user2->ID,
'Payload' => 'I agree, this is awesome!',
]);
$comment3 = Comment::factory()->create([
'ArticleID' => $achievement->ID,
'ArticleType' => 2,
'user_id' => $bannedUser->ID,
'Payload' => 'This comment is from a banned user!',
]);

// Act
$response = $this->get($this->apiUrl('GetComments', ['i' => $achievement->ID, 't' => 2]))
->assertSuccessful();

// Assert
$response->assertStatus(200);
$response->assertJson([
'Count' => 2,
'Total' => 2,
'Results' => [
[
'User' => $user1->User,
'Submitted' => $comment1->Submitted->toISOString(),
'CommentText' => $comment1->Payload,
],
[
'User' => $user2->User,
'Submitted' => $comment2->Submitted->toISOString(),
'CommentText' => $comment2->Payload,
],
],
]);
}

public function testGetCommentsForGame(): void
{
// Arrange
$system = System::factory()->create();
$game = Game::factory()->create(['ConsoleID' => $system->ID]);
$user1 = User::factory()->create();
$user2 = User::factory()->create();
$bannedUser = User::factory()->create(['banned_at' => Carbon::now()]);

$comment1 = Comment::factory()->create([
'ArticleID' => $game->ID,
'ArticleType' => 1,
'user_id' => $user1->ID,
'Payload' => 'This is a great achievement!',
]);
$comment2 = Comment::factory()->create([
'ArticleID' => $game->ID,
'ArticleType' => 1,
'user_id' => $user2->ID,
'Payload' => 'I agree, this is awesome!',
]);
$comment3 = Comment::factory()->create([
'ArticleID' => $game->ID,
'ArticleType' => 2,
'user_id' => $bannedUser->ID,
'Payload' => 'This comment is from a banned user!',
]);

// Act
$response = $this->get($this->apiUrl('GetComments', ['i' => $game->ID, 't' => 1]))
->assertSuccessful();

// Assert
$response->assertStatus(200);
$response->assertJson([
'Count' => 2,
'Total' => 2,
'Results' => [
[
'User' => $user1->User,
'Submitted' => $comment1->Submitted->toISOString(),
'CommentText' => $comment1->Payload,
],
[
'User' => $user2->User,
'Submitted' => $comment2->Submitted->toISOString(),
'CommentText' => $comment2->Payload,
],
],
]);
}

public function testGetCommentsForUser(): void
{
// Arrange
$user = User::factory()->create();
$user2 = User::factory()->create();
$bannedUser = User::factory()->create(['banned_at' => Carbon::now()]);

$comment1 = Comment::factory()->create([
'ArticleID' => $user->ID,
'ArticleType' => 3,
'user_id' => $user2->ID,
'Payload' => 'This is my first comment.',
]);
$comment2 = Comment::factory()->create([
'ArticleID' => $user->ID,
'ArticleType' => 3,
'user_id' => $user2->ID,
'Payload' => 'This is my second comment.',
]);
$comment3 = Comment::factory()->create([
'ArticleID' => $user->ID,
'ArticleType' => 2,
'user_id' => $bannedUser->ID,
'Payload' => 'This comment is from a banned user!',
]);

// Act
$response = $this->get($this->apiUrl('GetComments', ['u' => $user->User, 't' => 3]))
->assertSuccessful();

// Assert
$response->assertStatus(200);
$response->assertJson([
'Count' => 2,
'Total' => 2,
'Results' => [
[
'User' => $user2->User,
'Submitted' => $comment1->Submitted->toISOString(),
'CommentText' => $comment1->Payload,
],
[
'User' => $user2->User,
'Submitted' => $comment2->Submitted->toISOString(),
'CommentText' => $comment2->Payload,
],
],
]);
}

public function testGetCommentsForUserWithDisabledWall(): void
{
// Arrange
$user = User::factory()->create(['UserWallActive' => false]);
$user2 = User::factory()->create();
$comment1 = Comment::factory()->create([
'ArticleID' => $user->ID,
'ArticleType' => 3,
'user_id' => $user2->ID,
'Payload' => 'This is my first comment.',
]);
$comment2 = Comment::factory()->create([
'ArticleID' => $user->ID,
'ArticleType' => 3,
'user_id' => $user2->ID,
'Payload' => 'This is my second comment.',
]);

// Act
$response = $this->get($this->apiUrl('GetComments', ['u' => $user->User, 't' => 3]))
->assertSuccessful();

// Assert
$response->assertStatus(200);
$response->assertJsonStructure([]);
}
}
Loading