feat: add WikidataAwardGateway for actor awards from Wikidata SPARQL
This commit is contained in:
73
src/Service/WikidataAwardGateway.php
Normal file
73
src/Service/WikidataAwardGateway.php
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Service;
|
||||||
|
|
||||||
|
use App\Entity\Actor;
|
||||||
|
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||||
|
|
||||||
|
class WikidataAwardGateway
|
||||||
|
{
|
||||||
|
private const SPARQL_ENDPOINT = 'https://query.wikidata.org/sparql';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly HttpClientInterface $httpClient,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch awards for an actor from Wikidata.
|
||||||
|
*
|
||||||
|
* @return list<array{name: string, year: int}>
|
||||||
|
*/
|
||||||
|
public function getAwards(Actor $actor): array
|
||||||
|
{
|
||||||
|
$sparql = $this->buildQuery($actor->getName());
|
||||||
|
|
||||||
|
$response = $this->httpClient->request('GET', self::SPARQL_ENDPOINT, [
|
||||||
|
'query' => [
|
||||||
|
'query' => $sparql,
|
||||||
|
'format' => 'json',
|
||||||
|
],
|
||||||
|
'headers' => [
|
||||||
|
'Accept' => 'application/sparql-results+json',
|
||||||
|
'User-Agent' => 'LtbxdActorle/1.0',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$data = $response->toArray();
|
||||||
|
$awards = [];
|
||||||
|
|
||||||
|
foreach ($data['results']['bindings'] ?? [] as $binding) {
|
||||||
|
$name = $binding['awardLabel']['value'] ?? null;
|
||||||
|
$year = $binding['year']['value'] ?? null;
|
||||||
|
|
||||||
|
if ($name && $year) {
|
||||||
|
$awards[] = [
|
||||||
|
'name' => $name,
|
||||||
|
'year' => (int) substr($year, 0, 4),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $awards;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildQuery(string $actorName): string
|
||||||
|
{
|
||||||
|
$escaped = str_replace('"', '\\"', $actorName);
|
||||||
|
|
||||||
|
return <<<SPARQL
|
||||||
|
SELECT ?awardLabel ?year WHERE {
|
||||||
|
?person rdfs:label "{$escaped}"@en .
|
||||||
|
?person wdt:P31 wd:Q5 .
|
||||||
|
?person p:P166 ?awardStatement .
|
||||||
|
?awardStatement ps:P166 ?award .
|
||||||
|
?awardStatement pq:P585 ?date .
|
||||||
|
BIND(YEAR(?date) AS ?year)
|
||||||
|
SERVICE wikibase:label { bd:serviceParam wikibase:language "fr,en" . }
|
||||||
|
}
|
||||||
|
ORDER BY DESC(?year)
|
||||||
|
SPARQL;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user