- trop de trucs d'un coup... je vais faire attention ensuite ^^'

This commit is contained in:
Jérémy Guillot
2024-06-10 13:57:50 +02:00
parent 9595831aa3
commit c46e1a0a5c
69 changed files with 4004 additions and 385 deletions

View File

@@ -0,0 +1,86 @@
<?php
namespace App\Client;
use App\Interface\ClientInterface;
use GuzzleHttp\ClientInterface as GuzzleInterface;
class MangadexClient implements ClientInterface
{
private CONST AUTHENTICATION_URL = 'https://auth.mangadex.org/realms/mangadex/protocol/openid-connect/token';
private CONST API_URL = 'https://api.mangadex.org';
private GuzzleInterface $httpClient;
private string $clientId;
private string $clientSecret;
private string $username;
private string $password;
private ?string $accessToken = null;
private ?string $refreshToken = null;
public function __construct(GuzzleInterface $httpClient, string $clientId, string $clientSecret, string $username, string $password)
{
$this->httpClient = $httpClient;
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->username = $username;
$this->password = $password;
$this->authenticate();
}
public function authenticate(): void
{
$response = $this->httpClient->request('POST', self::AUTHENTICATION_URL, [
'form_params' => [
'grant_type' => 'password',
'username' => $this->username,
'password' => $this->password,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
],
]);
$data = json_decode($response->getBody()->getContents(), true);
$this->accessToken = $data['access_token'];
$this->refreshToken = $data['refresh_token'];
}
public function refresh(): void
{
$response = $this->httpClient->request('POST', self::AUTHENTICATION_URL, [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $this->refreshToken,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
],
]);
$data = json_decode($response->getBody()->getContents(), true);
$this->accessToken = $data['access_token'];
}
private function request(string $method, string $endpoint, array $options = []): array
{
$options['headers']['Authorization'] = 'Bearer ' . $this->accessToken;
$response = $this->httpClient->request($method, self::API_URL . $endpoint, $options);
if ($response->getStatusCode() === 429) {
$this->refresh();
$options['headers']['Authorization'] = 'Bearer ' . $this->accessToken;
$response = $this->httpClient->request($method, self::API_URL . $endpoint, $options);
}
return json_decode($response->getBody()->getContents(), true);
}
public function get(string $endpoint, array $params = []): array
{
return $this->request('GET', $endpoint, ['query' => $params]);
}
public function post(string $endpoint, array $data): array
{
return $this->request('POST', $endpoint, ['json' => $data]);
}
}

View File

@@ -6,8 +6,8 @@ use App\Entity\Manga;
use App\Repository\MangaRepository;
use App\Service\MangaExportService;
use App\Service\LelScansProviderService;
use App\Service\MangaScraperService;
use App\Service\MangaUpdatesDbProvider;
use App\Service\MangaScraperServiceOld;
use App\Service\MangaUpdatesMetadataProvider;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
@@ -20,11 +20,11 @@ use Symfony\Component\String\Slugger\AsciiSlugger;
class MangaController extends AbstractController
{
public function __construct(
private readonly MangaScraperService $mangaScraperService,
private readonly MangaScraperServiceOld $mangaScraperService,
private readonly MangaExportService $mangaExportService,
private readonly LelScansProviderService $mangaProviderService,
private readonly MangaRepository $mangaRepository,
private MangaUpdatesDbProvider $mangaUpdatesDbProvider
private MangaUpdatesMetadataProvider $mangaUpdatesDbProvider
)
{
}
@@ -48,12 +48,17 @@ class MangaController extends AbstractController
throw new NotFoundHttpException("Le manga demandé n'existe pas.");
}
$availableChapters = $this->mangaProviderService->getChapterList($mangaSlug);
$chaptersByVolume = [];
foreach ($manga->getChapters() as $chapter) {
$volume = $chapter->getVolume() ?? 'Not Found';
$chaptersByVolume[$volume][] = $chapter;
}
$chaptersByVolume = array_map('array_reverse', array_reverse($chaptersByVolume, true));
return $this->render('manga/show_chapters.html.twig', [
'controller_name' => 'MangaController',
'chapters_by_volume' => $chaptersByVolume,
'manga' => $manga,
'availableChapters' => $availableChapters,
]);
}
@@ -83,19 +88,11 @@ class MangaController extends AbstractController
]);
}
#[Route('/addNew', name: 'add_new_manga')]
public function addNew(): Response
#[Route('/addNew/{query}', name: 'add_new_manga')]
public function addNew(string $query = ''): Response
{
$availableManga = $this->mangaProviderService->getMangaList();
foreach ($availableManga as $key => $manga) {
$availableManga[$key]['slug'] = $this->titleToSlug($manga['name']);
}
$mangas = $this->mangaRepository->findAll();
return $this->render('manga/add_new.html.twig', [
'availableManga' => $availableManga,
'mangas' => $mangas,
'query' => $query,
]);
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Controller;
use App\Entity\Chapter;
use App\Entity\ContentSource;
use App\Entity\Manga;
use App\Repository\MangaRepository;
use App\Service\MangadexProvider;
use App\Service\MangaScraperService;
use App\Service\MangaUpdatesMetadataProvider;
use App\Service\SushiScanProviderService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController extends AbstractController
{
public function __construct(private MangadexProvider $mangadexProvider, private MangaRepository $mangaRepository)
{
}
#[Route('/test', name: 'test')]
public function test(): Response
{
$manga = $this->mangaRepository->find(8);
dd($this->mangadexProvider->getFeed($manga));
}
}

View File

@@ -28,6 +28,15 @@ class Chapter
#[ORM\OneToMany(mappedBy: 'chapter', targetEntity: Page::class, orphanRemoval: true)]
private Collection $pagesLink;
#[ORM\Column(nullable: true)]
private ?int $volume = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $title = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $localPath = null;
public function __construct()
{
$this->pagesLink = new ArrayCollection();
@@ -105,16 +114,52 @@ class Chapter
}
public function getPageByNumber(int $number): ?Page
{
/**
* @var Page $page
*/
foreach ($this->pagesLink as $page) {
if ($page->getNumber() === $number) {
return $page;
}
}
{
/**
* @var Page $page
*/
foreach ($this->pagesLink as $page) {
if ($page->getNumber() === $number) {
return $page;
}
}
return null;
}
return null;
}
public function getVolume(): ?int
{
return $this->volume;
}
public function setVolume(?int $volume): static
{
$this->volume = $volume;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $title): static
{
$this->title = $title;
return $this;
}
public function getLocalPath(): ?string
{
return $this->localPath;
}
public function setLocalPath(?string $localPath): static
{
$this->localPath = $localPath;
return $this;
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace App\Entity;
use App\Repository\ContentSourceRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ContentSourceRepository::class)]
class ContentSource
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $baseUrl = null;
#[ORM\Column(length: 255)]
private ?string $imageSelector = null;
#[ORM\Column(length: 255)]
private ?string $NextPageSelector = null;
#[ORM\Column(length: 255)]
private ?string $chapterUrlFormat = null;
#[ORM\Column(length: 255)]
private ?string $scrapingType = null;
public function getId(): ?int
{
return $this->id;
}
public function getBaseUrl(): ?string
{
return $this->baseUrl;
}
public function setBaseUrl(string $baseUrl): static
{
$this->baseUrl = $baseUrl;
return $this;
}
public function getImageSelector(): ?string
{
return $this->imageSelector;
}
public function setImageSelector(string $imageSelector): static
{
$this->imageSelector = $imageSelector;
return $this;
}
public function getNextPageSelector(): ?string
{
return $this->NextPageSelector;
}
public function setNextPageSelector(string $NextPageSelector): static
{
$this->NextPageSelector = $NextPageSelector;
return $this;
}
public function getChapterUrlFormat(): ?string
{
return $this->chapterUrlFormat;
}
public function setChapterUrlFormat(string $chapterUrlFormat): static
{
$this->chapterUrlFormat = $chapterUrlFormat;
return $this;
}
public function getChapterUrl(string $mangaTitle, float $chapterNumber): string
{
return sprintf($this->chapterUrlFormat, $mangaTitle, $chapterNumber);
}
public function getScrapingType(): ?string
{
return $this->scrapingType;
}
public function setScrapingType(string $scrapingType): static
{
$this->scrapingType = $scrapingType;
return $this;
}
}

