feat: refactoring of xml parsers
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\BusProNet\XmlLoader;
|
||||
|
||||
use App\BusProNet\Model\Pickup;
|
||||
use App\BusProNet\Model\Travel;
|
||||
use Psr\Cache\InvalidArgumentException;
|
||||
use Symfony\Component\DomCrawler\Crawler;
|
||||
use Symfony\Contracts\Cache\ItemInterface;
|
||||
|
||||
class PickupLoader extends AbstractLoader
|
||||
{
|
||||
public function loadAll(?string $filename = 'zustiege.xml'): array
|
||||
{
|
||||
try {
|
||||
return $this->cache->get('bpn_pickups', function (ItemInterface $item) use ($filename) {
|
||||
$item->expiresAfter(3 * 60 * 60);
|
||||
|
||||
$crawler = new Crawler(file_get_contents($this->xmlPath . '/' . $filename));
|
||||
$pickupNodes = $crawler->filterXPath('//zustiege/zustieg');
|
||||
|
||||
$pickups = [];
|
||||
|
||||
$pickupNodes->each(function (Crawler $node) use (&$pickups) {
|
||||
$id = $node->attr('idbuspro');
|
||||
$pickups[$id] = $this->parseXml($node);
|
||||
});
|
||||
|
||||
return $pickups;
|
||||
});
|
||||
} catch (InvalidArgumentException $e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public function loadById(int $id, ?string $filename = 'zustiege.xml'): ?Pickup
|
||||
{
|
||||
$pickups = $this->loadAll($filename);
|
||||
|
||||
return $pickups[$id] ?? null;
|
||||
}
|
||||
|
||||
public function parseXml(Crawler $node): Pickup
|
||||
{
|
||||
$pickup = new Pickup();
|
||||
$pickup->id = (int) $node->attr('idbuspro');
|
||||
$pickup->code = $node->attr('code');
|
||||
$pickup->city = $this->getStringOrNullValue($node->filterXPath('//ort'));
|
||||
$pickup->postalCode = $this->getStringOrNullValue($node->filterXPath('//plz'));
|
||||
$pickup->street = $this->getStringOrNullValue($node->filterXPath('//strasse'));
|
||||
|
||||
return $pickup;
|
||||
}
|
||||
|
||||
public function patchPickupsDetails(Travel $travel): void
|
||||
{
|
||||
foreach ($travel->pickups as $pickupId => $pickup) {
|
||||
$pickupData = $this->loadById($pickupId);
|
||||
|
||||
$pickup->code = $pickupData->code;
|
||||
$pickup->postalCode = $pickupData->postalCode;
|
||||
$pickup->city = $pickupData->city;
|
||||
$pickup->street = $pickupData->street;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user