Files
myep/src/BusProNet/XmlLoader/AgencyLoader.php
T

88 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\BusProNet\XmlLoader;
use App\BusProNet\ApiClient;
use App\BusProNet\Model\Agency;
use App\BusProNet\Model\Notification;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
class AgencyLoader
{
public const DEFAULT_AGENCY_CODE = 'INTERN';
public function __construct(
private readonly CacheInterface $cache,
private readonly ApiClient $apiClient,
private readonly LoggerInterface $logger,
) {
}
/**
* @return Agency[]
*/
public function loadAll(): array
{
try {
return $this->cache->get('bpn_agencies', function (ItemInterface $item) {
// Cache for 24 hours (agencies change infrequently)
$item->expiresAfter(24 * 60 * 60);
$result = $this->apiClient->getAgencies();
if ($result instanceof Notification) {
$this->logger->error('Failed to fetch agencies from BPN API', [
'message' => $result->message,
]);
return [];
}
return $result;
});
} catch (InvalidArgumentException $e) {
$this->logger->error('Cache error while loading agencies', [
'exception' => $e->getMessage(),
]);
return [];
}
}
public function loadById(int $id): ?Agency
{
$agencies = $this->loadAll();
foreach ($agencies as $agency) {
if ($agency->id === $id) {
return $agency;
}
}
return null;
}
public function loadByCode(string $code): ?Agency
{
$agencies = $this->loadAll();
foreach ($agencies as $agency) {
if ($agency->code === $code) {
return $agency;
}
}
return null;
}
public function loadDefault(): ?Agency
{
return $this->loadByCode(self::DEFAULT_AGENCY_CODE);
}
}