core/source/sources/ics_feed.php
2025-09-09 17:43:23 +00:00

145 lines
2.5 KiB
PHP

<?php
namespace davigil\sources;
require_once('helpers/string.php');
require_once('helpers/cache.php');
require_once('helpers/pit.php');
require_once('helpers/ics.php');
/**
*/
class class_source_ics_feed
implements interface_source
{
/**
*/
private string $url;
/**
*/
private bool $condense;
/**
*/
public function __construct(
string $url,
bool $condense
)
{
$this->url = $url;
$this->condense = $condense;
$this->cache_file = new \davigil\helpers\cache\class_cache_encoded(
new \davigil\helpers\cache\class_cache_file('data'),
fn($value) => \json_encode($value),
fn($value_encoded) => \json_decode($value_encoded, true)
);
$this->cache_memory = new \davigil\helpers\cache\class_cache_memory();
}
/**
*/
private function retrieve(
) : array
{
$client = new \Sabre\HTTP\Client();
$request = new \Sabre\HTTP\Request(
'GET',
$this->url,
[],
null
);
$response = $client->send($request);
$status_code = $response->getStatus();
switch ($status_code)
{
case 200:
{
$ics = $response->getBody();
$vcalendar = \davigil\helpers\ics\vcalendar_decode($ics);
$data = \array_map(
fn($vevent) => [
'id' => $vevent->uid,
'title' => (
$this->condense
?
\sprintf(
'%s%s',
$vevent->summary,
\implode(
'',
\array_map(
fn($category) => \sprintf(' (%s)', $category),
$vevent->categories
)
)
)
:
$vevent->summary
),
'begin' => \davigil\helpers\ics\datetime_to_unix_timestamp($vevent->dtstart->value),
'end' => (
($vevent->dtend === null)
?
null
:
\davigil\helpers\ics\datetime_to_unix_timestamp($vevent->dtend->value)
),
'location' => $vevent->location,
'description' => $vevent->description,
'tags' => (
$this->condense
?
['dummy']
:
$vevent->categories
),
],
$vcalendar->events
);
return $data;
break;
}
default:
{
throw (new \Exception(\sprintf('unhandled response status code: %u', $status_code)));
break;
}
}
}
/**
* [implementation]
*/
public function get(
array $parameters
) : array
{
$key = $this->url;
return \davigil\helpers\cache\get(
$this->cache_memory,
$key,
fn() => \davigil\helpers\cache\get(
$this->cache_file,
$key,
fn() => $this->retrieve(),
[
'ttl' => (60 * 5),
]
),
[
'ttl' => null,
]
);
}
}
?>