webmentions/src/Webmention.php

60 lines
1.6 KiB
PHP

<?php
namespace Lewisdale\Webmentions;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class Webmention {
private readonly HttpClientInterface $client;
function __construct()
{
$this->client = HttpClient::create();
}
public function sendForPage(string $source) : void {
$urls = $this->getUrls($source);
foreach($urls as $target) {
$this->sendWebmention($source, $target);
}
}
private function getUrls(string $url) : array {
$page = file_get_contents($url);
$doc = new Crawler($page);
$urls = [];
foreach ($doc->filter('.h-entry a') as $anchor) {
$target_url = $anchor->attributes->getNamedItem('href')->textContent;
if ($target_url !== null && strlen($target_url)) {
$urls[] = $target_url;
}
}
return $urls;
}
private function sendWebmention(string $source, string $target) {
$endpoint = $this->getWebmentionEndpoint($target);
if ($endpoint) {
echo "Sending for " . $endpoint . "<br />";
$this->client->request('POST', $endpoint,
[
"body" => [
"source" => $source,
"target" => $target
]
]);
}
}
private function getWebmentionEndpoint(string $url) : string | null {
$response = $this->client->request('GET', $url);
return EndpointParser::parse($response);
}
}