View File

@@ -22,7 +22,7 @@ class Manga
#[ORM\OneToMany(mappedBy: 'manga', targetEntity: Chapter::class, orphanRemoval: true)]
private Collection $chapters;
#[ORM\Column(length: 255)]
#[ORM\Column(length: 255, unique: true)]
private ?string $slug = null;
#[ORM\Column(length: 255, nullable: true)]
@@ -37,9 +37,25 @@ class Manga
#[ORM\Column(type: Types::ARRAY, nullable: true)]
private ?array $genres = null;
#[ORM\Column]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column(nullable: true)]
private ?float $rating = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $author = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $externalId = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $status = null;
public function __construct()
{
$this->chapters = new ArrayCollection();
$this->createdAt = new \DateTimeImmutable();
}
public function getId(): ?int
@@ -67,15 +83,15 @@ class Manga
return $this->chapters;
}
public function getChapterByNumber(float $number): ?Chapter
{
foreach ($this->chapters as $chapter) {
if ($chapter->getNumber() === $number) {
return $chapter;
}
}
return null;
}
public function getChapterByNumber(float $number): ?Chapter
{
foreach ($this->chapters as $chapter) {
if ($chapter->getNumber() === $number) {
return $chapter;
}
}
return null;
}
public function addChapter(Chapter $chapter): self
{
@@ -158,4 +174,64 @@ class Manga
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): static
{
$this->createdAt = $createdAt;
return $this;
}
public function getRating(): ?float
{
return $this->rating;
}
public function setRating(?float $rating): static
{
$this->rating = $rating;
return $this;
}
public function getAuthor(): ?string
{
return $this->author;
}
public function setAuthor(?string $author): static
{
$this->author = $author;
return $this;
}
public function getExternalId(): ?string
{
return $this->externalId;
}
public function setExternalId(?string $externalId): static
{
$this->externalId = $externalId;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(?string $status): static
{
$this->status = $status;
return $this;
}
}

View File

@@ -21,24 +21,24 @@ class ExceptionListener
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$response = match(true) {
$exception instanceof FilterValidationException,
$exception instanceof BadRequestException => $this->createResponse($exception, Response::HTTP_BAD_REQUEST),
$exception instanceof NotFoundHttpException,
$exception instanceof ItemNotFoundException => $this->createResponse($exception, Response::HTTP_NOT_FOUND),
$exception instanceof AccessDeniedHttpException => $this->createResponse($exception, Response::HTTP_FORBIDDEN),
$exception instanceof ValidationException,
$exception instanceof NotNormalizableValueException => $this->createResponse($exception, Response::HTTP_UNPROCESSABLE_ENTITY),
default => null,
};
if ($response) {
$event->setResponse($response);
}else{
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
}
// $exception = $event->getThrowable();
//
// $response = match(true) {
// $exception instanceof FilterValidationException,
// $exception instanceof BadRequestException => $this->createResponse($exception, Response::HTTP_BAD_REQUEST),
// $exception instanceof NotFoundHttpException,
// $exception instanceof ItemNotFoundException => $this->createResponse($exception, Response::HTTP_NOT_FOUND),
// $exception instanceof AccessDeniedHttpException => $this->createResponse($exception, Response::HTTP_FORBIDDEN),
// $exception instanceof ValidationException,
// $exception instanceof NotNormalizableValueException => $this->createResponse($exception, Response::HTTP_UNPROCESSABLE_ENTITY),
// default => null,
// };
//
// if ($response) {
// $event->setResponse($response);
// }else{
// $this->logger->error($exception->getMessage(), ['exception' => $exception]);
// }
}
private function createResponse(\Throwable $exception, int $statusCode): Response

