Skip to content

Commit

Permalink
Refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
VampireAotD committed Dec 18, 2024
1 parent fa0bbc1 commit 4753fc6
Show file tree
Hide file tree
Showing 15 changed files with 215 additions and 176 deletions.
40 changes: 26 additions & 14 deletions src/app/DTO/Service/Telegram/Anime/AnimeMessageDTO.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,43 @@
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardButton;
use SergiX44\Nutgram\Telegram\Types\Keyboard\InlineKeyboardMarkup;

final class AnimeMessageDTO
final readonly class AnimeMessageDTO
{
/**
* @param list<InlineKeyboardButtonDTO>|list<list<InlineKeyboardButtonDTO>> $inlineKeyboardButtons
*/
public function __construct(
public readonly string $photo,
public readonly string $caption,
/** @var InlineKeyboardButtonDTO[] */
private array $inlineKeyboardButtons = [],
public string $photo,
public string $caption,
private array $inlineKeyboardButtons = [],
) {
}

public function addButton(InlineKeyboardButtonDTO $dto): void
{
$this->inlineKeyboardButtons[] = $dto;
}

public function generateReplyMarkup(): InlineKeyboardMarkup
{
$markup = InlineKeyboardMarkup::make();

foreach ($this->inlineKeyboardButtons as $keyboardButton) {
foreach ($this->inlineKeyboardButtons as $button) {
if (is_array($button)) {
$row = [];

foreach ($button as $keyboardButton) {
$row[] = InlineKeyboardButton::make(
text : $keyboardButton->text,
url : $keyboardButton->url,
callback_data: $keyboardButton->callbackData
);
}

$markup->addRow(...$row);
continue;
}

$markup->addRow(
InlineKeyboardButton::make(
text : $keyboardButton->text,
url : $keyboardButton->url,
callback_data: $keyboardButton->callbackData
text : $button->text,
url : $button->url,
callback_data: $button->callbackData
)
);
}
Expand Down
5 changes: 0 additions & 5 deletions src/app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use Illuminate\Http\Request;
use Inertia\Middleware;
use Tighten\Ziggy\Ziggy;

class HandleInertiaRequests extends Middleware
{
Expand Down Expand Up @@ -40,10 +39,6 @@ public function share(Request $request): array
'flash' => [
'message' => fn() => $request->session()->get('message'),
],
'ziggy' => fn() => [
...(new Ziggy())->toArray(),
'location' => $request->url(),
],
];
}
}
21 changes: 0 additions & 21 deletions src/app/Models/Anime.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use Database\Factories\AnimeFactory;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
Expand Down Expand Up @@ -113,24 +112,4 @@ public function scopeCountScrapedPerMonth(Builder $query): Builder
return $query->selectRaw('COUNT(id) as per_month, MONTH(created_at) as month_number')
->groupBy('month_number');
}

/**
* @psalm-suppress TooManyTemplateParams
* @return Attribute<string, never>
*/
protected function toTelegramCaption(): Attribute
{
/** @see https://github.com/larastan/larastan/issues/2038 */
return Attribute::make(
get: fn(): string => sprintf(
"Название: %s\nСтатус: %s\nЭпизоды: %s\nОценка: %s\nОзвучки: %s\nЖанры: %s",
$this->title,
$this->status->value, // @phpstan-ignore-line Ignored because of parser issues
$this->episodes,
$this->rating,
$this->voiceActing->implode('name', ', '),
$this->genres->implode('name', ', '),
)
)->shouldCache();
}
}
63 changes: 44 additions & 19 deletions src/app/Services/Telegram/AnimeMessageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use App\Factory\Telegram\CallbackData\CallbackDataFactory;
use App\Models\Anime;
use App\Models\AnimeUrl;
use App\ValueObject\Telegram\Anime\AnimeCaptionText;
use Illuminate\Pagination\LengthAwarePaginator;

final readonly class AnimeMessageService
Expand All @@ -21,41 +22,65 @@ public function __construct(private CallbackDataFactory $callbackDataFactory)

public function createMessage(Anime $anime): AnimeMessageDTO
{
$buttons = $anime->urls->map(function (AnimeUrl $url) {
return new InlineKeyboardButtonDTO($url->domain, $url->url);
})->toArray();

return new AnimeMessageDTO($anime->image->path, $anime->to_telegram_caption, $buttons);
return new AnimeMessageDTO(
$anime->image->path,
(string) AnimeCaptionText::fromAnime($anime),
$this->generateExternalLinks($anime)
);
}

