-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthorPopularBooksQuery.php
More file actions
85 lines (69 loc) · 2.13 KB
/
AuthorPopularBooksQuery.php
File metadata and controls
85 lines (69 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
namespace Queries;
use Author;
use Book;
use Illuminate\Database\Eloquent\Collection;
use StuDocu\CacheableEntities\Contracts\Cacheable;
use StuDocu\CacheableEntities\Contracts\SerializableCacheable;
/**
* @phpstan-type ReturnStructure Collection<int, Book>
* @phpstan-type SerializedStructure int[]
*
* @implements Cacheable<ReturnStructure>
* @implements SerializableCacheable<ReturnStructure, SerializedStructure>
*/
class AuthorPopularBooksQuery implements Cacheable, SerializableCacheable
{
public const DEFAULT_LIMIT = 8;
public function __construct(
protected readonly Author $author,
protected readonly int $limit = self::DEFAULT_LIMIT,
) {
}
public function getCacheTTL(): int
{
return 3600 * 24;
}
public function getCacheKey(): string
{
return "authors:{$this->author->id}:books:popular.v1";
}
public function get(): Collection
{
$books = Book::query()
->join('book_popularity_scores', 'book_popularity_scores.book_id', '=', 'books.id')
->where('author_id', $this->author->id)
->whereValid()
->whereHas('ratings')
->orderByDesc('document_popularity_scores.score')
->take($this->limit)
->get();
$this->setRelations($books);
return $books;
}
public function serialize(mixed $value): array
{
return $value->pluck('id')->all();
}
/**
* @param SerializedStructure $value
*/
public function unserialize(mixed $value): Collection
{
$booksFastAccess = array_flip($value);
$books = Book::query()
->findMany($value)
->sortBy(fn (Book $book) => $booksFastAccess[$book->id] ?? 999)
->values();
$this->setRelations($books);
return $books;
}
/**
* @param ReturnStructure $books
*/
private function setRelations(Collection $books): void
{
$books->each->setRelation('author', $this->author);
// Generally speaking, you can do eager loading and such in a similar fashion (for ::get and ::unserialize).
}
}