View File

@@ -52,6 +52,10 @@ final class MangaFactory extends ModelFactory
return [
'slug' => $this->slugger->slug($title)->lower(),
'title' => $title,
'description' => self::faker()->text(),
'genres' => self::faker()->words(rand(1, 5)),
'publicationYear' => self::faker()->year(),
'rating' => self::faker()->randomFloat(1, 0, 10),
];
}

View File

@@ -48,8 +48,8 @@ final class PageFactory extends ModelFactory
{
return [
'chapter' => ChapterFactory::new(),
'imageLocalUrl' => self::faker()->text(255),
'imageUrl' => self::faker()->text(255),
'imageLocalUrl' => 'https://placehold.co/770x1090',
'imageUrl' => 'https://placehold.co/770x1090',
'number' => self::faker()->randomNumber(2),
];
}

View File

@@ -0,0 +1,9 @@
<?php
namespace App\Interface;
interface ClientInterface
{
public function get(string $endpoint, array $params = []): array;
public function post(string $endpoint, array $data): array;
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Interface;
use App\Entity\Manga;
interface ContentProviderInterface
{
public function getAvailableContent(Manga $manga): array;
public function getContent(Manga $manga): array;
}

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Service;
namespace App\Interface;
use Doctrine\Common\Collections\Collection;
interface MangaDbProviderInterface
interface MetadataProviderInterface
{
public function search(string $title): Collection;
}

View File

@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\ContentSource;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ContentSource>
*
* @method ContentSource|null find($id, $lockMode = null, $lockVersion = null)
* @method ContentSource|null findOneBy(array $criteria, array $orderBy = null)
* @method ContentSource[] findAll()
* @method ContentSource[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ContentSourceRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ContentSource::class);
}
// /**
// * @return ContentSource[] Returns an array of ContentSource objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('c')
// ->andWhere('c.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('c.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?ContentSource
// {
// return $this->createQueryBuilder('c')
// ->andWhere('c.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -39,6 +39,15 @@ class MangaRepository extends ServiceEntityRepository
}
}
public function findByTitle(string $title): array
{
return $this->createQueryBuilder('m')
->andWhere('m.title LIKE :title')
->setParameter('title', "%$title%")
->getQuery()
->getResult();
}
// /**
// * @return Manga[] Returns an array of Manga objects
// */

View File

@@ -1,10 +1,12 @@
<?php
namespace App\Service;
use App\Entity\Manga;
use App\Interface\ContentProviderInterface;
use Symfony\Component\BrowserKit\HttpBrowser as Client;
use Symfony\Component\DomCrawler\Crawler;
class LelScansProviderService implements MangaProviderInterface
class LelScansProviderService implements ContentProviderInterface
{
const PROVIDER_URL = 'https://lelscans.net/';
const MANGA_SLUG = '/{manga}/{chapter}/{page}';
@@ -53,4 +55,13 @@ class LelScansProviderService implements MangaProviderInterface
return $chapterList;
}
#[\Override] public function getAvailableContent(Manga $manga): array
{
// TODO: Implement getAvailableContent() method.
}
#[\Override] public function getContent(Manga $manga): array
{
// TODO: Implement getContent() method.
}
}

View File

@@ -2,9 +2,11 @@
namespace App\Service;
use App\Interface\ContentProviderInterface;
class MangaProviderFactory
{
public static function create($providerName): MangaProviderInterface
public static function create($providerName): ContentProviderInterface
{
return match ($providerName) {
'LelScans' => new LelScansProviderService(),
@@ -12,4 +14,4 @@ class MangaProviderFactory
default => throw new \Exception("Provider {$providerName} non supporté."),
};
}
}
}

View File

@@ -1,9 +0,0 @@
<?php
namespace App\Service;
interface MangaProviderInterface
{
public function getMangaList(): array;
public function getChapterList(string $mangaSlug): array;
}

View File

