fedi-feed-router/app/Services/Factories/ArticleParserFactory.php

81 lines
2 KiB
PHP
Raw Normal View History

2025-06-29 21:33:18 +02:00
<?php
namespace App\Services\Factories;
use App\Contracts\ArticleParserInterface;
2025-08-10 21:47:10 +02:00
use App\Models\Feed;
2025-06-29 21:39:28 +02:00
use App\Services\Parsers\BelgaArticleParser;
use App\Services\Parsers\GuardianArticleParser;
use App\Services\Parsers\VrtArticleParser;
2025-06-29 21:33:18 +02:00
use Exception;
class ArticleParserFactory
{
2025-07-07 00:51:32 +02:00
/**
* @var array<int, class-string<ArticleParserInterface>>
*/
2025-06-29 21:33:18 +02:00
private static array $parsers = [
VrtArticleParser::class,
2025-06-29 21:39:28 +02:00
BelgaArticleParser::class,
GuardianArticleParser::class,
2025-06-29 21:33:18 +02:00
];
2025-08-06 21:49:13 +02:00
/**
* @throws Exception
*/
2025-06-29 21:33:18 +02:00
public static function getParser(string $url): ArticleParserInterface
{
foreach (self::$parsers as $parserClass) {
$parser = new $parserClass;
2025-08-06 21:49:13 +02:00
2025-06-29 21:33:18 +02:00
if ($parser->canParse($url)) {
return $parser;
}
}
throw new Exception("No parser found for URL: {$url}");
}
2025-08-10 21:47:10 +02:00
public static function getParserForFeed(Feed $feed, string $parserType = 'article'): ?ArticleParserInterface
{
if (! $feed->provider) {
2025-08-10 21:47:10 +02:00
return null;
}
$providerConfig = config("feed.providers.{$feed->provider}");
if (! $providerConfig || ! isset($providerConfig['parsers'][$parserType])) {
2025-08-10 21:47:10 +02:00
return null;
}
/** @var class-string<ArticleParserInterface> $parserClass */
2025-08-10 21:47:10 +02:00
$parserClass = $providerConfig['parsers'][$parserType];
if (! class_exists($parserClass)) {
2025-08-10 21:47:10 +02:00
return null;
}
return new $parserClass;
2025-08-10 21:47:10 +02:00
}
2025-07-07 00:51:32 +02:00
/**
* @return array<int, string>
*/
2025-06-29 21:33:18 +02:00
public static function getSupportedSources(): array
{
return array_map(function ($parserClass) {
$parser = new $parserClass;
2025-06-29 21:33:18 +02:00
return $parser->getSourceName();
}, self::$parsers);
}
2025-07-07 02:48:46 +02:00
/**
* @param class-string<ArticleParserInterface> $parserClass
2025-07-07 02:48:46 +02:00
*/
2025-06-29 21:33:18 +02:00
public static function registerParser(string $parserClass): void
{
if (! in_array($parserClass, self::$parsers)) {
2025-06-29 21:33:18 +02:00
self::$parsers[] = $parserClass;
}
}
2025-08-06 21:49:13 +02:00
}