apipage/web/index.php
2019-06-26 09:36:50 +02:00

86 lines
1.7 KiB
PHP

<?php
use Graby\Graby;
use Fusonic\OpenGraph\Consumer;
use Pecee\SimpleRouter\SimpleRouter;
require __DIR__.'/../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::create(__DIR__.'/../');
$dotenv->load();
function isValidUrl( ? string $url, ? string $hostname) : bool
{
if ($url === null) {
return false;
}
if (trim($url) === '') {
return false;
}
if (filter_var($url, FILTER_VALIDATE_URL) === false) {
return false;
}
echo '<pre>', var_dump($hostname), '</pre>';
die;
return parse_url($url)['host'] !== $hostname;
}
function graby(string $url) : array
{
$graby = new Graby();
$result = $graby->fetchContent($url);
if (isset($result['headers'])) {
unset($result['headers']);
}
return $result;
}
function opengraph(string $url) : array
{
$consumer = new Consumer();
$object = $consumer->loadUrl($url);
return json_decode(json_encode($object), true);
}
SimpleRouter::get('/do/{parser}', function ($parser) {
$url = input()->get('url')->value;
if (!isValidUrl($url, getenv('API_HOSTNAME'))) {
return response()
->httpCode(400)
->json(['error' => 'Invalid URL']);
}
$parsers = [
'graby' => 'graby',
'opengraph' => 'opengraph',
];
if (!isset($parsers[$parser])) {
return response()
->httpCode(400)
->json(['error' => 'Invalid parser']);
}
try {
$result = call_user_func_array($parsers[$parser], [$url]);
return response()
->httpCode(200)
->json($result);
} catch (\Exception $e) {
return response()
->httpCode(500)
->json(['error' => $e->getMessage()]);
}
});
SimpleRouter::start();