Make 'more ebooks' carousel in ebook detail page show ebooks from a random tag of the current ebook

This commit is contained in:
Alex Cabal 2022-04-30 13:19:02 -05:00
parent 2b32b5d4f9
commit 5985939cd5
2 changed files with 25 additions and 9 deletions

View file

@ -116,7 +116,12 @@ class Library{
* @return array<Ebook> * @return array<Ebook>
*/ */
public static function GetEbooksByTag(string $tag): array{ public static function GetEbooksByTag(string $tag): array{
return self::GetFromApcu('tag-' . $tag); try{
return apcu_fetch('tag-' . $tag) ?? [];
}
catch(Safe\Exceptions\ApcuException $ex){
return [];
}
} }
/** /**

View file

@ -42,8 +42,17 @@ try{
} }
// Generate the bottom carousel. // Generate the bottom carousel.
// Pick a random tag from this ebook, and get ebooks in the same tag
$carousel = []; $carousel = [];
$ebooks = [];
if(sizeof($ebook->Tags) > 0){
$carouselTag = $ebook->Tags[rand(0, sizeof($ebook->Tags) - 1)];
$ebooks = Library::GetEbooksByTag(strtolower($carouselTag->Name));
}
else{
$ebooks = Library::GetEbooks(); $ebooks = Library::GetEbooks();
}
shuffle($ebooks); shuffle($ebooks);
$targetCarouselSize = 5; $targetCarouselSize = 5;
@ -51,6 +60,7 @@ try{
$targetCarouselSize = sizeof($ebooks) - 1; $targetCarouselSize = sizeof($ebooks) - 1;
} }
if($targetCarouselSize > 0){
$i = 0; $i = 0;
while(sizeof($carousel) < $targetCarouselSize){ while(sizeof($carousel) < $targetCarouselSize){
if(isset($ebooks[$i]) && $ebooks[$i]->Url !== $ebook->Url){ if(isset($ebooks[$i]) && $ebooks[$i]->Url !== $ebook->Url){
@ -60,6 +70,7 @@ try{
$i++; $i++;
} }
} }
}
catch(Exceptions\SeeOtherEbookException $ex){ catch(Exceptions\SeeOtherEbookException $ex){
http_response_code(301); http_response_code(301);
header('Location: ' . $ex->Url); header('Location: ' . $ex->Url);
@ -313,7 +324,7 @@ catch(Exceptions\InvalidEbookException $ex){
<? if(sizeof($carousel) > 0){ ?> <? if(sizeof($carousel) > 0){ ?>
<aside id="more-ebooks"> <aside id="more-ebooks">
<h2>More free ebooks</h2> <h2>More free <?= strtolower($carouselTag->Name) ?> ebooks</h2>
<ul> <ul>
<? foreach($carousel as $carouselEbook){ ?> <? foreach($carousel as $carouselEbook){ ?>
<li> <li>