feat: refactoring of xml parsers

This commit is contained in:
Björn Fromme committed 2025-01-24 17:10:49 +01:00
1 parent 11f1508640
commit 6730c243f6
49 files changed
+1414 -1235

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\BusProNet\XmlLoader;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Travel;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Contracts\Cache\ItemInterface;
class HotelLoader extends AbstractLoader
{
public function loadAll(?string $filename = 'hotel.xml'): array
{
try {
return $this->cache->get('bpn_hotels', function (ItemInterface $item) use ($filename) {
$item->expiresAfter(3 * 60 * 60);
$hotels = [];
$this
->loadXml($filename)
->filterXPath('//hotels/hotel')
->each(function (Crawler $node) use (&$hotels) {
$id = (int) $node->attr('idbuspro');
$hotels[$id] = $this->parseXml($node);
})
;
return $hotels;
});
} catch (InvalidArgumentException $e) {
return [];
}
}
public function mapCodeToId(string $hotelCode, ?string $filename = 'hotel.xml'): ?int
{
$hotels = $this->loadAll($filename);
foreach ($hotels as $hotel) {
if ($hotelCode === $hotel->code) {
return $hotel->id;
}
}
return null;
}
public function loadById(int $id, ?string $filename = 'hotel.xml'): ?Hotel
{
$hotels = $this->loadAll($filename);
return $hotels[$id] ?? null;
}
private function loadXml(?string $filename = 'hotel.xml'): Crawler
{
$filepath = $this->xmlPath.'/'.$filename;
$xml = file_get_contents($filepath);
return new Crawler($xml);
}
public function parseXml(Crawler $node): Hotel
{
$hotel = new Hotel();
$hotel->id = (int) $node->attr('idbuspro');
$hotel->code = $node->attr('code');
$hotel->name = $this->getStringOrNullValue($node->filterXPath('//name'));
$hotel->city = $this->getStringOrNullValue($node->filterXPath('//ort'));
$hotel->country = $this->getStringOrNullValue($node->filterXPath('//land'));
$hotel->street = $this->getStringOrNullValue($node->filterXPath('//strasse'));
$hotel->phone = $this->getStringOrNullValue($node->filterXPath('//telefon'));
return $hotel;
}
public function patchHotelDetails(Travel $travel): void
{
$hotelId = $travel->hotelId;
$hotel = $this->loadById($hotelId);
$travel->hotel = $hotel;
}
}