@@ -2,6 +2,9 @@
namespace App\Service;
use App\Entity\Chapter;
use App\Entity\Manga;
use App\Entity\ContentSource;
use App\EventSubscriber\MangaScrapedEvent;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
@@ -14,144 +17,256 @@ use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class MangaScraperService
{
const string IMG_BASE_DIR = '/public/manga-images';
private string $projectDir;
private EventDispatcherInterface $eventDispatcher;
const IMG_BASE_DIR = '/public/manga-images';
private string $projectDir;
private EventDispatcherInterface $eventDispatcher;
public function __construct($projectDir, EventDispatcherInterface $eventDispatcher)
{
$this->projectDir = $projectDir;
$this->eventDispatcher = $eventDispatcher;
}
public function __construct($projectDir, EventDispatcherInterface $eventDispatcher)
{
$this->projectDir = $projectDir;
$this->eventDispatcher = $eventDispatcher;
}
public function extractMangaPageData(string $html): array
{
$baseUrl = 'https://lelscans.net';
//pour éviter à PhpStorm de gueuler...
$selector = 'img';
$crawler = new Crawler($html);
$imgUrl = $crawler->filter($selector)->attr('src');
$nextLink = $crawler->filter('a[title="Suivant"]');
public function extractMangaPageData(string $html, ContentSource $mangaSource): array
{
$crawler = new Crawler($html);
$imgUrls = [];
if (!preg_match('/^https?:\/\//', $imgUrl)) {
$urlComponents = parse_url($baseUrl);
$scheme = $urlComponents['scheme'];
$host = $urlComponents['host'];
// Search for images with different extensions
foreach (['img[src$=".jpg"]', 'img[src$=".jpeg"]', 'img[src$=".png"]', 'img'] as $selector) {
$crawler->filter($selector)->each(function (Crawler $node) use (&$imgUrls) {
$src = $node->attr('src') ?? $node->attr('data-src');
if ($src) {
$imgUrls[] = $src;
}
});
}
// Construit l'URL absolue de l'image
$imgUrl = $scheme . '://' . $host . '/' . ltrim($imgUrl, '/');
}
if (empty($imgUrls)) {
throw new \Exception('No valid image found on the page.');
}
if($nextLink->count() > 0){
$nextUrl = $nextLink->attr('href');
}else{
$nextUrl = null;
}
$nextLink = $crawler->filter($mangaSource->getNextPageSelector());
$nextUrl = $nextLink->count() > 0 ? $nextLink->attr('href') : null;
return [
'image_url' => $imgUrl,
'next_page_url' => $nextUrl,
];
}
// Convert relative URLs to absolute URLs
$baseUrl = $mangaSource->getBaseUrl();
$imgUrls = array_map(function ($imgUrl) use ($baseUrl) {
if (!preg_match('/^https?:\/\//', $imgUrl)) {
$urlComponents = parse_url($baseUrl);
$scheme = $urlComponents['scheme'];
$host = $urlComponents['host'];
$imgUrl = $scheme . '://' . $host . '/' . ltrim($imgUrl, '/');
}
return $imgUrl;
}, $imgUrls);
return [
'image_urls' => $imgUrls,
'next_page_url' => $nextUrl,
];
}
/**
* @throws GuzzleException
*/
public function scrapeMangaChapter(string $chapterUrl, string $mangaTitle, float $chapterNumber): array|bool
{
if(!$this->isChapterAvailable($chapterUrl, $chapterNumber)){
return false;
}
public function scrapeManga(Manga $manga, ContentSource $mangaSource): array
{
$allChaptersData = [];
$pageData = [];
$currentPageUrl = $chapterUrl;
foreach ($manga->getChapters() as $chapter) {
$chapterData = $this->scrapeChapter($manga, $chapter, $mangaSource);
if ($chapterData !== false) {
$allChaptersData[$chapter->getNumber()] = $chapterData;
}
}
$mangaDir = sprintf('%s/%s', $this->projectDir . self::IMG_BASE_DIR, $mangaTitle);
if (!is_dir($mangaDir)) {
mkdir($mangaDir, 0755, true);
}
return $allChaptersData;
}
// Créez le dossier du chapitre s'il n'existe pas
$chapterDir = sprintf('%s/%s', $mangaDir, $chapterNumber);
if (!is_dir($chapterDir)) {
mkdir($chapterDir, 0755, true);
}
private function scrapeChapter(Manga $manga, Chapter $chapter, ContentSource $mangaSource): array|bool
{
switch ($mangaSource->getScrapingType()) {
case 'html':
return $this->scrapeChapterHtml($manga, $chapter, $mangaSource);
case 'javascript':
return $this->scrapeChapterJavaScript($manga, $chapter, $mangaSource);
// case 'api':
// // Implémentez la méthode de scraping par API si nécessaire
// return $this->scrapeChapterApi($manga, $chapter, $mangaSource);
default:
throw new \Exception('Unsupported scraping type: ' . $mangaSource->getScrapingType());
}
}
do {
$html = $this->fetchHtml($currentPageUrl);
$page = $this->extractMangaPageData($html);
$pageData[] = $page;
$currentPageUrl = $page['next_page_url'];
// private function scrapeChapterHtml(Manga $manga, Chapter $chapter, MangaSource $mangaSource): array|bool
// {
// $chapterUrl = $mangaSource->getChapterUrl($manga->getTitle(), $chapter->getChapterNumber());
// $html = $this->fetchHtml($chapterUrl);
// $imgUrls = $this->extractMangaPageData($html);
//
// return $this->saveChapterImages($manga, $chapter, $imgUrls);
// }
// Construisez le nom de fichier de l'image
$imageName = sprintf('%03d.jpg', count($pageData));
private function scrapeChapterJavaScript(Manga $manga, Chapter $chapter, ContentSource $mangaSource): array|bool
{
$chapterUrl = $mangaSource->getChapterUrl($manga->getTitle(), $chapter->getNumber());
$imgUrls = $this->fetchImagesUsingPuppeteer($chapterUrl, $mangaSource->getImageSelector(), $mangaSource->getNextPageSelector());
// Construisez le chemin du fichier de l'image
$imagePath = sprintf('%s/%s', $chapterDir, $imageName);
return $this->saveChapterImages($manga, $chapter, $imgUrls);
}
// Téléchargez et enregistrez l'image
$this->downloadAndSaveImage($page['image_url'], $imagePath);
private function fetchImagesUsingPuppeteer(string $url, string $imageSelector, string $nextButtonSelector): array
{
// Appeler le script Puppeteer avec les paramètres nécessaires
$output = [];
$command = sprintf('node puppeteer-script.js "%s" "%s" "%s" 2>&1', $url, $imageSelector, $nextButtonSelector); // Redirect stderr to stdout
dump($command);
// exec($command, $output, $return_var);
// Modifiez les données de la page pour inclure l'URL de l'image stockée localement
$pageData[count($pageData) - 1]['local_image_url'] = sprintf('/manga-images/%s/%s/%s', $mangaTitle, $chapterNumber, $imageName);
$pageData[count($pageData) - 1]['page_number'] = count($pageData);
dd($command, $output);
} while ($currentPageUrl);
// Convertir la sortie JSON en tableau PHP
return json_decode(implode("", $output), true);
}
$event = new MangaScrapedEvent($mangaTitle, $chapterNumber, $pageData);
$this->eventDispatcher->dispatch($event, MangaScrapedEvent::NAME);
/**
* @throws GuzzleException
*/
private function scrapeChapterHtml(Manga $manga, Chapter $chapter, ContentSource $mangaSource): array|bool
{
$chapterUrl = $mangaSource->getChapterUrl($manga->getSlug(), $chapter->getNumber());
return $pageData;
}
$pageData = [];
$currentPageUrl = $chapterUrl;
$mangaTitle = $manga->getTitle();
$chapterNumber = $chapter->getNumber();
$mangaDir = sprintf('%s/%s', $this->projectDir . self::IMG_BASE_DIR, $mangaTitle);
if (!is_dir($mangaDir)) {
mkdir($mangaDir, 0755, true);
}
$chapterDir = sprintf('%s/%s', $mangaDir, $chapterNumber);
if (!is_dir($chapterDir)) {
mkdir($chapterDir, 0755, true);
}
do {
$html = $this->fetchHtml($currentPageUrl);
$page = $this->extractMangaPageData($html, $mangaSource);
foreach ($page['image_urls'] as $imgUrl) {
dump($imgUrl);
dump(base64_decode($imgUrl));
// Déterminer l'extension de l'image
$imageExtension = pathinfo(parse_url($imgUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
// Construire le nom de fichier de l'image
$imageName = sprintf('%03d.%s', count($pageData) + 1, $imageExtension);
$imagePath = sprintf('%s/%s', $chapterDir, $imageName);
$this->downloadAndSaveImage($imgUrl, $imagePath);
$pageData[] = [
'image_url' => $imgUrl,
'local_image_url' => sprintf('/manga-images/%s/%s/%s', $mangaTitle, $chapterNumber, $imageName),
'page_number' => count($pageData) + 1,
];
}
// Si plus d'une image a été trouvée, ne pas chercher la page suivante
if (count($page['image_urls']) > 1) {
break;
}
$currentPageUrl = $page['next_page_url'];
} while ($currentPageUrl);
$event = new MangaScrapedEvent($mangaTitle, $chapterNumber, $pageData);
$this->eventDispatcher->dispatch($event, MangaScrapedEvent::NAME);
return $pageData;
}
/**
* @throws GuzzleException
*/
private function fetchHtml(string $url): string
{
$client = new Client();
$response = $client->get($url);
{
$client = new Client();
$response = $client->get($url);
return (string) $response->getBody();
}
return (string)$response->getBody();
}
/**
* @throws GuzzleException
*/
private function downloadAndSaveImage(string $imageUrl, string $destinationPath): void
{
$client = new Client();
$response = $client->get($imageUrl);
{
$client = new Client();
$response = $client->get($imageUrl);
file_put_contents($destinationPath, $response->getBody()->getContents());
}
file_put_contents($destinationPath, $response->getBody()->getContents());
}
private function saveChapterImages(Manga $manga, Chapter $chapter, array $imgUrls): array
{
$mangaTitle = $manga->getTitle();
$chapterNumber = $chapter->getNumber();
$mangaDir = sprintf('%s/%s', $this->projectDir . self::IMG_BASE_DIR, $mangaTitle);
if (!is_dir($mangaDir)) {
mkdir($mangaDir, 0755, true);
}
$chapterDir = sprintf('%s/%s', $mangaDir, $chapterNumber);
if (!is_dir($chapterDir)) {
mkdir($chapterDir, 0755, true);
}
$pageData = [];
foreach ($imgUrls as $index => $imgUrl) {
$imageName = sprintf('%03d.%s', $index + 1, pathinfo(parse_url($imgUrl, PHP_URL_PATH), PATHINFO_EXTENSION));
$imagePath = sprintf('%s/%s', $chapterDir, $imageName);
$this->downloadAndSaveImage($imgUrl, $imagePath);
$pageData[] = [
'image_url' => $imgUrl,
'local_image_url' => sprintf('/manga-images/%s/%s/%s', $mangaTitle, $chapterNumber, $imageName),
'page_number' => $index + 1,
];
}
$event = new MangaScrapedEvent($mangaTitle, $chapterNumber, $pageData);
$this->eventDispatcher->dispatch($event, MangaScrapedEvent::NAME);
return $pageData;
}
/**
* @throws GuzzleException
*/
private function isChapterAvailable(string $chapterUrl, float $chapterNumber): bool
{
$html = $this->fetchHtml($chapterUrl);
$crawler = new Crawler($html);
$nextLink = $crawler->filter('a[title="Suivant"]');
private function isChapterAvailable(string $chapterUrl, float $chapterNumber, ContentSource $mangaSource): bool
{
$html = $this->fetchHtml($chapterUrl);
$crawler = new Crawler($html);
$nextLink = $crawler->filter($mangaSource->getNextPageSelector());
if($nextLink->count() === 0){
return false;
}else{
$nextUrl = $nextLink->attr('href');
}
if ($nextLink->count() === 0) {
return false;
}
$routeCollection = new RouteCollection();
$routeCollection->add('manga_chapter', new Route('/scan-{manga}/{chapter}/{page}'));
$context = new RequestContext('/');
$matcher = new UrlMatcher($routeCollection, $context);
$path = parse_url($nextUrl, PHP_URL_PATH);
$parameters = $matcher->match($path);
$nextUrl = $nextLink->attr('href');
$routeCollection = new RouteCollection();
$routeCollection->add('manga_chapter', new Route('/scan-{manga}/{chapter}/{page}'));
$context = new RequestContext('/');
$matcher = new UrlMatcher($routeCollection, $context);
$path = parse_url($nextUrl, PHP_URL_PATH);
$parameters = $matcher->match($path);
if((float) $parameters['chapter'] !== $chapterNumber){
return false;
}
return true;
}
return (float)$parameters['chapter'] === $chapterNumber;
}
}

View File

@@ -0,0 +1,157 @@
<?php
namespace App\Service;
use App\EventSubscriber\MangaScrapedEvent;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class MangaScraperServiceOld
{
const string IMG_BASE_DIR = '/public/manga-images';
private string $projectDir;
private EventDispatcherInterface $eventDispatcher;
public function __construct($projectDir, EventDispatcherInterface $eventDispatcher)
{
$this->projectDir = $projectDir;
$this->eventDispatcher = $eventDispatcher;
}
public function extractMangaPageData(string $html): array
{
$baseUrl = 'https://lelscans.net';
//pour éviter à PhpStorm de gueuler...
$selector = 'img';
$crawler = new Crawler($html);
$imgUrl = $crawler->filter($selector)->attr('src');
$nextLink = $crawler->filter('a[title="Suivant"]');
if (!preg_match('/^https?:\/\//', $imgUrl)) {
$urlComponents = parse_url($baseUrl);
$scheme = $urlComponents['scheme'];
$host = $urlComponents['host'];
// Construit l'URL absolue de l'image
$imgUrl = $scheme . '://' . $host . '/' . ltrim($imgUrl, '/');
}
if($nextLink->count() > 0){
$nextUrl = $nextLink->attr('href');
}else{
$nextUrl = null;
}
return [
'image_url' => $imgUrl,
'next_page_url' => $nextUrl,
];
}
/**
* @throws GuzzleException
*/
public function scrapeMangaChapter(string $chapterUrl, string $mangaTitle, float $chapterNumber): array|bool
{
if(!$this->isChapterAvailable($chapterUrl, $chapterNumber)){
return false;
}
$pageData = [];
$currentPageUrl = $chapterUrl;
$mangaDir = sprintf('%s/%s', $this->projectDir . self::IMG_BASE_DIR, $mangaTitle);
if (!is_dir($mangaDir)) {
mkdir($mangaDir, 0755, true);
}
// Créez le dossier du chapitre s'il n'existe pas
$chapterDir = sprintf('%s/%s', $mangaDir, $chapterNumber);
if (!is_dir($chapterDir)) {
mkdir($chapterDir, 0755, true);
}
do {
$html = $this->fetchHtml($currentPageUrl);
$page = $this->extractMangaPageData($html);
$pageData[] = $page;
$currentPageUrl = $page['next_page_url'];
// Construisez le nom de fichier de l'image
$imageName = sprintf('%03d.jpg', count($pageData));
// Construisez le chemin du fichier de l'image
$imagePath = sprintf('%s/%s', $chapterDir, $imageName);
// Téléchargez et enregistrez l'image
$this->downloadAndSaveImage($page['image_url'], $imagePath);
// Modifiez les données de la page pour inclure l'URL de l'image stockée localement
$pageData[count($pageData) - 1]['local_image_url'] = sprintf('/manga-images/%s/%s/%s', $mangaTitle, $chapterNumber, $imageName);
$pageData[count($pageData) - 1]['page_number'] = count($pageData);
} while ($currentPageUrl);
$event = new MangaScrapedEvent($mangaTitle, $chapterNumber, $pageData);
$this->eventDispatcher->dispatch($event, MangaScrapedEvent::NAME);
return $pageData;
}
/**
* @throws GuzzleException
*/
private function fetchHtml(string $url): string
{
$client = new Client();
$response = $client->get($url);
return (string) $response->getBody();
}
/**
* @throws GuzzleException
*/
private function downloadAndSaveImage(string $imageUrl, string $destinationPath): void
{
$client = new Client();
$response = $client->get($imageUrl);
file_put_contents($destinationPath, $response->getBody()->getContents());
}
/**
* @throws GuzzleException
*/
private function isChapterAvailable(string $chapterUrl, float $chapterNumber): bool
{
$html = $this->fetchHtml($chapterUrl);
$crawler = new Crawler($html);
$nextLink = $crawler->filter('a[title="Suivant"]');
if($nextLink->count() === 0){
return false;
}else{
$nextUrl = $nextLink->attr('href');
}
$routeCollection = new RouteCollection();
$routeCollection->add('manga_chapter', new Route('/scan-{manga}/{chapter}/{page}'));
$context = new RequestContext('/');
$matcher = new UrlMatcher($routeCollection, $context);
$path = parse_url($nextUrl, PHP_URL_PATH);
$parameters = $matcher->match($path);
if((float) $parameters['chapter'] !== $chapterNumber){
return false;
}
return true;
}
}

View File

@@ -3,20 +3,19 @@
namespace App\Service;
use App\Entity\Manga;
use App\Interface\MetadataProviderInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class MangaUpdatesDbProvider implements MangaDbProviderInterface
class MangaUpdatesMetadataProvider implements MetadataProviderInterface
{
private Client $client;
public function __construct(private SluggerInterface $slugger)
public function __construct(private readonly SluggerInterface $slugger)
{
$this->client = new Client();
}
@@ -40,6 +39,9 @@ class MangaUpdatesDbProvider implements MangaDbProviderInterface
$results = $this->client->request('POST', 'https://api.mangaupdates.com/v1/series/search', [
'json' => [
'search' => $title,
'licensed' => 'yes',
'type' => ['Manga'],
'exclude_genre' => ['Doujinshi', 'Adult', 'Hentai', 'Ecchi', 'Yaoi', 'Yuri', 'Josei', 'Smut', 'Gender Bender'],
'orderby' => 'score',
]
])->withHeader('Authorization', 'Bearer ' . $jwt)
@@ -50,13 +52,21 @@ class MangaUpdatesDbProvider implements MangaDbProviderInterface
$mangas = [];
foreach (json_decode($results, true)['results'] as $record) {
$record = $record['record'];
$genres = [];
foreach ($record['genres'] as $genre) {
$genres[] = $genre['genre'];
}
$mangas[] = (new Manga())
->setTitle($record['title'])
->setSlug($this->slugger->slug($record['title'])->lower())
->setDescription($record['description'])
->setImageUrl($record['image']['url']['original'])
->setGenres($record['genres'])
->setPublicationYear((int)$record['year']);
->setGenres($genres)
->setPublicationYear((int)$record['year'])
->setRating((float)$record['bayesian_rating'])
;
}
return new ArrayCollection($mangas);

View File

@@ -0,0 +1,123 @@
<?php
namespace App\Service;
use App\Entity\Chapter;
use App\Entity\Manga;
use App\Interface\ClientInterface;
use App\Interface\MetadataProviderInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\String\Slugger\SluggerInterface;
readonly class MangadexProvider implements MetadataProviderInterface
{
public function __construct(private ClientInterface $client, private SluggerInterface $slugger)
{
}
public function search(?string $title): Collection
{
if($title === null) {
return new ArrayCollection();
}
$results = $this->client->get('/manga', [
'title' => $title,
'contentRating' => ['safe'],
'includes' => ['cover_art', 'author']
]);
$mangas = [];
foreach ($results['data'] as $result) {
$mangas[] = (new Manga())
->setExternalId($result['id'])
->setTitle($result['attributes']['title']['en'])
->setSlug($this->slugger->slug($result['attributes']['title']['en'])->lower())
->setDescription($result['attributes']['description']['fr'] ?? $result['attributes']['description']['en'] ?? '')
->setPublicationYear($result['attributes']['year'])
;
$tags = [];
foreach($result['attributes']['tags'] as $tag){
$tags[] = $tag['attributes']['name']['en'];
}
$mangas[count($mangas) - 1]->setGenres($tags);
foreach($result['relationships'] as $relationship) {
if($relationship['type'] === 'author') {
$mangas[count($mangas) - 1]->setAuthor($relationship['attributes']['name']);
}
if($relationship['type'] === 'cover_art') {
$mangas[count($mangas) - 1]->setImageUrl('https://mangadex.org/covers/' . $result['id'] . '/' .$relationship['attributes']['fileName']);
}
}
}
$test = array_map(fn($manga) => $manga->getExternalId(), $mangas);
$ratings = $this->client->get('/statistics/manga', [
'manga' => $test
]);
foreach($mangas as $manga) {
$manga->setRating($ratings['statistics'][$manga->getExternalId()]['rating']['average']);
}
return new ArrayCollection($mangas);
}
public function getFeed(Manga $manga): Manga
{
if($manga->getExternalId() === null) {
return $manga;
}
$chapters = [];
$page = 0;
do {
$results = $this->getFeedWithPagination($manga->getExternalId(), $page);
if (isset($results['data'])) {
$chapters = array_merge($chapters, $results['data']);
} else {
break;
}
$page++;
} while (count($chapters) < $results['total']);
foreach($chapters as $result) {
$chapterNumber = (float)$result['attributes']['chapter'];
// Utilisez la méthode exists de Doctrine pour vérifier si un chapitre avec le même numéro existe déjà
$chapterExists = $manga->getChapters()->exists(function($key, $existingChapter) use ($chapterNumber) {
return $existingChapter->getNumber() === $chapterNumber;
});
// Si le chapitre existe déjà, on skip
if ($chapterExists) {
continue;
}
// Créez et ajoutez le nouveau chapitre
$chapter = new Chapter();
$chapter->setNumber($chapterNumber)
->setTitle($result['attributes']['title'])
->setVolume((int)$result['attributes']['volume'] ?? null);
$manga->addChapter($chapter);
}
return $manga;
}
private function getFeedWithPagination(string $externalId, int $page){
return $this->client->get('/manga/' . $externalId . '/feed', [
'limit' => 500,
'translatedLanguage' =>['en'],
'order' => ['chapter' => 'asc'],
'offset' => $page * 500
]);
}
}

View File

@@ -2,33 +2,72 @@
namespace App\Service;
use Goutte\Client;
use App\Entity\Manga;
use App\Interface\ContentProviderInterface;
use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\BrowserKit\HttpBrowser as Client;
//use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpClient\HttpClient;
class SushiScanProviderService implements MangaProviderInterface
class SushiScanProviderService
{
const PROVIDER_URL = 'https://sushiscan.com/';
const MANGA_SLUG = '/{manga}/{chapter}/{page}';
private Client $client;
const PROVIDER_URL = 'https://sushiscan.net/catalogue/';
const MANGA_SLUG = '/{manga}/{chapter}/{page}';
public function __construct()
{
$this->client = new Client();
}
const CONTENT_TYPE = ['volume', 'chapitre'];
private Client $client;
/**
* @return array
*/
public function getMangaList(): array
{
// TODO: Implement getMangaList() method.
}
public function __construct()
{
$httpClient = HttpClient::create(['timeout' => 60]);
$this->client = new HttpBrowser($httpClient);
}
/**
* @param string $mangaSlug
* @return array
*/
public function getChapterList(string $mangaSlug): array
{
// TODO: Implement getChapterList() method.
}
}
public function getAvailableContent(Manga $manga)
{
$url = 'http://flaresolverr:8191/v1';
$jsonContent = json_encode([
'cmd' => 'request.get',
'url' => self::PROVIDER_URL . $manga->getSlug(),
'maxTimeout' => 90000,
]);
try{
$crawler = $this->client->request('POST', $url, [], [], [
'HTTP_CONTENT_TYPE' => 'application/json',
], $jsonContent);
}catch (\Exception $e) {
dd($e);
}
$contentList = [];
dd($crawler);
$crawler->filter('#chapterList ul > li')->each(function (Crawler $node) use (&$contentList) {
dump($node);
// $contentName = $node->text();
// $contentUrl = $node->attr('href');
// if ($contentName && $contentUrl) {
// $contentList[] = [
// 'name' => $contentName,
// 'url' => $contentUrl,
// ];
// }
});
return $contentList;
}
/**
* @param string $mangaSlug
* @return array
*/
public function getChapterList(string $mangaSlug): array
{
// TODO: Implement getChapterList() method.
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Twig\Components;
use App\Entity\Manga;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
#[AsLiveComponent]
class AddMangaModalComponent
{
use DefaultActionTrait;
#[LiveProp(writable: true)]
public ?Manga $manga;
public function open(Manga $manga): void
{
$this->manga = $manga;
}
public function close(): void
{
$this->manga = null;
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Twig\Components;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
#[AsTwigComponent]
class BootstrapModal
{
public ?string $id = null;
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Twig\Components;
use App\Repository\ChapterRepository;
use App\Repository\MangaRepository;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\DefaultActionTrait;
#[AsLiveComponent]
final class DownloadChapter
{
use DefaultActionTrait;
public ?string $mangaSlug = '';
public float $chapter;
public function __construct()
{
}
public function downloadChapter(MangaRepository $mangaRepository, ChapterRepository $chapterRepository): int
{
// $mangaSlug = $this->mangaSlug;
// $chapter = $this->chapter;
// $manga = $mangaRepository->findOneBy(['slug' => $mangaSlug]);
// $chapter = $chapterRepository->findOneBy(['manga' => $manga, 'number' => $chapter]);
return 0;
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Twig\Components;
use App\Service\MangadexProvider;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Exception;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\LiveComponent\ValidatableComponentTrait;
#[AsLiveComponent]
class MangaSearch
{
use DefaultActionTrait;
#[LiveProp(writable: true)]
public ?string $query = null;
public function __construct(private readonly MangadexProvider $mangadexProvider)
{
}
/**
* @throws Exception
*/
public function getMangas(): Collection|null
{
if ($this->query === null || $this->query === '') {
return null;
}
return $this->mangadexProvider->search($this->query);
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace App\Twig\Components;
use App\Entity\Manga;
use App\Service\MangadexProvider;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
#[AsLiveComponent]
class NewMangaForm
{
use ComponentToolsTrait;
use DefaultActionTrait;
public ?Manga $manga = null;
#[LiveProp(writable: true)]
public array $mangaData = [];
#[LiveProp(writable: true)]
public ?int $index = 0;
public function mount(Manga $manga): void
{
$this->manga = $manga;
$this->mangaData = [
'title' => $manga->getTitle(),
'slug' => $manga->getSlug(),
'description' => $manga->getDescription(),
'imageUrl' => $manga->getImageUrl(),
'status' => $manga->getStatus(),
'genres' => $manga->getGenres(),
'author' => $manga->getAuthor(),
'publicationYear' => $manga->getPublicationYear(),
'rating' => $manga->getRating(),
'externalId' => $manga->getExternalId(),
];
}
#[LiveAction]
public function saveManga(EntityManagerInterface $entityManager, MangadexProvider $mangadexProvider): Response
{
$manga = new Manga();
$manga->setTitle($this->mangaData['title'])
->setSlug($this->mangaData['slug'])
->setDescription($this->mangaData['description'])
->setImageUrl($this->mangaData['imageUrl'])
->setStatus($this->mangaData['status'])
->setGenres($this->mangaData['genres'])
->setAuthor($this->mangaData['author'])
->setPublicationYear($this->mangaData['publicationYear'])
->setRating($this->mangaData['rating'])
->setExternalId($this->mangaData['externalId']);
$mangadexProvider->getFeed($manga);
try {
foreach ($manga->getChapters() as $chapter) {
$entityManager->persist($chapter);
}
$entityManager->persist($manga);
$entityManager->flush();
} catch (\Exception $e) {
if ($e instanceof UniqueConstraintViolationException) {
return new RedirectResponse('/manga/' . $manga->getSlug());
}
throw $e;
}
return new RedirectResponse('/manga/' . $manga->getSlug());
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Twig\Components;
use App\Repository\MangaRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
#[AsLiveComponent]
final class Search
{
use DefaultActionTrait;
#[LiveProp (writable: true)]
public ?string $query = null;
public function __construct(private readonly MangaRepository $mangaRepository)
{
}
public function getMangas(): array
{
return $this->query ? $this->mangaRepository->findByTitle($this->query) : [];
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Twig\Components;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\DefaultActionTrait;
#[AsLiveComponent]
final class ToolBarButton
{
use DefaultActionTrait;
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class TruncateExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('truncate', [$this, 'truncate']),
];
}
public function truncate(?string $value, int $limit): string
{
if ($value === null) {
return '';
}
return strlen($value) > $limit ? substr($value, 0, $limit) . '...' : $value;
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Twig\Runtime;
use Twig\Extension\RuntimeExtensionInterface;
class TruncateExtensionRuntime implements RuntimeExtensionInterface
{
public function __construct()
{
// Inject dependencies if needed
}
public function doSomething($value)
{
// ...
}
}