webmentions/src/Webmention.php

60 lines
1.6 KiB
PHP
Raw Normal View History

<?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 {
2023-03-08 21:39:11 +00:00
$urls = $this->getUrls($source);
2023-03-08 21:39:11 +00:00
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);
2023-03-08 21:39:11 +00:00
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);
}
}