/**
* @param LengthAwarePaginator<Anime> $paginator
*/
public function createMessageWithPagination(
LengthAwarePaginator $paginator,
CallbackDataTypeEnum $queryType
): AnimeMessageDTO {
$message = $this->createMessage($paginator->first());
$anime = $paginator->first();

$buttons = [$this->generateExternalLinks($anime), $this->generatePagination($paginator, $queryType)];

return new AnimeMessageDTO(
$anime->image->path,
(string) AnimeCaptionText::fromAnime($anime),
$buttons
);
}

private function generateExternalLinks(Anime $anime): array
{
return $anime->urls->map(
static fn(AnimeUrl $url) => new InlineKeyboardButtonDTO($url->domain, $url->url)
)->toArray();
}

/**
* @param LengthAwarePaginator<Anime> $paginator
*/
private function generatePagination(
LengthAwarePaginator $paginator,
CallbackDataTypeEnum $queryType
): array {
$pagination = [];

if ($paginator->previousPageUrl()) {
$message->addButton(
new InlineKeyboardButtonDTO(
text : '<',
callbackData: $this->callbackDataFactory->resolve(
new PaginationCallbackDataDTO($paginator->currentPage() - 1, $queryType)
),
$pagination[] = new InlineKeyboardButtonDTO(
text : '<',
callbackData: $this->callbackDataFactory->resolve(
new PaginationCallbackDataDTO($paginator->currentPage() - 1, $queryType)
)
);
}

if ($paginator->hasMorePages()) {
$message->addButton(
new InlineKeyboardButtonDTO(
text : '>',
callbackData: $this->callbackDataFactory->resolve(
new PaginationCallbackDataDTO($paginator->currentPage() + 1, $queryType)
),
$pagination[] = new InlineKeyboardButtonDTO(
text : '>',
callbackData: $this->callbackDataFactory->resolve(
new PaginationCallbackDataDTO($paginator->currentPage() + 1, $queryType)
)
);
}

return $message;
return $pagination;
}
}
2 changes: 2 additions & 0 deletions src/app/Telegram/Commands/AnimeListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ public function handle(Nutgram $bot, AnimeMessageUseCase $animeMessageUseCase):
'exception_message' => $exception->getMessage(),
'exception_trace' => $exception->getTraceAsString(),
]);

$bot->sendMessage(text: __('telegram.callbacks.anime_list.render_error'));
}
}
}
34 changes: 34 additions & 0 deletions src/app/ValueObject/Telegram/Anime/AnimeCaptionText.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App\ValueObject\Telegram\Anime;

use App\Models\Anime;

final readonly class AnimeCaptionText implements \Stringable
{
public function __construct(public Anime $anime)
{
}

public static function fromAnime(Anime $anime): self
{
return new self($anime);
}

/**
* @return string
*/
public function __toString(): string
{
return __('telegram.captions.anime', [
'title' => $this->anime->title,
'status' => $this->anime->status->value, // @phpstan-ignore-line Ignored because of parser issues
'episodes' => $this->anime->episodes,
'rating' => $this->anime->rating,
'voiceacting' => $this->anime->voiceActing->implode('name', ', '),
'genres' => $this->anime->genres->implode('name', ', '),
]);
}
}
3 changes: 3 additions & 0 deletions src/lang/en/telegram.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,7 @@
],
],

'captions' => [
'anime' => "Title: :title\nStatus: :status\nEpisodes: :episodes\nRating: :rating\nVoice Acting: :voiceacting\nGenres: :genres",
],
];
4 changes: 2 additions & 2 deletions src/tests/Concerns/Fake/CanCreateFakeAnime.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ protected function createAnimeWithRelations(array $data = []): Anime
}

/**
* @return Collection<Anime>
* @return Collection<int, Anime>
*/
protected function createAnimeCollection(int $quantity = 1): Collection
{
return Anime::factory(count: $quantity)->createManyQuietly();
}

/**
* @return Collection<Anime>
* @return Collection<int, Anime>
*/
protected function createAnimeCollectionWithRelations(int $quantity = 1): Collection
{
Expand Down
Loading

0 comments on commit 4753fc6

Please sign in to comment.