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 = Library::GetEbooks(); $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();
}
shuffle($ebooks); shuffle($ebooks);
$targetCarouselSize = 5; $targetCarouselSize = 5;
@ -51,13 +60,15 @@ try{
$targetCarouselSize = sizeof($ebooks) - 1; $targetCarouselSize = sizeof($ebooks) - 1;
} }
$i = 0; if($targetCarouselSize > 0){
while(sizeof($carousel) < $targetCarouselSize){ $i = 0;
if(isset($ebooks[$i]) && $ebooks[$i]->Url !== $ebook->Url){ while(sizeof($carousel) < $targetCarouselSize){
$carousel[] = $ebooks[$i]; if(isset($ebooks[$i]) && $ebooks[$i]->Url !== $ebook->Url){
} $carousel[] = $ebooks[$i];
}
$i++; $i++;
}
} }
} }
catch(Exceptions\SeeOtherEbookException $ex){ catch(Exceptions\SeeOtherEbookException $ex){
@ -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>