Compare commits

...
11 Commits
58 changed files with 3613 additions and 627 deletions

No files matched your search

+7 -5
View File
@@ -78,11 +78,13 @@ [email protected]
# Example: APP_MAIL_RECIPIENT_WHITELIST='.*@ep-reisen\.de,qa@example\.com'
APP_MAIL_RECIPIENT_WHITELIST=
SFTP_XML_EXPORT_HOST=
SFTP_XML_EXPORT_PORT=22
SFTP_XML_EXPORT_USER=
SFTP_XML_EXPORT_PASSWORD=
SFTP_XML_EXPORT_ROOT=
# Machine to machine access to the MyE&P API. This is a separate confidential client
# from the login one below, so it can be rotated without locking anyone out. The base
# url is the host root: both the token endpoint and the api paths hang off it.
MYEP_API_BASE_URL=https://my.ep-reisen.de/
MYEP_API_CLIENT_ID=
MYEP_API_CLIENT_SECRET=
MYEP_OAUTH2_CLIENT_ID=
MYEP_OAUTH2_CLIENT_SECRET=
+4 -4
View File
@@ -198,11 +198,11 @@
<path d="M24 0C10.7 0 0 10.7 0 24S10.7 48 24 48h8V67c0 40.3 16 79 44.5 107.5L158.1 256 76.5 337.5C48 366 32 404.7 32 445v19H24c-13.3 0-24 10.7-24 24s10.7 24 24 24H360c13.3 0 24-10.7 24-24s-10.7-24-24-24h-8V445c0-40.3-16-79-44.5-107.5L225.9 256l81.5-81.5C336 146 352 107.3 352 67V48h8c13.3 0 24-10.7 24-24s-10.7-24-24-24H24zM192 289.9l81.5 81.5C293 391 304 417.4 304 445v19H80V445c0-27.6 11-54 30.5-73.5L192 289.9zm0-67.9l-81.5-81.5C91 121 80 94.6 80 67V48H304V67c0 27.6-11 54-30.5 73.5L192 222.1z"/>
</symbol>
<symbol id="icon-car" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><rect width="256" height="256" fill="none"/><circle cx="64" cy="176" r="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><circle cx="192" cy="176" r="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="88" y1="176" x2="168" y2="176" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M216,176h24a8,8,0,0,0,8-8V128a8,8,0,0,0-8-8H208L162.34,74.34A8,8,0,0,0,156.69,72H44.28a8,8,0,0,0-6.65,3.56L8,120v48a8,8,0,0,0,8,8H40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><line x1="208" y1="120" x2="8" y2="120" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></symbol>
<symbol id="icon-flag-a" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd"><path fill="#fff" d="M640 480H0V0h640z"/><path fill="#ed2939" d="M640 480H0V320h640zm0-319.9H0V.1h640z"/></g></symbol>
<symbol id="icon-flag-at" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd"><path fill="#fff" d="M640 480H0V0h640z"/><path fill="#ed2939" d="M640 480H0V320h640zm0-319.9H0V.1h640z"/></g></symbol>
<symbol id="icon-flag-ch" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd" stroke-width="1pt"><path fill="#d52b1e" d="M0 0h640v480H0z"/><g fill="#fff"><path d="M170 195h300v90H170z"/><path d="M275 90h90v300h-90z"/></g></g></symbol>
<symbol id="icon-flag-d" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><path fill="#ffce00" d="M0 320h640v160H0z"/><path d="M0 0h640v160H0z"/><path fill="#d00" d="M0 160h640v160H0z"/></symbol>
<symbol id="icon-flag-f" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd" stroke-width="1pt"><path fill="#fff" d="M0 0h640v480H0z"/><path fill="#00267f" d="M0 0h213.3v480H0z"/><path fill="#f31830" d="M426.7 0H640v480H426.7z"/></g></symbol>
<symbol id="icon-flag-i" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd" stroke-width="1pt"><path fill="#fff" d="M0 0h640v480H0z"/><path fill="#009246" d="M0 0h213.3v480H0z"/><path fill="#ce2b37" d="M426.7 0H640v480H426.7z"/></g></symbol>
<symbol id="icon-flag-de" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><path fill="#ffce00" d="M0 320h640v160H0z"/><path d="M0 0h640v160H0z"/><path fill="#d00" d="M0 160h640v160H0z"/></symbol>
<symbol id="icon-flag-fr" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd" stroke-width="1pt"><path fill="#fff" d="M0 0h640v480H0z"/><path fill="#00267f" d="M0 0h213.3v480H0z"/><path fill="#f31830" d="M426.7 0H640v480H426.7z"/></g></symbol>
<symbol id="icon-flag-it" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd" stroke-width="1pt"><path fill="#fff" d="M0 0h640v480H0z"/><path fill="#009246" d="M0 0h213.3v480H0z"/><path fill="#ce2b37" d="M426.7 0H640v480H426.7z"/></g></symbol>
<symbol id="icon-flag-nl" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><g fill-rule="evenodd"><path fill="#21468b" d="M0 320h640v160H0z"/><path fill="#fff" d="M0 160h640v160H0z"/><path fill="#ae1c28" d="M0 0h640v160H0z"/></g></symbol>
<!-- By Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL -->
<symbol id="icon-spinner" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg" stroke="currentColor">

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Generated
+8 -7
View File
@@ -12950,23 +12950,23 @@
},
{
"name": "fidry/cpu-core-counter",
"version": "1.3.0",
"version": "1.4.0",
"source": {
"type": "git",
"url": "https://github.com/theofidry/cpu-core-counter.git",
"reference": "db9508f7b1474469d9d3c53b86f817e344732678"
"reference": "7cbeb03e286fa81b2bbe0e6bd6b8a27c71a3144d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/db9508f7b1474469d9d3c53b86f817e344732678",
"reference": "db9508f7b1474469d9d3c53b86f817e344732678",
"url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/7cbeb03e286fa81b2bbe0e6bd6b8a27c71a3144d",
"reference": "7cbeb03e286fa81b2bbe0e6bd6b8a27c71a3144d",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"require-dev": {
"fidry/makefile": "^0.2.0",
"fidry/makefile": "^0.2.0 || ^1.1.2",
"fidry/php-cs-fixer-config": "^1.1.2",
"phpstan/extension-installer": "^1.2.0",
"phpstan/phpstan": "^2.0",
@@ -12974,6 +12974,7 @@
"phpstan/phpstan-phpunit": "^2.0",
"phpstan/phpstan-strict-rules": "^2.0",
"phpunit/phpunit": "^8.5.31 || ^9.5.26",
"symfony/polyfill-mbstring": "^1.33",
"webmozarts/strict-phpunit": "^7.5"
},
"type": "library",
@@ -12999,7 +13000,7 @@
],
"support": {
"issues": "https://github.com/theofidry/cpu-core-counter/issues",
"source": "https://github.com/theofidry/cpu-core-counter/tree/1.3.0"
"source": "https://github.com/theofidry/cpu-core-counter/tree/1.4.0"
},
"funding": [
{
@@ -13007,7 +13008,7 @@
"type": "github"
}
],
"time": "2025-08-14T07:29:31+00:00"
"time": "2026-09-27T17:40:20+00:00"
},
{
"name": "friendsofphp/php-cs-fixer",
-7
View File
@@ -1,13 +1,6 @@
# Read the documentation at https://github.com/thephpleague/flysystem-bundle/blob/master/docs/1-getting-started.md
flysystem:
storages:
xml_export.storage:
sftp:
host: '%env(SFTP_XML_EXPORT_HOST)%'
port: '%env(int:SFTP_XML_EXPORT_PORT)%'
username: '%env(SFTP_XML_EXPORT_USER)%'
password: '%env(SFTP_XML_EXPORT_PASSWORD)%'
root: '%env(SFTP_XML_EXPORT_ROOT)%'
xml_dump.storage:
local:
directory: '%kernel.project_dir%/var/bpn'
+16
View File
@@ -28,6 +28,22 @@ framework:
router:
default_uri: '%env(APP_BASE_URI)%'
# Every call to the sibling MyE&P application, both the token request and the API
# itself. Paths are given relative to the base uri, so without a leading slash.
http_client:
scoped_clients:
myep.client:
base_uri: '%env(MYEP_API_BASE_URL)%'
timeout: 10
max_duration: 30
headers:
Accept: application/json
retry_failed:
max_retries: 2
# 401 is deliberately absent: it needs the cached token dropped
# before the retry, which App\MyEp\Api\ApiClient does itself.
http_codes: [423, 425, 429, 500, 502, 503, 504]
when@test:
framework:
test: true
+17 -4
View File
@@ -3,6 +3,7 @@ monolog:
- deprecation
- bpn
- saas
- myep
- audit
- api
@@ -13,7 +14,7 @@ monolog:
handler: exceptions
excluded_http_codes: [404, 405]
buffer_size: 50
channels: ["!bpn", "!saas", "!audit", "!api"]
channels: ["!bpn", "!saas", "!myep", "!audit", "!api"]
exceptions:
type: rotating_file
path: "%kernel.logs_dir%/framework.%kernel.environment%.log"
@@ -31,6 +32,12 @@ monolog:
path: '%kernel.logs_dir%/saas.%kernel.environment%.log'
max_files: 5
level: info
myep:
channels: ["myep"]
type: rotating_file
path: '%kernel.logs_dir%/myep.%kernel.environment%.log'
max_files: 5
level: info
audit:
channels: [ "audit" ]
type: rotating_file
@@ -52,7 +59,7 @@ monolog:
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!bpn", "!saas", "!api", "!doctrine", "!console"]
channels: ["!event", "!bpn", "!saas", "!myep", "!api", "!doctrine", "!console"]
when@dev:
monolog:
@@ -89,7 +96,7 @@ when@prod:
handler: exceptions
excluded_http_codes: [404, 405]
buffer_size: 50
channels: ["!bpn", "!saas", "!audit", "!api"]
channels: ["!bpn", "!saas", "!myep", "!audit", "!api"]
exceptions:
type: rotating_file
path: "%kernel.logs_dir%/framework.%kernel.environment%.log"
@@ -107,6 +114,12 @@ when@prod:
path: '%kernel.logs_dir%/saas.%kernel.environment%.log'
max_files: 5
level: info
myep:
channels: ["myep"]
type: rotating_file
path: '%kernel.logs_dir%/myep.%kernel.environment%.log'
max_files: 5
level: info
audit:
channels: [ "audit" ]
type: rotating_file
@@ -126,4 +139,4 @@ when@prod:
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine", "!bpn", "!saas", "!audit", "!api"]
channels: ["!event", "!doctrine", "!bpn", "!saas", "!myep", "!audit", "!api"]
+8 -6
View File
@@ -15,9 +15,11 @@ zenstruck_schedule:
when@prod:
zenstruck_schedule:
tasks:
- task: app:bpn-import
frequency: '0 3 * * *'
description: "Imports dates, products and hotels from BusProNet"
# 03:20 rather than 03:00: MyE&P mirrors from BusProNet hourly overnight, on the
# hour, so an import at 03:00 can read a half written export.
- task: app:myep-import
frequency: '20 3 * * *'
description: "Imports travel dates, products and hotels from the MyE&P API"
- task: app:cron
frequency: '0 1 * * *'
@@ -45,9 +47,9 @@ when@staging:
subject_prefix: "[E&P-Team STAGING]"
tasks:
- task: app:bpn-import
frequency: '30 3 * * *'
description: "Imports dates, products and hotels from BusProNet"
- task: app:myep-import
frequency: '50 3 * * *'
description: "Imports travel dates, products and hotels from the MyE&P API"
- task: app:cron
frequency: '30 2 * * *'
+26 -2
View File
@@ -130,7 +130,6 @@ services:
# it drops its records from that table.
$logger: '@monolog.logger.audit'
$houses: '%houses%'
$xmlExport: '@xml_export.storage'
$xmlDump: '@xml_dump.storage'
$teamerInactivePeriod: '%teamer_inactive_period%'
$contractUploadDeadlineDays: '%contract_upload_deadline_days%'
@@ -165,7 +164,7 @@ services:
- name: liip_imagine.cache.resolver
resolver: format_extension
App\Command\BpnImportCommand:
App\Command\MyEpImportCommand:
arguments:
$connection: '@doctrine.dbal.default_connection'
@@ -217,6 +216,31 @@ services:
# new starter is picked up the same day.
$ttl: 21600
App\MyEp\Api\AccessTokenProvider:
arguments:
$logger: '@monolog.logger.myep'
$cache: '@cache.app'
$options:
client_id: '%env(MYEP_API_CLIENT_ID)%'
client_secret: '%env(MYEP_API_CLIENT_SECRET)%'
App\MyEp\Api\ApiClient:
arguments:
$logger: '@monolog.logger.myep'
App\MyEp\Api\ResponseMapper:
arguments:
$logger: '@monolog.logger.myep'
App\MyEp\Cache\StaleWhileErrorCache:
arguments:
$logger: '@monolog.logger.myep'
$cache: '@cache.app'
App\MyEp\Import\TravelExportClient:
arguments:
$logger: '@monolog.logger.myep'
App\Twig\AppRuntime:
arguments:
$intlExtension: '@twig.extension.intl'
+1 -1
View File
@@ -131,7 +131,7 @@ Three failure modes worth knowing because they are quiet rather than loud:
## Scheduled tasks are a different mechanism
`config/packages/zenstruck_schedule.yaml` holds the daily jobs (`app:cron`,
`app:bpn-import`, `app:teamer-status`, …), driven by a separate `schedule:run` cron entry.
`app:myep-import`, `app:teamer-status`, …), driven by a separate `schedule:run` cron entry.
**Do not put `messenger:consume` in there.** The bundle runs tasks in-process and
sequentially, so a consume task holds the entire schedule for its duration — every later
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Moves destination.country from the raw BusProNet abbreviations to lowercase ISO-2.
*
* The column used to hold whatever BusProNet reported as hotel/land, lowercased: a,
* ch, d, f, i, nl. That set is not a standard - the same country appears as A, AT and
* AUT upstream - so the import now stores the ISO code MyE&P resolves instead, and the
* existing rows are converted to match. The flag icons and the country filters use the
* same vocabulary and are switched with it.
*/
final class Version20260927090000 extends AbstractMigration
{
private const TO_ISO = [
'a' => 'at',
'd' => 'de',
'f' => 'fr',
'i' => 'it',
];
public function getDescription(): string
{
return 'Convert destination.country to lowercase ISO-3166-1 alpha-2';
}
public function up(Schema $schema): void
{
foreach (self::TO_ISO as $legacy => $iso) {
$this->addSql('UPDATE destination SET country = ? WHERE country = ?', [$iso, $legacy]);
}
// ch and nl are already ISO; empty strings were never a country
$this->addSql("UPDATE destination SET country = NULL WHERE country = ''");
}
public function down(Schema $schema): void
{
foreach (self::TO_ISO as $legacy => $iso) {
$this->addSql('UPDATE destination SET country = ? WHERE country = ?', [$legacy, $iso]);
}
}
}
+12 -21
View File
@@ -2,7 +2,6 @@
namespace App\BusProNet;
use App\BusProNet\Model\BaseDataResponse;
use App\BusProNet\Model\CrmAttributesResponse;
use App\BusProNet\Model\NotificationResponse;
use App\BusProNet\Model\ProfileResponse;
@@ -17,15 +16,24 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Uid\Uuid;
/**
* The socket protocol against BusProNet: length prefixed German XML over fsockopen.
*
* This is the **write** path and the user facing reads that go with it - profile lookup and
* update, registration, password reset, the CRM selections behind the leads roles and hotel
* codes. All of it is per user and authenticated as that user, which is why it stays here.
*
* It is not legacy. The base data reads that used to sit alongside it - STAMMLAENDER,
* STAMMZUSTIEGE, STAMMHOTELS - are gone: hotels, pickups and countries now come from MyE&P's
* REST api (App\BusProNet\DataProvider\*, App\MyEp\Api\ApiClient), which is the one place
* that understands BusProNet's XML.
*/
class ApiClient
{
use ApiClientTrait;
public const TYPE_NOTIFICATION = 'HINWEIS';
public const TYPE_CUSTOMER_DATA = 'KUNDENKONTO';
public const TYPE_BASE_DATA_COUNTRIES = 'STAMMLAENDER';
public const TYPE_BASE_DATA_PICKUPS = 'STAMMZUSTIEGE';
public const TYPE_BASE_DATA_HOTELS = 'STAMMHOTELS';
private array $config;
@@ -204,23 +212,6 @@ class ApiClient
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
}
/**
* @throws ApiClientException
* @throws ResponseParserException
*/
public function getBaseData(string $type): NotificationResponse|BaseDataResponse
{
$data = [
'anfrage' => [
'user' => $this->config['bpn_username'],
'key' => $this->createKey($this->config['bpn_username'], $this->config['bpn_password'], $type),
'satz' => ['@typ' => $type],
],
];
return $this->sendRequest($type, $data);
}
/**
* @throws ApiClientException
* @throws ResponseParserException
@@ -2,46 +2,39 @@
namespace App\BusProNet\DataProvider;
use App\BusProNet\ApiClient;
use App\BusProNet\ApiClientException;
use App\BusProNet\Model\Country;
use App\BusProNet\Model\NotificationResponse;
use App\BusProNet\ResponseParserException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ResponseMapper;
use App\MyEp\Cache\StaleWhileErrorCache;
/**
* Country base data, read from MyE&P rather than from BusProNet directly.
*
* Keyed by the raw BusProNet token, not by an ISO code: the token is what a hotel's
* country and a teamer's nationality join against, and that vocabulary stays raw.
*/
class CountryDataProvider
{
private const CACHE_KEY = 'myep_countries';
private const TTL = 3600;
public function __construct(
private readonly ApiClient $apiClient,
private readonly CacheInterface $cache,
private readonly LoggerInterface $logger,
private readonly ResponseMapper $responseMapper,
private readonly StaleWhileErrorCache $cache,
) {
}
/**
* @return array<string, Country> keyed by token
*/
public function getAll(): array
{
try {
$countries = $this->cache->get('bpn_countries', function (ItemInterface $item) {
$item->expiresAfter(3600);
$response = $this->apiClient->getBaseData(ApiClient::TYPE_BASE_DATA_COUNTRIES);
if ($response instanceof NotificationResponse) {
$this->logger->error('Unable to fetch country base data from BusProNet. Code: '.$response->getCode().', Message: '.$response->getMessage());
throw new ApiClientException('Unable to fetch country base data from BusProNet');
}
return $response->getItems();
});
} catch (ApiClientException|ResponseParserException $e) {
$this->logger->error('Unable to fetch country base data from BusProNet: '.$e->getMessage());
$countries = [];
}
return $countries;
return $this->cache->get(
self::CACHE_KEY,
self::TTL,
fn (): array => $this->responseMapper->mapCountries($this->apiClient->get('api/countries')),
);
}
public function get(?string $token): ?Country
@@ -2,47 +2,40 @@
namespace App\BusProNet\DataProvider;
use App\BusProNet\ApiClient;
use App\BusProNet\ApiClientException;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\NotificationResponse;
use App\BusProNet\ResponseParserException;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ResponseMapper;
use App\MyEp\Cache\StaleWhileErrorCache;
/**
* Hotel base data, read from MyE&P rather than from BusProNet directly.
*
* The models and the public interface are unchanged from when this spoke the BusProNet
* socket protocol: every caller keys on the BusProNet idbuspro, which is exactly what
* MyE&P reports as the hotel id.
*/
class HotelDataProvider
{
private const CACHE_KEY = 'myep_hotels';
private const TTL = 3600;
public function __construct(
private readonly ApiClient $apiClient,
private readonly CacheInterface $cache,
private readonly LoggerInterface $logger,
private readonly ResponseMapper $responseMapper,
private readonly StaleWhileErrorCache $cache,
) {
}
/**
* @return array<int, Hotel> keyed by busProId
*/
public function getAll(): array
{
try {
$hotels = $this->cache->get('bpn_hotels', function (ItemInterface $item) {
$item->expiresAfter(3600);
$response = $this->apiClient->getBaseData(ApiClient::TYPE_BASE_DATA_HOTELS);
if ($response instanceof NotificationResponse) {
$this->logger->error('Unable to fetch hotel base data from BusProNet. Code: '.$response->getCode().', Message: '.$response->getMessage());
throw new ApiClientException('Unable to fetch hotel base data from BusProNet');
}
return $response->getItems();
});
} catch (ApiClientException|InvalidArgumentException|ResponseParserException $e) {
$this->logger->error('Unable to fetch hotel base data from BusProNet: '.$e->getMessage());
$hotels = [];
}
return $hotels;
return $this->cache->get(
self::CACHE_KEY,
self::TTL,
fn (): array => $this->responseMapper->mapHotels($this->apiClient->get('api/hotels')),
);
}
public function get(int $busProId): ?Hotel
@@ -50,12 +43,21 @@ class HotelDataProvider
return $this->getAll()[$busProId] ?? null;
}
/**
* @return list<Hotel>
*/
public function findByCode(string $code): array
{
$hotels = [];
foreach ($this->getAll() as $hotel) {
if (str_starts_with($hotel->getCode(), $code) || str_ends_with($hotel->getCode(), $code)) {
$hotelCode = $hotel->getCode();
if (null === $hotelCode) {
continue;
}
if (str_starts_with($hotelCode, $code) || str_ends_with($hotelCode, $code)) {
$hotels[] = $hotel;
}
}
@@ -2,46 +2,39 @@
namespace App\BusProNet\DataProvider;
use App\BusProNet\ApiClient;
use App\BusProNet\ApiClientException;
use App\BusProNet\Model\NotificationResponse;
use App\BusProNet\Model\Pickup;
use App\BusProNet\ResponseParserException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ResponseMapper;
use App\MyEp\Cache\StaleWhileErrorCache;
/**
* Boarding point base data, read from MyE&P rather than from BusProNet directly.
*
* These are the stops themselves, without a departure time: a time belongs to a stop on
* a given travel date and is carried by the destination's pickups instead.
*/
class PickupDataProvider
{
private const CACHE_KEY = 'myep_pickups';
private const TTL = 3600;
public function __construct(
private readonly ApiClient $apiClient,
private readonly CacheInterface $cache,
private readonly LoggerInterface $logger,
private readonly ResponseMapper $responseMapper,
private readonly StaleWhileErrorCache $cache,
) {
}
/**
* @return array<int, Pickup> keyed by busProId
*/
public function getAll(): array
{
try {
$pickups = $this->cache->get('bpn_pickups', function (ItemInterface $item) {
$item->expiresAfter(3600);
$response = $this->apiClient->getBaseData(ApiClient::TYPE_BASE_DATA_PICKUPS);
if ($response instanceof NotificationResponse) {
$this->logger->error('Unable to fetch pickup base data from BusProNet. Code: '.$response->getCode().', Message: '.$response->getMessage());
throw new ApiClientException('Unable to fetch pickup base data from BusProNet');
}
return $response->getItems();
});
} catch (ApiClientException|ResponseParserException $e) {
$this->logger->error('Unable to fetch pickup base data from BusProNet: '.$e->getMessage());
$pickups = [];
}
return $pickups;
return $this->cache->get(
self::CACHE_KEY,
self::TTL,
fn (): array => $this->responseMapper->mapPickups($this->apiClient->get('api/pickups')),
);
}
public function get(int $busProId): ?Pickup
-15
View File
@@ -1,15 +0,0 @@
<?php
namespace App\BusProNet\Model;
class BaseDataResponse
{
public function __construct(private readonly array $items)
{
}
public function getItems(): array
{
return $this->items;
}
}
-13
View File
@@ -4,23 +4,10 @@ namespace App\BusProNet\Model;
class Country
{
private ?int $id = null;
private ?string $name = null;
private ?string $token = null;
private ?string $nationality = null;
public function getId(): ?int
{
return $this->id;
}
public function setId(?int $id): static
{
$this->id = $id;
return $this;
}
public function getName(): ?string
{
return $this->name;
+22 -65
View File
@@ -4,29 +4,22 @@ namespace App\BusProNet\Model;
class Hotel
{
private ?int $id = null;
private ?int $busProId = null;
private ?string $code = null;
private ?string $name = null;
private ?string $city = null;
private ?string $street = null;
private ?string $phone = null;
private ?string $type = null;
/**
* The raw BusProNet abbreviation, which is not a standard: the same country turns
* up as D, DEU, A, AT or AUT. It joins against the country base data by token.
*/
private ?string $country = null;
/**
* The same country as lowercase ISO-3166-1 alpha-2, resolved by MyE&P. Null when
* the source carries no country or none can be determined.
*/
private ?string $countryCode = null;
private ?string $costUnit = null;
public function getId(): ?int
{
return $this->id;
}
public function setId(?int $id): static
{
$this->id = $id;
return $this;
}
public function getBusProId(): ?int
{
return $this->busProId;
@@ -63,54 +56,6 @@ class Hotel
return $this;
}
public function getCity(): ?string
{
return $this->city;
}
public function setCity(?string $city): static
{
$this->city = $city;
return $this;
}
public function getStreet(): ?string
{
return $this->street;
}
public function setStreet(?string $street): static
{
$this->street = $street;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): static
{
$this->phone = $phone;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getCountry(): ?string
{
return $this->country;
@@ -123,6 +68,18 @@ class Hotel
return $this;
}
public function getCountryCode(): ?string
{
return $this->countryCode;
}
public function setCountryCode(?string $countryCode): static
{
$this->countryCode = $countryCode;
return $this;
}
public function getCostUnit(): ?string
{
return $this->costUnit;
-79
View File
@@ -3,15 +3,11 @@
namespace App\BusProNet;
use App\BusProNet\Model\Address;
use App\BusProNet\Model\BaseDataResponse;
use App\BusProNet\Model\Communication;
use App\BusProNet\Model\Country;
use App\BusProNet\Model\CrmAttribute;
use App\BusProNet\Model\CrmAttributeGroup;
use App\BusProNet\Model\CrmAttributesResponse;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\NotificationResponse;
use App\BusProNet\Model\Pickup;
use App\BusProNet\Model\ProfileResponse;
use App\BusProNet\Model\ProfileUpdateResponse;
use App\BusProNet\Model\RegistrationResponse;
@@ -64,12 +60,6 @@ class ResponseParser
return $this->createRegistrationResponse($xml);
}
break;
case ApiClient::TYPE_BASE_DATA_COUNTRIES:
return $this->createCountriesResponse($xml);
case ApiClient::TYPE_BASE_DATA_PICKUPS:
return $this->createPickupsResponse($xml);
case ApiClient::TYPE_BASE_DATA_HOTELS:
return $this->createHotelsResponse($xml);
}
throw new ResponseParserException(sprintf('Unrecognised BusProNet response type "%s"', $responseType));
@@ -268,75 +258,6 @@ class ResponseParser
return $response;
}
public function createCountriesResponse(\SimpleXMLElement $xml): BaseDataResponse
{
$countries = [];
foreach ($xml->laender->land as $item) {
$itemAttributes = $item->attributes();
$token = (string) $itemAttributes['kuerzel'];
$country = new Country();
$country
->setId((int) $itemAttributes['id'])
->setName((string) $itemAttributes['bezeichnung'])
->setToken((string) $itemAttributes['kuerzel'])
->setNationality((string) $itemAttributes['nationalitaet'])
;
$countries[$token] = $country;
}
return new BaseDataResponse($countries);
}
public function createPickupsResponse(\SimpleXMLElement $xml): BaseDataResponse
{
$pickups = [];
foreach ($xml->zustieg as $item) {
$itemAttributes = $item->attributes();
$id = (int) $itemAttributes['id'];
$busProId = (int) $itemAttributes['idbuspro'];
$pickup = new Pickup();
$pickup
->setId($id)
->setBusProId($busProId)
->setCode((string) $itemAttributes['code'])
->setCity((string) $item->ort)
->setStreet((string) $item->strasse)
;
$pickups[$busProId] = $pickup;
}
return new BaseDataResponse($pickups);
}
public function createHotelsResponse(\SimpleXMLElement $xml): BaseDataResponse
{
$hotels = [];
foreach ($xml->hotel as $item) {
$itemAttributes = $item->attributes();
$id = (int) $itemAttributes['id'];
$busProId = (int) $itemAttributes['idbuspro'];
$hotel = new Hotel();
$hotel
->setId($id)
->setBusProId($busProId)
->setCode((string) $itemAttributes['code'])
->setName((string) $item->name)
->setCountry(strtolower((string) $item->land))
->setCity((string) $item->ort)
->setStreet((string) $item->strasse)
->setPhone((string) $item->telefon)
->setType((string) $item->art)
->setCostUnit($item->kostenstelle)
;
$hotels[$busProId] = $hotel;
}
return new BaseDataResponse($hotels);
}
/**
* The BusProNet endpoint can answer with an empty or truncated body. Keep the libxml
* reason instead of collapsing every shape of broken response into one message.
-195
View File
@@ -1,195 +0,0 @@
<?php
namespace App\Command;
use App\BusProNet\DataProvider\HotelDataProvider;
use App\BusProNet\DataProvider\PickupDataProvider;
use Doctrine\DBAL\Connection;
use League\Flysystem\FilesystemException;
use League\Flysystem\FilesystemOperator;
use League\Flysystem\StorageAttributes;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:bpn-import',
description: 'Imports dates, products and hotels from BusProNet',
)]
class BpnImportCommand extends Command
{
public function __construct(
private readonly Connection $connection,
private readonly HotelDataProvider $hotelDataProvider,
private readonly PickupDataProvider $pickupDataProvider,
private readonly LoggerInterface $logger,
private readonly FilesystemOperator $xmlExport,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
// Get all xml files
try {
$xmlFiles = $this
->xmlExport
->listContents('')
->filter(fn (StorageAttributes $attributes) => $attributes->isFile() && str_starts_with($attributes->path(), 'Ziel_'))
->toArray();
} catch (FilesystemException $e) {
$io->error('Unable to list XML files');
return Command::FAILURE;
}
$totalCount = count($xmlFiles);
if (0 === $totalCount) {
$io->error('No XML files available or found');
return Command::FAILURE;
}
// Resolve the BusProNet base data once, before touching a single row. A destination
// cannot be written without its hotel, so an unavailable hotel list would otherwise
// skip every record and still report success. Holding both lists locally also keeps
// the loop off the providers: on a failed fetch nothing is cached, and a per-lookup
// ->get() would re-open the socket for every pickup of all 174 files.
$hotels = $this->hotelDataProvider->getAll();
$pickups = $this->pickupDataProvider->getAll();
if ([] === $hotels) {
$io->error('Hotel-Stammdaten konnten nicht von BusProNet geladen werden – Import abgebrochen.');
$this->logger->error('BPN import aborted: hotel base data unavailable');
return Command::FAILURE;
}
$io->info('Found '.$totalCount.' XML files');
$addedCount = 0;
$updatedCount = 0;
$warnings = [];
if ([] === $pickups) {
$warnings[] = 'Zustiegs-Stammdaten konnten nicht von BusProNet geladen werden';
}
$progressBar = $io->createProgressBar($totalCount);
$progressBar->setFormat(" %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%\n %message%");
$progressBar->setMessage('Starting');
$progressBar->start();
// Iterate over xml files
foreach ($xmlFiles as $xmlFile) {
$progressBar->setMessage($xmlFile->path());
// Load xml file into simplexml object
try {
$xml = simplexml_load_string($this->xmlExport->read($xmlFile->path()));
} catch (FilesystemException $e) {
$warnings[] = 'Unable to read XML file '.$xmlFile->path();
$progressBar->advance();
continue;
}
// Iterate over all destinations
foreach ($xml->xpath('reise/termin') as $destinationXml) {
$product = (string) $destinationXml->xpath('text')[0];
$busProId = (int) $destinationXml->attributes()['idbuspro'];
$code = (string) $destinationXml->attributes()['code'];
$dateFrom = \DateTimeImmutable::createFromFormat('d.m.Y', (string) $destinationXml->attributes()['termin']);
$dateTo = \DateTimeImmutable::createFromFormat('d.m.Y', (string) $destinationXml->attributes()['bis']);
// Find pickups
$datePickups = [];
foreach ($destinationXml->xpath('zustiege/zustieg') as $pickupXml) {
$pickupBusProId = (int) $pickupXml->attributes()['idbuspro'];
if ($pickupBusProId) {
if (null === $pickup = $pickups[$pickupBusProId] ?? null) {
$warnings[] = 'Pickup with busProId '.$pickupBusProId.' not found';
continue;
}
$datePickups[] = [
'busProId' => $pickupBusProId,
'city' => $pickup->getCity(),
'street' => $pickup->getStreet(),
'time' => (string) $pickupXml->attributes()['zeit'],
];
}
}
// Iterate over all hotel entries
foreach ($destinationXml->xpath('hotel') as $hotelXml) {
$hotelBusProId = (int) $hotelXml->attributes()['idbuspro'];
if (null === $hotel = $hotels[$hotelBusProId] ?? null) {
$warnings[] = 'Hotel with busProId '.$hotelBusProId.' not found';
continue;
}
// Finally update or store collected data
if ($id = $this->connection->fetchOne('SELECT id FROM destination WHERE bus_pro_id=? AND hotel_bus_pro_id=?', [$busProId, $hotelBusProId])) {
$this
->connection
->update('destination', [
'code' => $code,
'date_from' => $dateFrom->format('Y-m-d'),
'date_to' => $dateTo->format('Y-m-d'),
'product' => $product,
'pickups' => json_encode($datePickups),
'cost_unit' => $hotel->getCostUnit(),
'country' => $hotel->getCountry(),
'updated_at' => (new \DateTimeImmutable())->format('Y-m-d H:i:s'),
], [
'id' => $id,
'hotel_bus_pro_id' => $hotelBusProId,
])
;
++$updatedCount;
} else {
$this
->connection
->insert('destination', [
'code' => $code,
'bus_pro_id' => $busProId,
'date_from' => $dateFrom->format('Y-m-d'),
'date_to' => $dateTo->format('Y-m-d'),
'product' => $product,
'hotel' => $hotel->getName(),
'hotel_code' => $hotel->getCode(),
'hotel_bus_pro_id' => $hotelBusProId,
'pickups' => json_encode($datePickups),
'cost_unit' => $hotel->getCostUnit(),
'country' => $hotel->getCountry(),
'created_at' => (new \DateTimeImmutable())->format('Y-m-d H:i:s'),
])
;
++$addedCount;
}
}
}
$progressBar->advance();
}
$progressBar->setMessage('Done');
$progressBar->finish();
$io->newLine(2);
if ($warnings) {
$io->warning(array_unique($warnings));
}
$logMessage = 'Added '.$addedCount.' and updated '.$updatedCount.' destinations';
$io->info($logMessage);
$this->logger->info($logMessage);
return Command::SUCCESS;
}
}
+235
View File
@@ -0,0 +1,235 @@
<?php
namespace App\Command;
use App\BusProNet\DataProvider\HotelDataProvider;
use App\BusProNet\DataProvider\PickupDataProvider;
use App\MyEp\Api\ApiClient;
use App\MyEp\Import\DestinationRow;
use App\MyEp\Import\InvalidRowException;
use App\Service\Assignment\PickupDepartureOrder;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Read-only probe of the MyE&P API: does it answer, and does it carry what the import needs.
*
* Writes nothing and touches no database. It exists because the interesting failures in this
* integration are silent ones - a field named `id` where the import reads `busProId`, a time
* in a shape the departure ordering cannot parse - and they are only visible against a real
* response. `app:myep-import` cannot serve as the probe: its own guard passes or fails on the
* hotel payload, and once past it the command writes.
*/
#[AsCommand(
name: 'app:myep-check',
description: 'Checks that the MyE&P API answers and carries the fields the import needs',
)]
class MyEpCheckCommand extends Command
{
public function __construct(
private readonly ApiClient $apiClient,
private readonly HotelDataProvider $hotelDataProvider,
private readonly PickupDataProvider $pickupDataProvider,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->section('Base data');
$hotels = $this->hotelDataProvider->getAll();
$pickups = $this->pickupDataProvider->getAll();
if ([] === $hotels) {
$io->error('No hotels returned - the import would refuse to run.');
return Command::FAILURE;
}
$withCostUnit = count(array_filter($hotels, fn ($h) => null !== $h->getCostUnit()));
$withCountry = count(array_filter($hotels, fn ($h) => null !== $h->getCountryCode()));
$io->definitionList(
['hotels' => (string) count($hotels)],
['with costUnit' => sprintf('%d%s', $withCostUnit, 0 === $withCostUnit ? ' <- import would refuse' : '')],
['with countryCode' => sprintf('%d%s', $withCountry, 0 === $withCountry ? ' <- import would refuse' : '')],
['pickups' => (string) count($pickups)],
);
$io->section('Travel export');
// A whole page rather than one row: the first row often has no boarding points, and an
// unread pickups array is exactly the failure this probe exists to catch.
$payload = $this->apiClient->get('api/exports/travels', ['page' => 1, 'perPage' => 500]);
$meta = $payload['meta'] ?? [];
$io->definitionList(...array_map(
fn (string $key) => [$key => var_export($meta[$key] ?? null, true)],
['total', 'totalPages', 'perPage', 'skipped', 'pickupsWithoutMasterData', 'generatedAt'],
));
$rows = array_values(array_filter((array) ($payload['data'] ?? []), 'is_array'));
if ([] === $rows) {
$io->error('The export returned no rows.');
return Command::FAILURE;
}
$withPickups = array_values(array_filter($rows, fn (array $r) => [] !== ($r['pickups'] ?? [])));
$io->definitionList(
['rows on this page' => (string) count($rows)],
['of them with pickups' => (string) count($withPickups)],
);
$row = $withPickups[0] ?? $rows[0];
// Does `datetime` actually resolve the overnight leg? A coach leaves in the evening and
// keeps boarding through the night, so a 00:30 stop belongs to the day after a 23:30 one.
// If every entry on such a row carries the same calendar date, the field is unresolved and
// ordering by it inverts the route.
$straddling = 0;
$unresolved = [];
foreach ($withPickups as $candidate) {
$times = array_filter(array_column($candidate['pickups'], 'time'));
$dates = array_unique(array_map(
fn (?string $d) => null === $d ? null : substr($d, 0, 10),
array_column($candidate['pickups'], 'datetime'),
));
$late = array_filter($times, fn (string $t) => $t >= '18:00');
$early = array_filter($times, fn (string $t) => $t <= '06:00');
if ([] === $late || [] === $early) {
continue;
}
++$straddling;
if (1 === count($dates)) {
$unresolved[] = $candidate['busProId'];
}
}
$io->definitionList(
['rows straddling midnight' => (string) $straddling],
['of them with one date only' => sprintf('%d%s', count($unresolved), [] === $unresolved ? '' : ' <- datetime unresolved')],
);
// The decisive question is not whether a date looks odd but whether adopting `datetime`
// would reorder a route. Compared against our own anchor-based ordering, which reads the
// bare clock times and is what runs today.
$disagree = [];
foreach ($withPickups as $candidate) {
$pickups = $candidate['pickups'];
if (2 > count($pickups)) {
continue;
}
$legacy = array_column(
PickupDepartureOrder::sort(array_map(
function (array $p): array {
unset($p['datetime']);
return $p;
},
$pickups,
)),
'busProId',
);
$dated = $pickups;
usort($dated, fn (array $a, array $b) => ($a['datetime'] ?? '') <=> ($b['datetime'] ?? ''));
if ($legacy !== array_column($dated, 'busProId')) {
$disagree[] = $candidate['busProId'];
}
}
$io->definitionList(
['rows where datetime order differs' => sprintf(
'%d of %d%s',
count($disagree),
count($withPickups),
[] === $disagree ? '' : ' <- adopting datetime would reorder these',
)],
);
if ([] !== $unresolved) {
$io->warning(sprintf(
'datetime does not roll past midnight on %d of %d straddling rows (e.g. busProId %s). '
.'Ordering by it would put the early-morning stops before the evening departure.',
count($unresolved),
$straddling,
implode(', ', array_slice($unresolved, 0, 5)),
));
}
$resolvedStraddlers = array_values(array_filter(
$withPickups,
function (array $r) use ($unresolved): bool {
$times = array_filter(array_column($r['pickups'], 'time'));
$late = array_filter($times, fn (string $t) => $t >= '18:00');
$early = array_filter($times, fn (string $t) => $t <= '06:00');
return [] !== $late && [] !== $early && false === in_array($r['busProId'], $unresolved, true);
},
));
if ([] !== $resolvedStraddlers) {
$sample = $resolvedStraddlers[0];
$io->writeln(sprintf('<comment>A straddling row where datetime DID roll (busProId %d, dateFrom %s)</comment>', $sample['busProId'], $sample['dateFrom']));
foreach ($sample['pickups'] as $pickup) {
$io->writeln(sprintf(' %-14s %-6s %s', $pickup['city'] ?? '?', $pickup['time'] ?? '-', $pickup['datetime'] ?? '-'));
}
$io->newLine();
}
$io->writeln('<comment>Raw first row</comment>');
$io->writeln(json_encode($row, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$io->section('As the import reads it');
try {
$destinationRow = DestinationRow::fromArray($row);
} catch (InvalidRowException $e) {
$io->error(sprintf('The import would skip this row: %s', $e->getMessage()));
return Command::FAILURE;
}
$io->definitionList(
['busProId' => (string) $destinationRow->busProId],
['code' => var_export($destinationRow->code, true)],
['product' => var_export($destinationRow->product, true)],
['dateFrom' => $destinationRow->dateFrom->format('Y-m-d')],
['dateTo' => $destinationRow->dateTo->format('Y-m-d')],
['hotelBusProId' => (string) $destinationRow->hotelBusProId],
['hotelCode' => var_export($destinationRow->hotelCode, true)],
['hotelName' => var_export($destinationRow->hotelName, true)],
['costUnit' => var_export($destinationRow->costUnit, true)],
['country' => var_export($destinationRow->country, true)],
['pickups' => json_encode($destinationRow->pickups, JSON_UNESCAPED_UNICODE)],
);
if ([] !== $row['pickups'] && [] === $destinationRow->pickups) {
$io->error('The export carries pickups but the import read none - check the id field name.');
return Command::FAILURE;
}
$io->success('MyE&P answers and the import can read the row.');
return Command::SUCCESS;
}
}
+176
View File
@@ -0,0 +1,176 @@
<?php
namespace App\Command;
use App\MyEp\Api\ApiException;
use App\MyEp\Import\DestinationRow;
use App\MyEp\Import\TravelExportClient;
use Doctrine\DBAL\Connection;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Fills the destination table from MyE&P's travel export.
*
* Replaces the Ziel_*.xml parsing this command used to do. MyE&P now owns every part of that:
* it reads BusProNet's German XML, flattens it to one row per travel date x hotel - the pair
* this table is keyed on - joins the hotel and pickup base data in, and resolves the boarding
* times. What is left here is the upsert.
*
* Still raw DBAL rather than the ORM: the rows carry no behaviour, nothing listens for their
* changes, and a Destination is soft deletable, so hydrating 400 entities to write scalars
* onto them would buy nothing.
*/
#[AsCommand(
name: 'app:myep-import',
description: 'Imports travel dates, products and hotels from the MyE&P API',
)]
class MyEpImportCommand extends Command
{
public function __construct(
private readonly Connection $connection,
private readonly TravelExportClient $travelExportClient,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
try {
$export = $this->travelExportClient->fetchAll();
} catch (ApiException $e) {
$io->error('Der Reise-Export konnte nicht von MyE&P geladen werden – Import abgebrochen.');
$this->logger->error('Import aborted: the MyE&P travel export could not be read', [
'reason' => $e->getMessage(),
]);
return Command::FAILURE;
}
// An empty export would otherwise be a run that touches nothing and reports success,
// which reads as "nothing changed upstream" rather than as a failure to read it.
if ([] === $export->rows) {
$io->error('Der Reise-Export von MyE&P enthält keine Reisen – Import abgebrochen.');
$this->logger->error('Import aborted: the MyE&P travel export was empty');
return Command::FAILURE;
}
// Every destination this import touches gets its cost unit and its country written from
// the export, on update as well as on insert. If MyE&P stops reporting those two fields,
// a run would quietly blank them on rows that have them: the cost unit then drops off
// the invoices (App\Service\Pdf\InvoiceApprover) and a missing country code blanks the
// flag icons and takes the row out of the country filters. Refusing to run is the
// recoverable failure; overwriting good data is not.
if ([] !== $missingFields = $this->missingHotelFields($export->rows)) {
$io->error(sprintf(
'Die MyE&P-API liefert keine %s – Import abgebrochen, damit bestehende Werte nicht überschrieben werden.',
implode(' und ', $missingFields),
));
$this->logger->error('Import aborted: the MyE&P travel export carries no '.implode(', ', $missingFields));
return Command::FAILURE;
}
$io->info(sprintf('%d Reisen von MyE&P geladen', count($export->rows)));
// Both are losses MyE&P made silently on its side: a skipped pair is a travel the
// disposition will never offer, and a boarding point without master data reaches the
// form with no town. Logged every run so they get chased instead of settling in.
$this->logger->info('MyE&P travel export read', [
'rows' => count($export->rows),
'skipped' => $export->skipped,
'pickups_without_master_data' => $export->pickupsWithoutMasterData,
'generated_at' => $export->generatedAt,
]);
if (0 < $export->skipped || 0 < $export->pickupsWithoutMasterData) {
$io->warning(sprintf(
'MyE&P hat %d Reise-Hotel-Kombinationen verworfen und %d Zustiege ohne Stammdaten gemeldet.',
$export->skipped,
$export->pickupsWithoutMasterData,
));
}
$now = new \DateTimeImmutable();
$addedCount = 0;
$updatedCount = 0;
$progressBar = $io->createProgressBar(count($export->rows));
$progressBar->setFormat(" %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%\n %message%");
$progressBar->setMessage('Starting');
$progressBar->start();
foreach ($export->rows as $row) {
$progressBar->setMessage(sprintf('%s %s', $row->dateFrom->format('d.m.Y'), $row->product));
$id = $this->connection->fetchOne(
'SELECT id FROM destination WHERE bus_pro_id=? AND hotel_bus_pro_id=?',
[$row->busProId, $row->hotelBusProId],
);
if ($id) {
$this->connection->update('destination', $row->toUpdatePayload($now), ['id' => $id]);
++$updatedCount;
} else {
$this->connection->insert('destination', $row->toInsertPayload($now));
++$addedCount;
}
$progressBar->advance();
}
$progressBar->setMessage('Done');
$progressBar->finish();
$io->newLine(2);
$io->success(sprintf('%d Destinationen angelegt, %d aktualisiert', $addedCount, $updatedCount));
$this->logger->info('MyE&P destination import finished', [
'added' => $addedCount,
'updated' => $updatedCount,
]);
return Command::SUCCESS;
}
/**
* Names the hotel fields MyE&P is not reporting, German labels for the operator.
*
* Asserted across the whole export rather than per row, because a row legitimately has
* neither: only a minority of hotels carry a kostenstelle upstream, and some carry no
* country BusProNet can resolve. An export where not one row has the field is a field
* missing from the response, not a gap in the data.
*
* @param DestinationRow[] $rows
*
* @return list<string>
*/
private function missingHotelFields(array $rows): array
{
$required = [
'Kostenstellen' => static fn (DestinationRow $row): bool => '' !== (string) $row->costUnit,
'Länderkennungen' => static fn (DestinationRow $row): bool => '' !== (string) $row->country,
];
$missing = [];
foreach ($required as $label => $isReported) {
foreach ($rows as $row) {
if ($isReported($row)) {
continue 2;
}
}
$missing[] = $label;
}
return $missing;
}
}
@@ -7,27 +7,51 @@ use App\Model\DestinationDto;
trait DestinationTrait
{
/**
* Resolves the chosen boarding points against the base data.
*
* A stop the base data cannot resolve is kept with null city and street rather than dropped,
* the same choice App\Command\MyEpImportCommand makes for the export's own unresolvable ids:
* it is still a real departure point, and App\Service\Common\PickupOptions falls back to
* "Zustieg {busProId}" for one with no town. Dropping it would hide a departure the coach
* actually makes.
*
* The id comes from the form rather than from the resolved stop, so it survives a lookup
* that does not.
*/
private function mapPickups(DestinationDto $destinationDto): array
{
$pickups = [];
foreach ($destinationDto->getPickups() as $pickupId) {
$pickup = $this->pickupDataProvider->get($pickupId);
$pickups[] = [
'busProId' => $pickup->getBusProId(),
'city' => $pickup->getCity(),
'street' => $pickup->getStreet(),
'time' => $pickup->getTime(),
'busProId' => (int) $pickupId,
'city' => $pickup?->getCity(),
'street' => $pickup?->getStreet(),
'time' => $pickup?->getTime(),
];
}
return $pickups;
}
/**
* @throws \LogicException when the hotel does not resolve
*/
private function updateEntity(Destination $destination, DestinationDto $destinationDto): void
{
$hotel = $this->hotelDataProvider->get($destinationDto->getHotelBusProId());
$pickups = $this->mapPickups($destinationDto);
$hotelBusProId = $destinationDto->getHotelBusProId();
// App\Validator\Constraints\ResolvableHotel is what reports this to the operator, on the
// field and in German, and every caller here runs behind $form->isValid(). This is the
// second line only: a caller that skips validation would otherwise write a destination
// with no house name, no cost unit and no country, and nothing reads those back until an
// invoice is stamped. Failing loudly beats a half built row.
if (null === $hotel = $this->hotelDataProvider->get((int) $hotelBusProId)) {
throw new \LogicException(sprintf('Refusing to write destination %s: hotel %s does not resolve against the MyE&P base data', $destination->getId() ?? 'new', var_export($hotelBusProId, true)));
}
$destination
->setProduct($destinationDto->getProduct())
@@ -37,7 +61,7 @@ trait DestinationTrait
->setHotelCode($hotel->getCode())
->setHotelBusProId($hotel->getBusProId())
->setCountry($destinationDto->getCountry())
->setPickups($pickups)
->setPickups($this->mapPickups($destinationDto))
->setCostUnit($hotel->getCostUnit())
;
}
+3 -3
View File
@@ -63,10 +63,10 @@ class ApplicationFilterType extends AbstractType
'required' => false,
'placeholder' => 'nicht filtern',
'choices' => [
'Österreich' => 'a',
'Österreich' => 'at',
'Schweiz' => 'ch',
'Frankreich' => 'f',
'Italien' => 'i',
'Frankreich' => 'fr',
'Italien' => 'it',
],
])
->add('apply', SubmitType::class, [
+3 -3
View File
@@ -67,10 +67,10 @@ class AssignmentFilterType extends AbstractType
'required' => false,
'placeholder' => 'nicht filtern',
'choices' => [
'Österreich' => 'a',
'Österreich' => 'at',
'Schweiz' => 'ch',
'Frankreich' => 'f',
'Italien' => 'i',
'Frankreich' => 'fr',
'Italien' => 'it',
],
])
->add('apply', SubmitType::class, [
+1 -8
View File
@@ -40,14 +40,7 @@ class DestinationType extends AbstractType
])
->add('country', ChoiceType::class, [
'label' => 'Land',
'choices' => [
'Österreich' => 'a',
'Schweiz' => 'ch',
'Frankreich' => 'f',
'Italien' => 'i',
'Deutschland' => 'd',
'Niederlande' => 'nl',
],
'choices' => DestinationDto::COUNTRIES,
])
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
+27 -1
View File
@@ -3,14 +3,31 @@
namespace App\Model;
use App\Entity\Destination;
use App\Validator\Constraints as AppAssert;
use Symfony\Component\Validator\Constraints as Assert;
class DestinationDto
{
/**
* The countries a destination can be authored in, as German label => ISO-3166-1 alpha-2.
*
* Both the form's choice list and the constraint below read this one map. They used to
* spell the codes out twice and drifted apart the moment the stored values moved to
* ISO-2: the form offered 'at' while the constraint still only accepted 'a'.
*/
public const COUNTRIES = [
'Österreich' => 'at',
'Schweiz' => 'ch',
'Frankreich' => 'fr',
'Italien' => 'it',
'Deutschland' => 'de',
'Niederlande' => 'nl',
];
#[Assert\NotBlank(message: 'Bitte angeben')]
private ?string $product = null;
#[Assert\Choice(choices: ['a', 'ch', 'd', 'f', 'i', 'nl'], message: 'Ungültige Auswahl')]
#[Assert\Choice(callback: 'countryCodes', message: 'Ungültige Auswahl')]
private ?string $country = null;
#[Assert\NotNull(message: 'Bitte das Beginndatum angeben')]
@@ -20,6 +37,7 @@ class DestinationDto
private ?\DateTimeImmutable $dateTo = null;
#[Assert\NotBlank(message: 'Bitte angeben')]
#[AppAssert\ResolvableHotel]
private ?string $hotelBusProId = null;
private ?string $costUnit = null;
@@ -46,6 +64,14 @@ class DestinationDto
return $instance;
}
/**
* @return list<string>
*/
public static function countryCodes(): array
{
return array_values(self::COUNTRIES);
}
public function getProduct(): ?string
{
return $this->product;
+139
View File
@@ -0,0 +1,139 @@
<?php
namespace App\MyEp\Api;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface as TransportException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Obtains and caches the client_credentials access token for the MyE&P API.
*
* MyE&P issues short-lived tokens (ten minutes), so a token is kept in the shared
* cache until shortly before it expires rather than requested per call.
*/
class AccessTokenProvider
{
private const CACHE_KEY = 'myep.api.access_token';
/**
* Assumed token lifetime when the response omits expires_in.
*/
private const DEFAULT_LIFETIME = 600;
/**
* Dropped from every lifetime so a token is never handed out in the seconds
* before it expires.
*/
private const EXPIRY_MARGIN = 60;
private const MINIMUM_LIFETIME = 30;
private array $config;
public function __construct(
private readonly HttpClientInterface $myepClient,
private readonly CacheItemPoolInterface $cache,
private readonly LoggerInterface $logger,
array $options,
) {
$this->config = $this->resolveOptions($options);
}
/**
* @throws ApiException
*/
public function getToken(): string
{
try {
$item = $this->cache->getItem(self::CACHE_KEY);
} catch (InvalidArgumentException $e) {
throw new ApiException('Unable to read the cached MyE&P access token', 0, $e);
}
if ($item->isHit()) {
return $item->get();
}
[$token, $lifetime] = $this->requestToken();
$item->set($token);
$item->expiresAfter($lifetime);
$this->cache->save($item);
return $token;
}
/**
* Drops the cached token so the next call fetches a fresh one. Used when the API
* rejects a token the cache still considered valid.
*/
public function invalidate(): void
{
try {
$this->cache->deleteItem(self::CACHE_KEY);
} catch (InvalidArgumentException) {
// the key is a constant, so it cannot be malformed; nothing to recover from
}
}
/**
* @return array{0: string, 1: int} the token and the seconds it may be cached for
*
* @throws ApiException
*/
private function requestToken(): array
{
try {
$response = $this->myepClient->request('POST', $this->config['token_path'], [
'body' => [
'grant_type' => 'client_credentials',
'client_id' => $this->config['client_id'],
'client_secret' => $this->config['client_secret'],
'scope' => $this->config['scope'],
],
]);
$statusCode = $response->getStatusCode();
$payload = $response->toArray(false);
} catch (TransportException $e) {
$this->logger->error('Unable to obtain a MyE&P access token', [
'client_id' => $this->config['client_id'],
'exception' => $e,
]);
throw new ApiException('Unable to obtain a MyE&P access token', 0, $e);
}
$token = $payload['access_token'] ?? null;
if (200 !== $statusCode || false === is_string($token) || '' === $token) {
$this->logger->error('MyE&P rejected the access token request', [
'client_id' => $this->config['client_id'],
'status_code' => $statusCode,
'error' => $payload['error'] ?? null,
]);
throw new ApiException('MyE&P rejected the access token request with status '.$statusCode);
}
$expiresIn = (int) ($payload['expires_in'] ?? self::DEFAULT_LIFETIME);
return [$token, max(self::MINIMUM_LIFETIME, $expiresIn - self::EXPIRY_MARGIN)];
}
private function resolveOptions(array $options): array
{
$optionsResolver = new OptionsResolver();
$optionsResolver->setRequired(['client_id', 'client_secret']);
$optionsResolver->setDefaults([
'token_path' => 'token',
'scope' => 'api',
]);
return $optionsResolver->resolve($options);
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace App\MyEp\Api;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface as TransportException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
/**
* Reads the MyE&P JSON API. Every response is validated here so that callers only
* ever see a decoded payload or an ApiException.
*/
class ApiClient
{
public function __construct(
private readonly HttpClientInterface $myepClient,
private readonly AccessTokenProvider $tokens,
private readonly LoggerInterface $logger,
) {
}
/**
* @throws ApiException
*/
public function get(string $path, array $query = []): array
{
$response = $this->send($path, $query);
if (Response::HTTP_UNAUTHORIZED === $this->statusOf($response, $path)) {
// tokens live ten minutes, so one expiring mid-run is routine rather than a fault
$this->tokens->invalidate();
$response = $this->send($path, $query);
}
$statusCode = $this->statusOf($response, $path);
if (Response::HTTP_FORBIDDEN === $statusCode) {
$this->logger->error('MyE&P denied a request for lack of scope', ['path' => $path]);
throw new ApiException(sprintf('MyE&P denied "%s": the API client lacks the required scope', $path));
}
if ($statusCode < 200 || $statusCode >= 300) {
$this->logger->error('MyE&P returned an unexpected status', [
'path' => $path,
'status_code' => $statusCode,
]);
throw new ApiException(sprintf('MyE&P returned status %d for "%s"', $statusCode, $path));
}
return $this->decode($response, $path);
}
private function send(string $path, array $query): ResponseInterface
{
try {
return $this->myepClient->request('GET', $path, [
'auth_bearer' => $this->tokens->getToken(),
'query' => $query,
]);
} catch (TransportException $e) {
$this->logger->error('Request to MyE&P failed', ['path' => $path, 'exception' => $e]);
throw new ApiException(sprintf('Request to MyE&P endpoint "%s" failed', $path), 0, $e);
}
}
private function statusOf(ResponseInterface $response, string $path): int
{
try {
return $response->getStatusCode();
} catch (TransportException $e) {
$this->logger->error('Request to MyE&P failed', ['path' => $path, 'exception' => $e]);
throw new ApiException(sprintf('Request to MyE&P endpoint "%s" failed', $path), 0, $e);
}
}
private function decode(ResponseInterface $response, string $path): array
{
try {
$payload = $response->toArray(false);
} catch (TransportException $e) {
$this->logger->error('Unreadable response from MyE&P', ['path' => $path, 'exception' => $e]);
throw new ApiException(sprintf('Unreadable response from MyE&P endpoint "%s"', $path), 0, $e);
}
// some MyE&P endpoints report upstream failures in the body while still
// answering with 200, so the payload decides, not the status code
if (isset($payload['error'])) {
$this->logger->error('MyE&P reported an error', [
'path' => $path,
'error' => $payload['error'],
]);
throw new ApiException(sprintf('MyE&P reported an error for "%s": %s', $path, (string) $payload['error']));
}
return $payload;
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace App\MyEp\Api;
class ApiException extends \RuntimeException
{
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\MyEp\Api;
/**
* Normalizes the country code MyE&P resolves for a hotel.
*
* MyE&P maps the raw BusProNet abbreviations (D, A, AUT, DEU, …) to ISO-3166-1
* alpha-2 and reports the result as countryCode. Anything that is not a two letter
* code is dropped rather than stored: the value goes into a two character column and
* addresses a flag icon, so a half-mapped token is worse than no country at all.
*/
final class CountryCode
{
public static function normalize(mixed $value): ?string
{
if (false === is_string($value)) {
return null;
}
$code = strtolower(trim($value));
return 1 === preg_match('/^[a-z]{2}$/', $code) ? $code : null;
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
namespace App\MyEp\Api;
use App\BusProNet\Model\Country;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Pickup;
use Psr\Log\LoggerInterface;
/**
* Turns MyE&P list responses into the BusProNet models the application already works
* with, keyed the way the data providers expose them.
*
* The id MyE&P reports for hotels and pickups is the BusProNet idbuspro, so it fills
* both the id and the busProId of the models.
*/
class ResponseMapper
{
public function __construct(private readonly LoggerInterface $logger)
{
}
/**
* @return array<int, Hotel> keyed by busProId
*/
public function mapHotels(array $rows): array
{
$hotels = [];
foreach ($rows as $row) {
if (null === $busProId = $this->readBusProId($row, 'hotel')) {
continue;
}
$hotel = new Hotel();
$hotel
->setBusProId($busProId)
->setCode($this->readString($row, 'code'))
->setName($this->readString($row, 'name'))
->setCountry($this->readString($row, 'country'))
->setCountryCode($this->readCountryCode($row))
->setCostUnit($this->readString($row, 'costUnit'))
;
$hotels[$busProId] = $hotel;
}
return $hotels;
}
/**
* @return array<int, Pickup> keyed by busProId
*/
public function mapPickups(array $rows): array
{
$pickups = [];
foreach ($rows as $row) {
if (null === $busProId = $this->readBusProId($row, 'pickup')) {
continue;
}
$pickup = new Pickup();
$pickup
->setId($busProId)
->setBusProId($busProId)
->setCode($this->readString($row, 'code'))
->setCity($this->readString($row, 'city'))
->setStreet($this->readString($row, 'street'))
;
// the time is a property of a boarding stop on a date, never of the stop itself
$pickups[$busProId] = $pickup;
}
return $pickups;
}
/**
* @return array<string, Country> keyed by token
*/
public function mapCountries(array $rows): array
{
$countries = [];
foreach ($rows as $row) {
$token = is_array($row) ? $this->readString($row, 'token') : null;
if (null === $token || '' === $token) {
$this->logger->warning('Skipped a MyE&P country without a token', ['row' => $row]);
continue;
}
$country = new Country();
$country
->setName($this->readString($row, 'name'))
->setToken($token)
->setNationality($this->readString($row, 'nationality'))
;
$countries[$token] = $country;
}
return $countries;
}
private function readCountryCode(array $row): ?string
{
$countryCode = CountryCode::normalize($row['countryCode'] ?? null);
if (null === $countryCode && null !== ($row['country'] ?? null)) {
$this->logger->warning('MyE&P reported a hotel country it could not map to ISO', [
'id' => $row['id'] ?? null,
'country' => $row['country'],
'countryCode' => $row['countryCode'] ?? null,
]);
}
return $countryCode;
}
private function readBusProId(mixed $row, string $type): ?int
{
$busProId = is_array($row) ? (int) ($row['id'] ?? 0) : 0;
if (0 === $busProId) {
$this->logger->warning(sprintf('Skipped a MyE&P %s without an id', $type), ['row' => $row]);
return null;
}
return $busProId;
}
private function readString(array $row, string $key): ?string
{
$value = $row[$key] ?? null;
return null === $value ? null : (string) $value;
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
namespace App\MyEp\Cache;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
/**
* Caches a value and keeps the last successful one around far longer, so a MyE&P
* outage degrades to slightly stale master data instead of empty dropdowns.
*
* Symfony's cache contract cannot express this: it discards the item when the
* callback throws, which is exactly the case that needs the previous value.
*/
class StaleWhileErrorCache
{
private const LAST_GOOD_SUFFIX = '.last_good';
/**
* How long a served stale value suppresses further upstream attempts. Without it
* every call during an outage would try again, since the fresh key stays empty.
*/
private const RETRY_DELAY = 60;
public function __construct(
private readonly CacheItemPoolInterface $cache,
private readonly LoggerInterface $logger,
private readonly int $staleLifetime = 604800,
) {
}
/**
* @param callable(): array $producer
*/
public function get(string $key, int $ttl, callable $producer): array
{
try {
$fresh = $this->cache->getItem($key);
} catch (InvalidArgumentException $e) {
$this->logger->error('Unusable MyE&P cache key', ['key' => $key, 'exception' => $e]);
return $this->produceUncached($key, $producer);
}
if ($fresh->isHit()) {
return $fresh->get();
}
try {
$value = $producer();
} catch (\Throwable $e) {
return $this->serveStale($key, $fresh, $e);
}
$fresh->set($value);
$fresh->expiresAfter($ttl);
$this->cache->save($fresh);
$this->saveLastGood($key, $value);
return $value;
}
private function serveStale(string $key, CacheItemInterface $fresh, \Throwable $e): array
{
try {
$lastGood = $this->cache->getItem($key.self::LAST_GOOD_SUFFIX);
} catch (InvalidArgumentException) {
$lastGood = null;
}
if (null === $lastGood || false === $lastGood->isHit()) {
$this->logger->error('MyE&P request failed and no previous data is cached', [
'key' => $key,
'exception' => $e,
]);
return [];
}
$this->logger->error('MyE&P request failed, serving the last known data', [
'key' => $key,
'exception' => $e,
]);
$stale = $lastGood->get();
$fresh->set($stale);
$fresh->expiresAfter(self::RETRY_DELAY);
$this->cache->save($fresh);
return $stale;
}
private function saveLastGood(string $key, array $value): void
{
try {
$lastGood = $this->cache->getItem($key.self::LAST_GOOD_SUFFIX);
} catch (InvalidArgumentException) {
return;
}
$lastGood->set($value);
$lastGood->expiresAfter($this->staleLifetime);
$this->cache->save($lastGood);
}
private function produceUncached(string $key, callable $producer): array
{
try {
return $producer();
} catch (\Throwable $e) {
$this->logger->error('MyE&P request failed', ['key' => $key, 'exception' => $e]);
return [];
}
}
}
+161
View File
@@ -0,0 +1,161 @@
<?php
namespace App\MyEp\Import;
use App\MyEp\Api\CountryCode;
/**
* One travel date at one hotel, as the MyE&P travel export reports it. This is the
* unit the destination table is keyed on.
*/
class DestinationRow
{
public function __construct(
public readonly int $busProId,
public readonly string $code,
public readonly string $product,
public readonly \DateTimeImmutable $dateFrom,
public readonly \DateTimeImmutable $dateTo,
public readonly int $hotelBusProId,
public readonly string $hotelCode,
public readonly string $hotelName,
public readonly ?string $costUnit,
/** lowercase ISO-3166-1 alpha-2, null when MyE&P could not resolve one */
public readonly ?string $country,
public readonly array $pickups,
) {
}
/**
* @throws InvalidRowException
*/
public static function fromArray(array $data): self
{
$hotel = $data['hotel'] ?? null;
if (false === is_array($hotel)) {
throw new InvalidRowException('Travel export row without a hotel');
}
$busProId = (int) ($data['busProId'] ?? 0);
$hotelBusProId = (int) ($hotel['busProId'] ?? 0);
if (0 === $busProId || 0 === $hotelBusProId) {
throw new InvalidRowException(sprintf('Travel export row with an unusable id pair (%d, %d)', $busProId, $hotelBusProId));
}
return new self(
$busProId,
(string) ($data['code'] ?? ''),
(string) ($data['product'] ?? ''),
self::readDate($data, 'dateFrom'),
self::readDate($data, 'dateTo'),
$hotelBusProId,
(string) ($hotel['code'] ?? ''),
(string) ($hotel['name'] ?? ''),
self::readNullableString($hotel, 'costUnit'),
CountryCode::normalize($hotel['countryCode'] ?? null),
self::readPickups($data['pickups'] ?? []),
);
}
/**
* The columns an existing destination is refreshed with. The hotel name and code
* are part of it because they do change upstream, and rows that keep an outdated
* name drop out of the house matching.
*/
public function toUpdatePayload(\DateTimeImmutable $now): array
{
return [
'code' => $this->code,
'date_from' => $this->dateFrom->format('Y-m-d'),
'date_to' => $this->dateTo->format('Y-m-d'),
'product' => $this->product,
'hotel' => $this->hotelName,
'hotel_code' => $this->hotelCode,
'pickups' => json_encode($this->pickups),
'cost_unit' => $this->costUnit,
'country' => $this->country,
'updated_at' => $now->format('Y-m-d H:i:s'),
];
}
public function toInsertPayload(\DateTimeImmutable $now): array
{
return [
'code' => $this->code,
'bus_pro_id' => $this->busProId,
'date_from' => $this->dateFrom->format('Y-m-d'),
'date_to' => $this->dateTo->format('Y-m-d'),
'product' => $this->product,
'hotel' => $this->hotelName,
'hotel_code' => $this->hotelCode,
'hotel_bus_pro_id' => $this->hotelBusProId,
'pickups' => json_encode($this->pickups),
'cost_unit' => $this->costUnit,
'country' => $this->country,
'created_at' => $now->format('Y-m-d H:i:s'),
];
}
/**
* @throws InvalidRowException
*/
private static function readDate(array $data, string $key): \DateTimeImmutable
{
$value = $data[$key] ?? null;
if (false === is_string($value) || false === $date = \DateTimeImmutable::createFromFormat('!Y-m-d', $value)) {
throw new InvalidRowException(sprintf('Travel export row with an unreadable %s', $key));
}
return $date;
}
/**
* The shape here is what the destination table stores and what
* App\BusProNet\Model\Pickup::fromArray() reads back, which ignores the extra `datetime`.
*
* `datetime` is not optional decoration. MyE&P sends `time` as a bare HH:MM, so without it
* App\Service\Assignment\PickupDepartureOrder never finds a dated entry, its anchor is null
* and it falls back to sorting on the clock alone - which puts a 00:30 boarding point ahead
* of the 22:00 departure on every route that runs through the night.
*/
private static function readPickups(mixed $pickups): array
{
if (false === is_array($pickups)) {
return [];
}
$mapped = [];
foreach ($pickups as $pickup) {
if (false === is_array($pickup)) {
continue;
}
$busProId = (int) ($pickup['busProId'] ?? 0);
if (0 === $busProId) {
continue;
}
$mapped[] = [
'busProId' => $busProId,
'city' => self::readNullableString($pickup, 'city'),
'street' => self::readNullableString($pickup, 'street'),
'time' => self::readNullableString($pickup, 'time'),
'datetime' => self::readNullableString($pickup, 'datetime'),
];
}
return $mapped;
}
private static function readNullableString(array $data, string $key): ?string
{
$value = $data[$key] ?? null;
return null === $value ? null : (string) $value;
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App\MyEp\Import;
/**
* A single unusable row of the travel export. Thrown per row so the import can skip
* it and carry on instead of losing the whole run.
*/
class InvalidRowException extends \RuntimeException
{
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\MyEp\Import;
/**
* The travel export as one run of the import sees it: its rows and what MyE&P dropped building them.
*
* The counters come from the first page's meta and describe the whole export, not the page, so
* reading them once is correct. They matter because both are silent losses: a skipped row is a
* travel the disposition will never offer, and a pickup without master data is a boarding point
* with no town or street. The import logs them per run so the ids can be chased upstream rather
* than quietly becoming permanent.
*/
final readonly class TravelExport
{
/**
* @param DestinationRow[] $rows
* @param int $skipped date x hotel pairs MyE&P dropped as unusable
* @param int $pickupsWithoutMasterData distinct pickup ids absent from zustiege.xml
*/
public function __construct(
public array $rows,
public int $skipped,
public int $pickupsWithoutMasterData,
public ?string $generatedAt,
) {
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace App\MyEp\Import;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ApiException;
use Psr\Log\LoggerInterface;
/**
* Reads the full travel export from MyE&P, one page at a time.
*/
class TravelExportClient
{
private const PATH = 'api/exports/travels';
private const PER_PAGE = 500;
/**
* Stops a malformed meta block from turning the import into an endless loop.
*/
private const MAX_PAGES = 100;
public function __construct(
private readonly ApiClient $apiClient,
private readonly LoggerInterface $logger,
) {
}
/**
* @throws ApiException
*/
public function fetchAll(): TravelExport
{
$rows = [];
$page = 1;
$totalPages = 1;
$meta = [];
do {
$payload = $this->apiClient->get(self::PATH, [
'page' => $page,
'perPage' => self::PER_PAGE,
]);
$data = $payload['data'] ?? null;
if (false === is_array($data)) {
throw new ApiException('The MyE&P travel export did not contain a data list');
}
foreach ($data as $item) {
if (false === is_array($item)) {
continue;
}
try {
$rows[] = DestinationRow::fromArray($item);
} catch (InvalidRowException $e) {
$this->logger->warning('Skipped an unusable travel export row', [
'reason' => $e->getMessage(),
'row' => $item,
]);
}
}
// The counters repeat unchanged on every page, so the first one answers for the run.
$meta = [] === $meta ? (array) ($payload['meta'] ?? []) : $meta;
$totalPages = max(1, (int) ($payload['meta']['totalPages'] ?? 1));
++$page;
} while ($page <= $totalPages && $page <= self::MAX_PAGES && [] !== $data);
if ($totalPages > self::MAX_PAGES) {
$this->logger->error('The MyE&P travel export reported more pages than are read', [
'total_pages' => $totalPages,
'max_pages' => self::MAX_PAGES,
]);
}
return new TravelExport(
$rows,
(int) ($meta['skipped'] ?? 0),
(int) ($meta['pickupsWithoutMasterData'] ?? 0),
isset($meta['generatedAt']) ? (string) $meta['generatedAt'] : null,
);
}
}
+17 -18
View File
@@ -12,7 +12,6 @@ use App\Security\OAuth2\MyEpClient;
use Doctrine\ORM\EntityManagerInterface;
use Flagception\Manager\FeatureManagerInterface;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
@@ -26,6 +25,8 @@ use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface as HttpExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class MyEpAuthenticator extends AbstractAuthenticator
{
@@ -46,6 +47,7 @@ class MyEpAuthenticator extends AbstractAuthenticator
public function __construct(
private readonly MyEpClient $client,
private readonly HttpClientInterface $myepClient,
private readonly UserDataHandler $userDataHandler,
private readonly EntityManagerInterface $entityManager,
private readonly UrlGeneratorInterface $urlGenerator,
@@ -84,25 +86,22 @@ class MyEpAuthenticator extends AbstractAuthenticator
throw new CustomUserMessageAuthenticationException('Login via MyE&P nicht möglich');
}
// A plain bearer request over the shared MyE&P client, so it inherits its
// timeouts and transport retries. It deliberately does not go through
// App\MyEp\Api\ApiClient: this token was just minted for this one request, so
// there is no cached token to renew on a 401, and every failure here ends in
// the same message anyway. Logging stays on the audit channel, unlike the
// machine to machine traffic - a login attempt belongs in the audit trail.
try {
$provider = $this->client->getProvider();
$url = $provider->getResourceOwnerDetailsUrl($accessToken);
$userinfoRequest = $provider->getAuthenticatedRequest('GET', $url, $accessToken, [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
],
$response = $this->myepClient->request('GET', 'api/userinfo', [
'auth_bearer' => $accessToken->getToken(),
'headers' => ['Accept' => 'application/json'],
]);
$userinfo = $response->toArray();
} catch (HttpExceptionInterface $e) {
$this->logger->error('Login via MyE&P failed due to unexpected userinfo response', [
'exception' => $e,
]);
$response = $provider->getHttpClient()->sendRequest($userinfoRequest);
} catch (ClientExceptionInterface $e) {
$this->logger->error('Login via MyE&P failed due to unexpected userinfo response');
throw new CustomUserMessageAuthenticationException('Login via MyE&P nicht möglich');
}
$userinfo = json_decode($response->getBody(), true);
if (false === is_array($userinfo)) {
$this->logger->error('Login via MyE&P failed due to unreadable userinfo payload');
throw new CustomUserMessageAuthenticationException('Login via MyE&P nicht möglich');
}
@@ -61,6 +61,22 @@ abstract class AbstractFilterHandler
abstract protected function saveFilterSettings(AbstractFilterDto $filterDto): void;
/**
* Country filters used to be stored as the raw BusProNet abbreviations, which the
* destination table has since moved off. A session written before that switch would
* otherwise keep filtering for a value no destination carries any more.
*/
protected function toIsoCountry(?string $country): ?string
{
return match ($country) {
'a' => 'at',
'd' => 'de',
'f' => 'fr',
'i' => 'it',
default => $country,
};
}
protected function getSession(): SessionInterface
{
return $this->requestStack->getSession();
@@ -49,7 +49,7 @@ class ApplicationFilterHandler extends AbstractFilterHandler
$filterDto->setIncludePast((bool) $data['include_past']);
}
if (isset($data['country'])) {
$filterDto->setCountry($data['country']);
$filterDto->setCountry($this->toIsoCountry($data['country']));
}
if (isset($data['teamer_name'])) {
$filterDto->setTeamerName($data['teamer_name']);
@@ -49,7 +49,7 @@ class AssignmentFilterHandler extends AbstractFilterHandler
$filterDto->setIncludePast((bool) $data['include_past']);
}
if (isset($data['country'])) {
$filterDto->setCountry($data['country']);
$filterDto->setCountry($this->toIsoCountry($data['country']));
}
if (isset($data['teamer_name'])) {
$filterDto->setTeamerName($data['teamer_name']);
@@ -0,0 +1,21 @@
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* The chosen hotel must still resolve against MyE&P's base data.
*
* Everything a destination records about its house is derived from that lookup - name, code,
* cost unit, country - so an id that no longer resolves cannot produce a complete row. It used
* to reach App\Controller\Administrative\System\Destination\DestinationTrait::updateEntity()
* and fail there on a null, which is a 500 on a form submit rather than a message on a field.
*/
#[\Attribute]
class ResolvableHotel extends Constraint
{
public string $unknownMessage = 'Dieser Vertragspartner ist nicht mehr verfügbar';
public string $unavailableMessage = 'Die Stammdaten sind gerade nicht erreichbar – bitte später erneut versuchen';
}
@@ -0,0 +1,40 @@
<?php
namespace App\Validator\Constraints;
use App\BusProNet\DataProvider\HotelDataProvider;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ResolvableHotelValidator extends ConstraintValidator
{
public function __construct(private readonly HotelDataProvider $hotelDataProvider)
{
}
public function validate(mixed $value, Constraint $constraint): void
{
if (false === $constraint instanceof ResolvableHotel) {
return;
}
// Whether a hotel was chosen at all is NotBlank's business, not this one's.
if (null === $value || '' === $value) {
return;
}
// An empty list is MyE&P being unreachable rather than a bad choice: StaleWhileErrorCache
// answers [] instead of throwing, so this is the only place the two are still
// distinguishable. Reporting an outage as an invalid selection sends the operator looking
// for a different answer when the one they gave was right.
if ([] === $hotels = $this->hotelDataProvider->getAll()) {
$this->context->buildViolation($constraint->unavailableMessage)->addViolation();
return;
}
if (false === isset($hotels[(int) $value])) {
$this->context->buildViolation($constraint->unknownMessage)->addViolation();
}
}
}
@@ -0,0 +1,94 @@
<?php
namespace App\Tests\BusProNet\DataProvider;
use App\BusProNet\DataProvider\CountryDataProvider;
use App\MyEp\Api\AccessTokenProvider;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ResponseMapper;
use App\MyEp\Cache\StaleWhileErrorCache;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class CountryDataProviderTest extends TestCase
{
public function testCountriesAreKeyedByTheRawToken(): void
{
$provider = $this->provider([$this->countriesResponse()]);
$countries = $provider->getAll();
// the token, not an ISO code: this is the vocabulary a hotel's country and a
// teamer's nationality join against
$this->assertEquals(['D', 'A', 'CH'], array_keys($countries));
$this->assertEquals('Deutschland', $countries['D']->getName());
$this->assertEquals('deutsch', $countries['D']->getNationality());
}
public function testGetResolvesByTokenAndToleratesNull(): void
{
$provider = $this->provider([$this->countriesResponse()]);
$this->assertEquals('Österreich', $provider->get('A')->getName());
$this->assertNull($provider->get('XX'));
$this->assertNull($provider->get(null));
}
public function testACountryWithoutATokenIsSkipped(): void
{
$provider = $this->provider([new MockResponse(json_encode([
['id' => 1, 'name' => 'Ohne Token'],
['id' => 2, 'name' => 'Schweiz', 'token' => 'CH'],
]))]);
$this->assertEquals(['CH'], array_keys($provider->getAll()));
}
public function testAFailingRequestServesTheLastKnownCountries(): void
{
$pool = new ArrayAdapter();
$this->provider([$this->countriesResponse()], $pool)->getAll();
$pool->deleteItem('myep_countries');
$failing = $this->provider([new MockResponse('', ['http_code' => 503])], $pool);
$this->assertCount(3, $failing->getAll());
}
private function countriesResponse(): MockResponse
{
return new MockResponse(json_encode([
['id' => 1, 'name' => 'Deutschland', 'token' => 'D', 'nationality' => 'deutsch'],
['id' => 2, 'name' => 'Österreich', 'token' => 'A', 'nationality' => 'österreichisch'],
['id' => 3, 'name' => 'Schweiz', 'token' => 'CH', 'nationality' => 'schweizerisch'],
]));
}
/**
* @param list<MockResponse> $responses
*/
private function provider(array $responses, ?ArrayAdapter $pool = null): CountryDataProvider
{
$pool ??= new ArrayAdapter();
$logger = new NullLogger();
$httpClient = new MockHttpClient(array_merge(
[new MockResponse(json_encode(['access_token' => 'token', 'expires_in' => 600]))],
$responses,
));
$tokens = new AccessTokenProvider($httpClient, new ArrayAdapter(), $logger, [
'client_id' => 'id',
'client_secret' => 'secret',
]);
return new CountryDataProvider(
new ApiClient($httpClient, $tokens, $logger),
new ResponseMapper($logger),
new StaleWhileErrorCache($pool, $logger),
);
}
}
@@ -0,0 +1,131 @@
<?php
namespace App\Tests\BusProNet\DataProvider;
use App\BusProNet\DataProvider\HotelDataProvider;
use App\MyEp\Api\AccessTokenProvider;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ResponseMapper;
use App\MyEp\Cache\StaleWhileErrorCache;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class HotelDataProviderTest extends TestCase
{
public function testHotelsAreKeyedByBusProId(): void
{
$provider = $this->provider([$this->hotelsResponse()]);
$hotels = $provider->getAll();
$this->assertEquals([163959, 11223], array_keys($hotels));
$this->assertEquals('Sportclub Jenatsch', $hotels[163959]->getName());
// MyE&P reports the BusProNet idbuspro as its id, and busProId is the only property
// that holds it now - the model used to carry the same number twice
$this->assertEquals(163959, $hotels[163959]->getBusProId());
$this->assertEquals('4711', $hotels[163959]->getCostUnit());
$this->assertEquals('CH', $hotels[163959]->getCountry());
$this->assertEquals('ch', $hotels[163959]->getCountryCode());
}
public function testAnUnmappableCountryCodeBecomesNull(): void
{
$provider = $this->provider([$this->hotelsResponse()]);
// "AUT" is what MyE&P could not map; it must not reach the two character column
$this->assertNull($provider->getAll()[11223]->getCountryCode());
$this->assertEquals('AUT', $provider->getAll()[11223]->getCountry());
}
public function testAFailingRequestServesTheLastKnownHotels(): void
{
$pool = new ArrayAdapter();
$provider = $this->provider([$this->hotelsResponse()], $pool);
$this->assertCount(2, $provider->getAll());
// the fresh key is gone but the last known good one is not, which is the whole
// point: an outage must not empty the destination form's hotel list
$pool->deleteItem('myep_hotels');
$failing = $this->provider([new MockResponse('', ['http_code' => 503])], $pool);
$this->assertCount(2, $failing->getAll());
}
public function testAFailingRequestWithoutAnyCachedDataYieldsNothing(): void
{
$provider = $this->provider([new MockResponse('', ['http_code' => 503])]);
$this->assertEquals([], $provider->getAll());
}
public function testFindByCodeMatchesOnEitherEnd(): void
{
$provider = $this->provider([$this->hotelsResponse()]);
$this->assertCount(1, $provider->findByCode('LPJ'));
$this->assertCount(1, $provider->findByCode('GR'));
$this->assertCount(0, $provider->findByCode('XXX'));
}
public function testAHotelWithoutACodeIsSkippedByFindByCode(): void
{
$provider = $this->provider([new MockResponse(json_encode([
['id' => 1, 'name' => 'Ohne Code'],
]))]);
$this->assertEquals([], $provider->findByCode('SSL'));
}
private function hotelsResponse(): MockResponse
{
return new MockResponse(json_encode([
[
'id' => 163959,
'code' => 'LPJGR',
'name' => 'Sportclub Jenatsch',
'city' => 'Lenzerheide',
'street' => 'Voa Principala 1',
'phone' => '+41 81 000 00 00',
'costUnit' => '4711',
'country' => 'CH',
'countryCode' => 'ch',
],
[
'id' => 11223,
'code' => 'SSLAT',
'name' => 'Haus Sonnenschein',
'country' => 'AUT',
'countryCode' => 'AUT',
],
]));
}
/**
* @param list<MockResponse> $responses
*/
private function provider(array $responses, ?ArrayAdapter $pool = null): HotelDataProvider
{
$pool ??= new ArrayAdapter();
$logger = new NullLogger();
$httpClient = new MockHttpClient(array_merge(
[new MockResponse(json_encode(['access_token' => 'token', 'expires_in' => 600]))],
$responses,
));
$tokens = new AccessTokenProvider($httpClient, new ArrayAdapter(), $logger, [
'client_id' => 'id',
'client_secret' => 'secret',
]);
return new HotelDataProvider(
new ApiClient($httpClient, $tokens, $logger),
new ResponseMapper($logger),
new StaleWhileErrorCache($pool, $logger),
);
}
}
@@ -0,0 +1,91 @@
<?php
namespace App\Tests\BusProNet\DataProvider;
use App\BusProNet\DataProvider\PickupDataProvider;
use App\MyEp\Api\AccessTokenProvider;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ResponseMapper;
use App\MyEp\Cache\StaleWhileErrorCache;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class PickupDataProviderTest extends TestCase
{
public function testPickupsAreKeyedByBusProId(): void
{
$provider = $this->provider([$this->pickupsResponse()]);
$pickups = $provider->getAll();
$this->assertEquals([4, 27], array_keys($pickups));
$this->assertEquals('Karlsruhe', $pickups[4]->getCity());
$this->assertEquals('A5 - Autohof Bruchsal', $pickups[4]->getStreet());
$this->assertEquals(4, $pickups[4]->getBusProId());
}
public function testGetResolvesASingleBoardingPoint(): void
{
$provider = $this->provider([$this->pickupsResponse()]);
$this->assertEquals('Karlsruhe', $provider->get(4)->getCity());
$this->assertNull($provider->get(999));
}
public function testAPickupWithoutAnIdIsSkipped(): void
{
$provider = $this->provider([new MockResponse(json_encode([
['city' => 'Nirgendwo'],
['id' => 27, 'city' => 'Stuttgart'],
]))]);
$this->assertEquals([27], array_keys($provider->getAll()));
}
public function testAFailingRequestServesTheLastKnownPickups(): void
{
$pool = new ArrayAdapter();
$this->provider([$this->pickupsResponse()], $pool)->getAll();
$pool->deleteItem('myep_pickups');
$failing = $this->provider([new MockResponse('', ['http_code' => 503])], $pool);
$this->assertCount(2, $failing->getAll());
}
private function pickupsResponse(): MockResponse
{
return new MockResponse(json_encode([
['id' => 4, 'code' => '298', 'city' => 'Karlsruhe', 'street' => 'A5 - Autohof Bruchsal'],
['id' => 27, 'code' => '301', 'city' => 'Stuttgart', 'street' => 'Flughafen'],
]));
}
/**
* @param list<MockResponse> $responses
*/
private function provider(array $responses, ?ArrayAdapter $pool = null): PickupDataProvider
{
$pool ??= new ArrayAdapter();
$logger = new NullLogger();
$httpClient = new MockHttpClient(array_merge(
[new MockResponse(json_encode(['access_token' => 'token', 'expires_in' => 600]))],
$responses,
));
$tokens = new AccessTokenProvider($httpClient, new ArrayAdapter(), $logger, [
'client_id' => 'id',
'client_secret' => 'secret',
]);
return new PickupDataProvider(
new ApiClient($httpClient, $tokens, $logger),
new ResponseMapper($logger),
new StaleWhileErrorCache($pool, $logger),
);
}
}
+5 -53
View File
@@ -3,10 +3,7 @@
namespace App\Tests\BusProNet;
use App\BusProNet\ApiClient;
use App\BusProNet\Model\BaseDataResponse;
use App\BusProNet\Model\CrmAttributesResponse;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Pickup;
use App\BusProNet\Model\ProfileResponse;
use App\BusProNet\Model\ProfileUpdateResponse;
use App\BusProNet\Model\RegistrationResponse;
@@ -135,51 +132,6 @@ class ResponseParserTest extends TestCase
$this->assertTrue($response->isUpdated());
}
public function testParseSuccessfulPickupsResponse(): void
{
$content = '<?xml version="1.0" encoding="utf-8" ?><zustiege><zustieg id="1" idbuspro="1" code="298"><ort>Karlsruhe</ort><strasse>A5 - Autohof Bruchsal</strasse><art>BUS</art><hausabholung>False</hausabholung><crsbuchbar>True</crsbuchbar><internetbuchbar>True</internetbuchbar></zustieg><zustieg id="2" idbuspro="2" code="2"><ort>Bonn</ort><strasse>Bahnhof</strasse><art>BUS</art><hausabholung>False</hausabholung><crsbuchbar>True</crsbuchbar><internetbuchbar>True</internetbuchbar></zustieg></zustiege>';
$parser = $this->getParserInstance();
$response = $parser->parseXmlString(ApiClient::TYPE_BASE_DATA_PICKUPS, $content);
$this->assertInstanceOf(BaseDataResponse::class, $response);
$pickups = $response->getItems();
$this->assertCount(2, $pickups);
$pickup = reset($pickups);
$this->assertInstanceOf(Pickup::class, $pickup);
$this->assertEquals(1, $pickup->getId());
$this->assertEquals(1, $pickup->getBusProId());
$this->assertEquals('298', $pickup->getCode());
$this->assertEquals('Karlsruhe', $pickup->getCity());
$this->assertEquals('A5 - Autohof Bruchsal', $pickup->getStreet());
}
public function testParseSuccessfulHotelsResponse(): void
{
$content = '<?xml version="1.0" encoding="utf-8" ?><hotels><hotel id="1" idbuspro="202003" code="HÖCHST"><name>Berggasthof Höchsten</name><ort>Musterort</ort><strasse>Musterstr. 123</strasse><telefon>03444/19100</telefon><art>Gaststätte</art><internetbuchbar>True</internetbuchbar></hotel><hotel id="2" idbuspro="202004" code="Z. LÖW"><name>Brauereigasthof Zum Löwen</name><ort>Musterort</ort><strasse>Musterstr. 123</strasse><telefon>03437/11133</telefon><art>Gaststätte</art><internetbuchbar>True</internetbuchbar><selektiongruppe id="1" idbuspro="1" bezeichnung="Reisearten 1"><selektion id="1" idbuspro="2" bezeichnung="Kurz-und Clubreisen" /><selektion id="2" idbuspro="7" bezeichnung="Musik und Theater" /><selektion id="3" idbuspro="12" bezeichnung="Flugreisen" /><selektion id="4" idbuspro="13" bezeichnung="Tagesfahrten" /><selektion id="5" idbuspro="1" bezeichnung="Städtereisen" /></selektiongruppe><selektiongruppe id="2" idbuspro="2" bezeichnung="Reisearten 2"><selektion id="1" idbuspro="18" bezeichnung="Adventreisen" /></selektiongruppe><selektiongruppe id="3" idbuspro="3" bezeichnung="Statistik 1"><selektion id="1" idbuspro="31" bezeichnung="Städtreisen" /><selektion id="2" idbuspro="32" bezeichnung="Kurz-und Clubreisen" /><selektion id="3" idbuspro="37" bezeichnung="Musik und Theater" /><selektion id="4" idbuspro="42" bezeichnung="Flugreisen" /><selektion id="5" idbuspro="43" bezeichnung="Tagesfahrten" /></selektiongruppe></hotel></hotels>';
$parser = $this->getParserInstance();
$response = $parser->parseXmlString(ApiClient::TYPE_BASE_DATA_HOTELS, $content);
$this->assertInstanceOf(BaseDataResponse::class, $response);
$hotels = $response->getItems();
$this->assertCount(2, $hotels);
$hotel = reset($hotels);
$this->assertInstanceOf(Hotel::class, $hotel);
$this->assertEquals(1, $hotel->getId());
$this->assertEquals(202003, $hotel->getBusProId());
$this->assertEquals('HÖCHST', $hotel->getCode());
$this->assertEquals('Berggasthof Höchsten', $hotel->getName());
$this->assertEquals('Musterort', $hotel->getCity());
$this->assertEquals('Musterstr. 123', $hotel->getStreet());
$this->assertEquals('03444/19100', $hotel->getPhone());
$this->assertEquals('Gaststätte', $hotel->getType());
}
/**
* A broken response used to collapse into one opaque "Unable to parse XML response",
* which is what made the production import failure undiagnosable. Each shape must now
@@ -192,17 +144,17 @@ class ResponseParserTest extends TestCase
$this->expectException(ResponseParserException::class);
$this->expectExceptionMessage('empty response');
$parser->parseXmlString(ApiClient::TYPE_BASE_DATA_PICKUPS, '');
$parser->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, '');
}
public function testParseTruncatedResponse(): void
{
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="STAMMZUSTIEGE"></satz><zustieg id="1"';
$content = '<?xml version="1.0" encoding="utf-8"?><ergebnis><satz typ="KUNDENKONTO"></satz><art>Adressdaten</art';
$parser = $this->getParserInstance();
try {
$parser->parseXmlString(ApiClient::TYPE_BASE_DATA_PICKUPS, $content);
$parser->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, $content);
$this->fail('Expected a ResponseParserException');
} catch (ResponseParserException $e) {
$this->assertStringContainsString('('.strlen($content).' bytes)', $e->getMessage());
@@ -219,7 +171,7 @@ class ResponseParserTest extends TestCase
$this->expectException(ResponseParserException::class);
$this->expectExceptionMessage('Unrecognised BusProNet response type "STAMMIRGENDWAS"');
$parser->parseXmlString(ApiClient::TYPE_BASE_DATA_PICKUPS, $content);
$parser->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, $content);
}
public function testParsingDoesNotLeakLibxmlErrorState(): void
@@ -228,7 +180,7 @@ class ResponseParserTest extends TestCase
try {
try {
$this->getParserInstance()->parseXmlString(ApiClient::TYPE_BASE_DATA_PICKUPS, '<ergebnis');
$this->getParserInstance()->parseXmlString(ApiClient::TYPE_CUSTOMER_DATA, '<ergebnis');
} catch (ResponseParserException) {
}
+239
View File
@@ -0,0 +1,239 @@
<?php
declare(strict_types=1);
namespace App\Tests\Command;
use App\Command\MyEpImportCommand;
use App\MyEp\Api\ApiException;
use App\MyEp\Import\DestinationRow;
use App\MyEp\Import\TravelExport;
use App\MyEp\Import\TravelExportClient;
use Doctrine\DBAL\Connection;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
/**
* The import writes a destination's cost unit and country from the export, on update as well as
* on insert, so it can only run once MyE&P reports both fields. Until it does, a run would blank
* them on the 2,206 destinations that carry a cost unit and the 2,259 that carry a country -
* silently, because nothing reads them back until an invoice is stamped. Most of these tests pin
* the refusal, and that it happens before any write.
*/
class MyEpImportCommandTest extends TestCase
{
public function testItRefusesToRunWhenNoRowReportsACostUnit(): void
{
$tester = $this->runImport([$this->row(costUnit: null, country: 'ch')]);
$this->assertSame(Command::FAILURE, $tester->getStatusCode());
$this->assertStringContainsString('Kostenstellen', $tester->getDisplay());
$this->assertStringNotContainsString('Länderkennungen', $tester->getDisplay());
}
public function testItRefusesToRunWhenNoRowReportsACountryCode(): void
{
$tester = $this->runImport([$this->row(costUnit: '4711', country: null)]);
$this->assertSame(Command::FAILURE, $tester->getStatusCode());
$this->assertStringContainsString('Länderkennungen', $tester->getDisplay());
}
public function testItNamesBothFieldsWhenNeitherIsReported(): void
{
$tester = $this->runImport([$this->row(costUnit: null, country: null)]);
$this->assertSame(Command::FAILURE, $tester->getStatusCode());
$this->assertStringContainsString('Kostenstellen und Länderkennungen', $tester->getDisplay());
}
public function testAnEmptyStringDoesNotCountAsAReportedField(): void
{
$tester = $this->runImport([$this->row(costUnit: '', country: '')]);
$this->assertSame(Command::FAILURE, $tester->getStatusCode());
$this->assertStringContainsString('Kostenstellen und Länderkennungen', $tester->getDisplay());
}
/**
* Most hotels legitimately have no kostenstelle upstream, so the guard asks whether the field
* is reported at all, not whether every row fills it.
*/
public function testOneRowCarryingAFieldIsEnoughToPassTheGuard(): void
{
$tester = $this->runImport(
[$this->row(costUnit: null, country: null), $this->row(costUnit: '4711', country: 'ch')],
$this->writingConnection(existingId: 7),
);
$this->assertSame(Command::SUCCESS, $tester->getStatusCode());
$this->assertStringNotContainsString('Kostenstellen', $tester->getDisplay());
}
/**
* A run that touches nothing and reports success reads as "nothing changed upstream" rather
* than as a failure to read the export at all.
*/
public function testItRefusesToRunOnAnEmptyExport(): void
{
$tester = $this->runImport([]);
$this->assertSame(Command::FAILURE, $tester->getStatusCode());
$this->assertStringContainsString('keine Reisen', $tester->getDisplay());
}
public function testItRefusesToRunWhenTheExportCannotBeRead(): void
{
$client = $this->createMock(TravelExportClient::class);
$client->method('fetchAll')->willThrowException(new ApiException('gateway timeout'));
$tester = new CommandTester(new MyEpImportCommand(
$this->refusingConnection(),
$client,
new NullLogger(),
));
$tester->execute([]);
$this->assertSame(Command::FAILURE, $tester->getStatusCode());
$this->assertStringContainsString('konnte nicht von MyE&P geladen werden', $tester->getDisplay());
}
public function testAKnownPairIsUpdatedRatherThanInserted(): void
{
$connection = $this->createMock(Connection::class);
$connection->method('fetchOne')->willReturn(42);
$connection->expects($this->once())->method('update')->with(
'destination',
$this->callback(function (array $payload): bool {
// the hotel name and code are the point: leaving them out of the update was what
// let a renamed hotel keep a stale name forever and drop out of house matching
$this->assertArrayHasKey('hotel', $payload);
$this->assertArrayHasKey('hotel_code', $payload);
$this->assertArrayNotHasKey('bus_pro_id', $payload);
return true;
}),
['id' => 42],
);
$connection->expects($this->never())->method('insert');
$tester = $this->runImport([$this->row(costUnit: '4711', country: 'ch')], $connection);
$this->assertSame(Command::SUCCESS, $tester->getStatusCode());
$this->assertStringContainsString('0 Destinationen angelegt, 1 aktualisiert', $tester->getDisplay());
}
public function testAnUnknownPairIsInserted(): void
{
$connection = $this->createMock(Connection::class);
$connection->method('fetchOne')->willReturn(false);
$connection->expects($this->once())->method('insert')->with(
'destination',
$this->callback(function (array $payload): bool {
$this->assertSame(12778, $payload['bus_pro_id']);
$this->assertSame(222928, $payload['hotel_bus_pro_id']);
$this->assertSame('ch', $payload['country']);
return true;
}),
);
$connection->expects($this->never())->method('update');
$tester = $this->runImport([$this->row(costUnit: '4711', country: 'ch')], $connection);
$this->assertStringContainsString('1 Destinationen angelegt, 0 aktualisiert', $tester->getDisplay());
}
/**
* Both counters are losses MyE&P made on its side and would otherwise not surface anywhere.
*/
public function testTheOperatorIsToldWhatMyEpDropped(): void
{
$tester = $this->runImport(
[$this->row(costUnit: '4711', country: 'ch')],
$this->writingConnection(existingId: 7),
skipped: 3,
pickupsWithoutMasterData: 21,
);
$display = $tester->getDisplay();
$this->assertStringContainsString('3 Reise-Hotel-Kombinationen verworfen', $display);
$this->assertStringContainsString('21 Zustiege ohne Stammdaten', $display);
}
public function testACleanExportSaysNothingAboutDroppedRows(): void
{
$tester = $this->runImport(
[$this->row(costUnit: '4711', country: 'ch')],
$this->writingConnection(existingId: 7),
);
$this->assertStringNotContainsString('verworfen', $tester->getDisplay());
}
/**
* @param DestinationRow[] $rows
*/
private function runImport(
array $rows,
?Connection $connection = null,
int $skipped = 0,
int $pickupsWithoutMasterData = 0,
): CommandTester {
$client = $this->createMock(TravelExportClient::class);
$client->method('fetchAll')->willReturn(
new TravelExport($rows, $skipped, $pickupsWithoutMasterData, '2026-09-29T03:20:00+02:00')
);
$tester = new CommandTester(new MyEpImportCommand(
$connection ?? $this->refusingConnection(),
$client,
new NullLogger(),
));
$tester->execute([]);
return $tester;
}
/**
* Any query at all means the guard let a write through, which is the whole failure the
* refusal tests cover, so the connection fails the test rather than the command.
*/
private function refusingConnection(): Connection&MockObject
{
$connection = $this->createMock(Connection::class);
$connection->expects($this->never())->method($this->anything());
return $connection;
}
private function writingConnection(int $existingId): Connection&MockObject
{
$connection = $this->createMock(Connection::class);
$connection->method('fetchOne')->willReturn($existingId);
return $connection;
}
private function row(?string $costUnit, ?string $country): DestinationRow
{
return new DestinationRow(
12778,
'DWWSCH070227',
'Davos - Sportclub Weissfluh',
new \DateTimeImmutable('2027-02-07'),
new \DateTimeImmutable('2027-02-12'),
222928,
'DWWGRU2',
'Sportclub Weißfluh',
$costUnit,
$country,
[],
);
}
}
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Administrative\System\Destination;
use App\BusProNet\DataProvider\HotelDataProvider;
use App\BusProNet\DataProvider\PickupDataProvider;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Pickup;
use App\Controller\Administrative\System\Destination\DestinationTrait;
use App\Entity\Destination;
use App\Model\DestinationDto;
use PHPUnit\Framework\TestCase;
/**
* The shared mapping behind the destination create, edit and duplicate forms.
*
* Both behaviours here are about what happens when MyE&P cannot resolve something, which is
* the state the whole form lands in during an outage: the hotel stops the write, a boarding
* point does not.
*/
class DestinationTraitTest extends TestCase
{
/**
* The same choice App\Command\MyEpImportCommand makes for the export's own unresolvable ids.
* Dropping the stop would hide a departure the coach actually makes; PickupOptions renders
* one without a town as "Zustieg {busProId}".
*/
public function testAnUnresolvablePickupIsKeptWithoutItsAddress(): void
{
$harness = $this->harness($this->hotel(), [4 => $this->pickup()]);
$destination = new Destination();
$harness->map($destination, $this->dto([4, 999]));
$this->assertSame([
['busProId' => 4, 'city' => 'Karlsruhe', 'street' => 'A5 - Autohof Bruchsal', 'time' => null],
['busProId' => 999, 'city' => null, 'street' => null, 'time' => null],
], $destination->getPickups());
}
/**
* ResolvableHotel reports this on the field, and every caller runs behind $form->isValid().
* This is the second line: a half built destination has no house name, no cost unit and no
* country, and nothing reads those back until an invoice is stamped.
*/
public function testAnUnresolvableHotelRefusesToWriteAnything(): void
{
$harness = $this->harness(hotel: null);
$destination = new Destination();
try {
$harness->map($destination, $this->dto([]));
$this->fail('Expected a LogicException');
} catch (\LogicException $e) {
$this->assertStringContainsString('does not resolve', $e->getMessage());
}
$this->assertNull($destination->getHotel());
$this->assertNull($destination->getProduct());
}
/**
* @param ?Hotel $hotel null stands for a hotel the base data cannot resolve
* @param array<int, Pickup> $pickups keyed by busProId; anything absent does not resolve
*/
private function harness(?Hotel $hotel, array $pickups = []): object
{
$hotelProvider = $this->createMock(HotelDataProvider::class);
$hotelProvider->method('get')->willReturn($hotel);
$pickupProvider = $this->createMock(PickupDataProvider::class);
$pickupProvider->method('get')->willReturnCallback(fn ($id) => $pickups[$id] ?? null);
return new class($hotelProvider, $pickupProvider) {
use DestinationTrait;
public function __construct(
private readonly HotelDataProvider $hotelDataProvider,
private readonly PickupDataProvider $pickupDataProvider,
) {
}
public function map(Destination $destination, DestinationDto $dto): void
{
$this->updateEntity($destination, $dto);
}
};
}
private function dto(array $pickupIds): DestinationDto
{
return (new DestinationDto())
->setProduct('Lenzerheide - Sportclub Jenatsch')
->setDateFrom(new \DateTimeImmutable('2026-04-04'))
->setDateTo(new \DateTimeImmutable('2026-04-11'))
->setHotelBusProId('163959')
->setCountry('ch')
->setPickups($pickupIds)
;
}
private function hotel(): Hotel
{
return (new Hotel())
->setBusProId(163959)
->setCode('LPJGR')
->setName('Sportclub Jenatsch')
->setCostUnit('4711')
;
}
private function pickup(): Pickup
{
return (new Pickup())
->setBusProId(4)
->setCity('Karlsruhe')
->setStreet('A5 - Autohof Bruchsal')
;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace App\Tests\Model;
use App\Model\DestinationDto;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validation;
/**
* The stored country moved to ISO-3166-1 alpha-2, but the constraint on this DTO kept the
* old BusProNet abbreviations while the form was already offering the new codes. Every
* country except Schweiz and Niederlande - the two whose code happens to be unchanged -
* was rejected as "Ungültige Auswahl" on save, so a destination could not be created or
* edited for Österreich, Deutschland, Frankreich or Italien at all.
*
* The codes are asserted literally rather than read back off the map they come from, so
* that changing the map has to be a deliberate act rather than something a test agrees
* with by construction.
*/
class DestinationDtoTest extends TestCase
{
public function testTheAuthorableCountriesAreTheIsoCodes(): void
{
$this->assertSame(['at', 'ch', 'fr', 'it', 'de', 'nl'], DestinationDto::countryCodes());
}
/**
* @dataProvider isoCountryCodes
*/
public function testAnIsoCountryCodeIsAccepted(string $code): void
{
$this->assertCount(0, $this->validateCountry($code));
}
/**
* The four that the form offered and the constraint refused.
*
* @dataProvider busProNetCountryAbbreviations
*/
public function testABusProNetAbbreviationIsNoLongerAccepted(string $abbreviation): void
{
$this->assertCount(1, $this->validateCountry($abbreviation));
}
/**
* MyE&P drops a country it cannot map to two letters, so a destination without one is
* a normal row rather than an invalid one.
*/
public function testNoCountryIsAccepted(): void
{
$this->assertCount(0, $this->validateCountry(null));
}
/**
* @return iterable<array{string}>
*/
public static function isoCountryCodes(): iterable
{
foreach (DestinationDto::countryCodes() as $code) {
yield $code => [$code];
}
}
/**
* @return iterable<array{string}>
*/
public static function busProNetCountryAbbreviations(): iterable
{
yield 'a' => ['a'];
yield 'd' => ['d'];
yield 'f' => ['f'];
yield 'i' => ['i'];
}
private function validateCountry(?string $country): ConstraintViolationListInterface
{
return Validation::createValidatorBuilder()
->enableAttributeMapping()
->getValidator()
->validateProperty((new DestinationDto())->setCountry($country), 'country')
;
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Tests\MyEp\Api;
use App\MyEp\Api\AccessTokenProvider;
use App\MyEp\Api\ApiException;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class AccessTokenProviderTest extends TestCase
{
private const CACHE_KEY = 'myep.api.access_token';
public function testTokenIsReturnedFromTheTokenEndpoint(): void
{
$httpClient = new MockHttpClient([$this->tokenResponse('abc123')]);
$this->assertEquals('abc123', $this->getProviderInstance($httpClient)->getToken());
}
public function testTheClientCredentialsGrantIsRequested(): void
{
$body = null;
$httpClient = new MockHttpClient(function (string $method, string $url, array $options) use (&$body) {
$this->assertEquals('POST', $method);
$this->assertEquals('https://myep.example/token', $url);
$body = $options['body'];
return $this->tokenResponse('abc123');
});
$this->getProviderInstance($httpClient)->getToken();
$this->assertStringContainsString('grant_type=client_credentials', $body);
$this->assertStringContainsString('scope=api', $body);
$this->assertStringContainsString('client_secret=secret', $body);
}
public function testTheTokenIsCachedRatherThanRequestedPerCall(): void
{
$httpClient = new MockHttpClient([$this->tokenResponse('abc123')]);
$cache = new ArrayAdapter();
$provider = $this->getProviderInstance($httpClient, $cache);
$provider->getToken();
$provider->getToken();
$this->assertEquals(1, $httpClient->getRequestsCount());
$this->assertTrue($cache->getItem(self::CACHE_KEY)->isHit());
}
public function testACachedTokenIsUsedWithoutAskingForANewOne(): void
{
$cache = new ArrayAdapter();
$item = $cache->getItem(self::CACHE_KEY);
$item->set('cached-token');
$cache->save($item);
$httpClient = new MockHttpClient([]);
$this->assertEquals('cached-token', $this->getProviderInstance($httpClient, $cache)->getToken());
$this->assertEquals(0, $httpClient->getRequestsCount());
}
public function testAnInvalidatedTokenIsRequestedAgain(): void
{
$httpClient = new MockHttpClient([$this->tokenResponse('abc123'), $this->tokenResponse('def456')]);
$provider = $this->getProviderInstance($httpClient);
$provider->getToken();
$provider->invalidate();
$this->assertEquals('def456', $provider->getToken());
$this->assertEquals(2, $httpClient->getRequestsCount());
}
public function testARejectedRequestFails(): void
{
$httpClient = new MockHttpClient([
new MockResponse('{"error":"invalid_client"}', ['http_code' => 401]),
]);
$this->expectException(ApiException::class);
$this->getProviderInstance($httpClient)->getToken();
}
public function testAResponseWithoutATokenFails(): void
{
$httpClient = new MockHttpClient([new MockResponse('{"expires_in":600}')]);
$this->expectException(ApiException::class);
$this->getProviderInstance($httpClient)->getToken();
}
public function testAnUnreachableTokenEndpointFails(): void
{
$httpClient = new MockHttpClient([new MockResponse('', ['error' => 'connection refused'])]);
$this->expectException(ApiException::class);
$this->getProviderInstance($httpClient)->getToken();
}
public function testAnUnparsableResponseFails(): void
{
$httpClient = new MockHttpClient([new MockResponse('<html>gateway timeout</html>')]);
$this->expectException(ApiException::class);
$this->getProviderInstance($httpClient)->getToken();
}
private function tokenResponse(string $token, int $expiresIn = 600): MockResponse
{
return new MockResponse(json_encode([
'access_token' => $token,
'token_type' => 'Bearer',
'expires_in' => $expiresIn,
]));
}
private function getProviderInstance(MockHttpClient $httpClient, ?CacheItemPoolInterface $cache = null): AccessTokenProvider
{
return new AccessTokenProvider(
$httpClient,
$cache ?? new ArrayAdapter(),
new NullLogger(),
[
'client_id' => 'team-app',
'client_secret' => 'secret',
'token_path' => 'https://myep.example/token',
'scope' => 'api',
],
);
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
namespace App\Tests\MyEp\Api;
use App\MyEp\Api\AccessTokenProvider;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ApiException;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class ApiClientTest extends TestCase
{
public function testPayloadIsReturned(): void
{
$httpClient = $this->mockClient([new MockResponse('[{"id":1}]')]);
$this->assertEquals([['id' => 1]], $this->getClientInstance($httpClient)->get('api/hotels'));
}
public function testTheTokenIsSentAsABearer(): void
{
$authorization = null;
$httpClient = $this->mockClient(function (string $method, string $url, array $options) use (&$authorization) {
$this->assertEquals('GET', $method);
$authorization = $this->headerOf($options, 'authorization');
return new MockResponse('[]');
});
$this->getClientInstance($httpClient)->get('api/hotels');
$this->assertEquals('Authorization: Bearer token-1', $authorization);
}
public function testQueryParametersArePassedOn(): void
{
$requestedUrl = null;
$httpClient = $this->mockClient(function (string $method, string $url) use (&$requestedUrl) {
$requestedUrl = $url;
return new MockResponse('[]');
});
$this->getClientInstance($httpClient)->get('api/exports/travels', ['page' => 2, 'perPage' => 500]);
$this->assertStringContainsString('page=2', $requestedUrl);
$this->assertStringContainsString('perPage=500', $requestedUrl);
}
public function testARejectedTokenIsRenewedOnce(): void
{
$httpClient = $this->mockClient([
new MockResponse('{"message":"Unauthorized"}', ['http_code' => 401]),
new MockResponse('[{"id":1}]'),
]);
$result = $this->getClientInstance($httpClient)->get('api/hotels');
$this->assertEquals([['id' => 1]], $result);
$this->assertEquals(2, $httpClient->getRequestsCount());
}
public function testARepeatedlyRejectedTokenFailsWithoutLooping(): void
{
$httpClient = $this->mockClient([
new MockResponse('{"message":"Unauthorized"}', ['http_code' => 401]),
new MockResponse('{"message":"Unauthorized"}', ['http_code' => 401]),
]);
try {
$this->getClientInstance($httpClient)->get('api/hotels');
$this->fail('Expected an ApiException');
} catch (ApiException) {
}
$this->assertEquals(2, $httpClient->getRequestsCount());
}
public function testAMissingScopeFails(): void
{
$httpClient = $this->mockClient([new MockResponse('{"message":"Forbidden"}', ['http_code' => 403])]);
$this->expectException(ApiException::class);
$this->expectExceptionMessageMatches('/scope/');
$this->getClientInstance($httpClient)->get('api/hotels');
}
public function testAServerErrorFails(): void
{
$httpClient = $this->mockClient([new MockResponse('', ['http_code' => 500])]);
$this->expectException(ApiException::class);
$this->getClientInstance($httpClient)->get('api/hotels');
}
public function testAnErrorReportedWithStatusOkFails(): void
{
// some MyE&P endpoints answer 200 with an error body, so the payload has to decide
$httpClient = $this->mockClient([
new MockResponse('{"error":"upstream unavailable","type":"api_error"}'),
]);
$this->expectException(ApiException::class);
$this->getClientInstance($httpClient)->get('api/products');
}
public function testAnUnreadableBodyFails(): void
{
$httpClient = $this->mockClient([new MockResponse('<html>not json</html>')]);
$this->expectException(ApiException::class);
$this->getClientInstance($httpClient)->get('api/hotels');
}
public function testAnUnreachableApiFails(): void
{
$httpClient = $this->mockClient([new MockResponse('', ['error' => 'connection refused'])]);
$this->expectException(ApiException::class);
$this->getClientInstance($httpClient)->get('api/hotels');
}
private function mockClient(array|callable $responses): MockHttpClient
{
return new MockHttpClient($responses, 'https://myep.example/');
}
private function headerOf(array $options, string $name): ?string
{
foreach ($options['headers'] ?? [] as $header) {
if (str_starts_with(strtolower($header), $name.':')) {
return $header;
}
}
return null;
}
private function getClientInstance(MockHttpClient $httpClient): ApiClient
{
$tokenClient = new MockHttpClient(function () {
static $count = 0;
return new MockResponse(json_encode([
'access_token' => 'token-'.++$count,
'expires_in' => 600,
]));
});
$tokens = new AccessTokenProvider($tokenClient, new ArrayAdapter(), new NullLogger(), [
'client_id' => 'team-app',
'client_secret' => 'secret',
'token_path' => 'https://myep.example/token',
]);
return new ApiClient($httpClient, $tokens, new NullLogger());
}
}
+162
View File
@@ -0,0 +1,162 @@
<?php
namespace App\Tests\MyEp\Api;
use App\BusProNet\Model\Country;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Pickup;
use App\MyEp\Api\ResponseMapper;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
class ResponseMapperTest extends TestCase
{
public function testHotelsAreKeyedByTheirBusProId(): void
{
$hotels = $this->getMapperInstance()->mapHotels([
['id' => 163959, 'code' => 'LPJGR', 'name' => 'Sportclub Jenatsch'],
['id' => 202003, 'code' => 'SRR', 'name' => 'Berggasthof Ranalt'],
]);
$this->assertEquals([163959, 202003], array_keys($hotels));
$this->assertInstanceOf(Hotel::class, $hotels[163959]);
$this->assertEquals(163959, $hotels[163959]->getBusProId());
$this->assertEquals('LPJGR', $hotels[163959]->getCode());
$this->assertEquals('Sportclub Jenatsch', $hotels[163959]->getName());
}
public function testHotelFieldsAreMapped(): void
{
$hotels = $this->getMapperInstance()->mapHotels([[
'id' => 163959,
'code' => 'LPJGR',
'name' => 'Sportclub Jenatsch',
'city' => 'Lenzerheide',
'street' => 'Voa Principala 1',
'phone' => '+41 81 000000',
'country' => 'CH',
'countryCode' => 'ch',
'costUnit' => '4711',
]]);
$hotel = $hotels[163959];
$this->assertEquals('4711', $hotel->getCostUnit());
}
public function testTheRawCountryTokenIsKeptAsReported(): void
{
// the raw token is not a standard, it is the join key into the country base data
$hotels = $this->getMapperInstance()->mapHotels([['id' => 1, 'country' => 'AUT']]);
$this->assertEquals('AUT', $hotels[1]->getCountry());
}
public function testTheCountryCodeIsLowercasedIso(): void
{
// this is what reaches the two character column and the flag icons
$hotels = $this->getMapperInstance()->mapHotels([['id' => 1, 'country' => 'AUT', 'countryCode' => 'AT']]);
$this->assertEquals('at', $hotels[1]->getCountryCode());
}
public function testAnUnresolvedCountryCodeIsNull(): void
{
$hotels = $this->getMapperInstance()->mapHotels([
['id' => 1, 'country' => 'XYZ'],
['id' => 2, 'country' => 'SLO', 'countryCode' => null],
['id' => 3, 'country' => 'D', 'countryCode' => 'deu'],
]);
$this->assertNull($hotels[1]->getCountryCode());
$this->assertNull($hotels[2]->getCountryCode());
$this->assertNull($hotels[3]->getCountryCode(), 'a three letter code does not fit the column');
}
public function testOptionalHotelFieldsMayBeAbsent(): void
{
$hotels = $this->getMapperInstance()->mapHotels([['id' => 1, 'code' => 'AAA']]);
$this->assertNull($hotels[1]->getCountryCode());
$this->assertNull($hotels[1]->getCostUnit());
$this->assertNull($hotels[1]->getName());
}
public function testHotelsWithoutAnIdAreSkipped(): void
{
$hotels = $this->getMapperInstance()->mapHotels([
['code' => 'AAA'],
['id' => 0, 'code' => 'BBB'],
['id' => 7, 'code' => 'CCC'],
]);
$this->assertEquals([7], array_keys($hotels));
}
public function testPickupsAreKeyedByTheirBusProId(): void
{
$pickups = $this->getMapperInstance()->mapPickups([
['id' => 4, 'code' => '298', 'city' => 'Karlsruhe', 'street' => 'A5 - Autohof Bruchsal'],
]);
$this->assertEquals([4], array_keys($pickups));
$this->assertInstanceOf(Pickup::class, $pickups[4]);
$this->assertEquals(4, $pickups[4]->getBusProId());
$this->assertEquals(4, $pickups[4]->getId());
$this->assertEquals('298', $pickups[4]->getCode());
$this->assertEquals('Karlsruhe', $pickups[4]->getCity());
$this->assertEquals('A5 - Autohof Bruchsal', $pickups[4]->getStreet());
}
public function testAPickupCarriesNoTimeOfItsOwn(): void
{
// a departure time belongs to a boarding stop on a date, not to the stop itself
$pickups = $this->getMapperInstance()->mapPickups([['id' => 4, 'time' => '23:59']]);
$this->assertNull($pickups[4]->getTime());
}
public function testPickupsWithoutAnIdAreSkipped(): void
{
$pickups = $this->getMapperInstance()->mapPickups([['city' => 'Karlsruhe'], ['id' => 4]]);
$this->assertEquals([4], array_keys($pickups));
}
public function testCountriesAreKeyedByTheirToken(): void
{
$countries = $this->getMapperInstance()->mapCountries([
['id' => 1, 'name' => 'Schweiz', 'token' => 'CH', 'nationality' => 'schweizerisch'],
]);
$this->assertEquals(['CH'], array_keys($countries));
$this->assertInstanceOf(Country::class, $countries['CH']);
$this->assertEquals('Schweiz', $countries['CH']->getName());
$this->assertEquals('CH', $countries['CH']->getToken());
$this->assertEquals('schweizerisch', $countries['CH']->getNationality());
}
public function testCountriesWithoutATokenAreSkipped(): void
{
$countries = $this->getMapperInstance()->mapCountries([
['id' => 1, 'name' => 'Schweiz'],
['id' => 2, 'name' => 'Österreich', 'token' => 'A'],
]);
$this->assertEquals(['A'], array_keys($countries));
}
public function testAnEmptyListMapsToAnEmptyResult(): void
{
$mapper = $this->getMapperInstance();
$this->assertEquals([], $mapper->mapHotels([]));
$this->assertEquals([], $mapper->mapPickups([]));
$this->assertEquals([], $mapper->mapCountries([]));
}
private function getMapperInstance(): ResponseMapper
{
return new ResponseMapper(new NullLogger());
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Tests\MyEp\Cache;
use App\MyEp\Cache\StaleWhileErrorCache;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
class StaleWhileErrorCacheTest extends TestCase
{
public function testTheProducedValueIsReturnedAndCached(): void
{
$pool = new ArrayAdapter();
$cache = new StaleWhileErrorCache($pool, new NullLogger());
$value = $cache->get('myep.hotels.v1', 3600, fn () => ['a' => 1]);
$this->assertEquals(['a' => 1], $value);
$this->assertTrue($pool->getItem('myep.hotels.v1')->isHit());
$this->assertTrue($pool->getItem('myep.hotels.v1.last_good')->isHit());
}
public function testACachedValueIsServedWithoutProducingAgain(): void
{
$pool = new ArrayAdapter();
$cache = new StaleWhileErrorCache($pool, new NullLogger());
$calls = 0;
$producer = function () use (&$calls) {
++$calls;
return ['a' => 1];
};
$cache->get('myep.hotels.v1', 3600, $producer);
$value = $cache->get('myep.hotels.v1', 3600, $producer);
$this->assertEquals(['a' => 1], $value);
$this->assertEquals(1, $calls);
}
public function testTheLastKnownValueIsServedWhenProducingFails(): void
{
$pool = new ArrayAdapter();
$cache = new StaleWhileErrorCache($pool, new NullLogger());
$cache->get('myep.hotels.v1', 3600, fn () => ['a' => 1]);
$pool->deleteItem('myep.hotels.v1');
$value = $cache->get('myep.hotels.v1', 3600, fn () => throw new \RuntimeException('upstream is down'));
$this->assertEquals(['a' => 1], $value);
}
public function testAServedStaleValueSuppressesFurtherAttempts(): void
{
$pool = new ArrayAdapter();
$cache = new StaleWhileErrorCache($pool, new NullLogger());
$calls = 0;
$failing = function () use (&$calls) {
++$calls;
throw new \RuntimeException('upstream is down');
};
$cache->get('myep.hotels.v1', 3600, fn () => ['a' => 1]);
$pool->deleteItem('myep.hotels.v1');
$cache->get('myep.hotels.v1', 3600, $failing);
$cache->get('myep.hotels.v1', 3600, $failing);
$this->assertEquals(1, $calls);
}
public function testAFailureWithoutAnyCachedValueIsEmpty(): void
{
$cache = new StaleWhileErrorCache(new ArrayAdapter(), new NullLogger());
$value = $cache->get('myep.hotels.v1', 3600, fn () => throw new \RuntimeException('upstream is down'));
$this->assertEquals([], $value);
}
public function testEachKeyKeepsItsOwnValue(): void
{
$pool = new ArrayAdapter();
$cache = new StaleWhileErrorCache($pool, new NullLogger());
$cache->get('myep.hotels.v1', 3600, fn () => ['hotel']);
$cache->get('myep.pickups.v1', 3600, fn () => ['pickup']);
$this->assertEquals(['hotel'], $cache->get('myep.hotels.v1', 3600, fn () => ['other']));
$this->assertEquals(['pickup'], $cache->get('myep.pickups.v1', 3600, fn () => ['other']));
}
}
+203
View File
@@ -0,0 +1,203 @@
<?php
namespace App\Tests\MyEp\Import;
use App\BusProNet\Model\Pickup;
use App\MyEp\Import\DestinationRow;
use App\MyEp\Import\InvalidRowException;
use PHPUnit\Framework\TestCase;
class DestinationRowTest extends TestCase
{
public function testARowIsMapped(): void
{
$row = DestinationRow::fromArray($this->getRowData());
$this->assertEquals(11886, $row->busProId);
$this->assertEquals('LPJPGJ040426', $row->code);
$this->assertEquals('Lenzerheide - Sportclub Jenatsch', $row->product);
$this->assertEquals('2026-04-04', $row->dateFrom->format('Y-m-d'));
$this->assertEquals('2026-04-11', $row->dateTo->format('Y-m-d'));
$this->assertEquals(163959, $row->hotelBusProId);
$this->assertEquals('LPJGR', $row->hotelCode);
$this->assertEquals('Sportclub Jenatsch', $row->hotelName);
$this->assertEquals('4711', $row->costUnit);
$this->assertEquals('ch', $row->country);
}
public function testTheIsoCountryCodeIsStoredRatherThanTheRawToken(): void
{
$row = DestinationRow::fromArray($this->getRowData([
'hotel' => ['busProId' => 1, 'country' => 'AUT', 'countryCode' => 'AT'],
]));
$this->assertEquals('at', $row->country);
}
public function testAnUnresolvedCountryCodeIsStoredAsNull(): void
{
$row = DestinationRow::fromArray($this->getRowData([
'hotel' => ['busProId' => 1, 'country' => 'SLO'],
]));
$this->assertNull($row->country);
}
public function testTheDatesAreReadAsWholeDays(): void
{
$row = DestinationRow::fromArray($this->getRowData());
$this->assertEquals('00:00:00', $row->dateFrom->format('H:i:s'));
$this->assertEquals('00:00:00', $row->dateTo->format('H:i:s'));
}
public function testPickupsKeepTheShapeTheDestinationTableStores(): void
{
$row = DestinationRow::fromArray($this->getRowData());
$this->assertEquals([[
'busProId' => 4,
'city' => 'Karlsruhe',
'street' => 'A5 - Autohof Bruchsal',
'time' => '23:59',
'datetime' => '2026-04-04T23:59:00+02:00',
]], $row->pickups);
}
/**
* MyE&P sends `time` as a bare HH:MM, so this is the only field that says which calendar day
* a boarding point belongs to. Dropping it left App\Service\Assignment\PickupDepartureOrder
* with no anchor and a naive clock sort, which puts a 00:30 stop before the 22:00 departure.
*/
public function testTheResolvedDepartureTimestampIsCarried(): void
{
$row = DestinationRow::fromArray($this->getRowData());
$this->assertSame('2026-04-04T23:59:00+02:00', $row->pickups[0]['datetime']);
}
public function testAPickupWithoutAResolvedTimestampIsStillCarried(): void
{
$row = DestinationRow::fromArray($this->getRowData(['pickups' => [
['busProId' => 27, 'city' => 'Ulm', 'street' => 'Busparkplatz', 'time' => null],
]]));
$this->assertNull($row->pickups[0]['datetime']);
$this->assertCount(1, $row->pickups);
}
public function testStoredPickupsCanBeReadBackAsModels(): void
{
$row = DestinationRow::fromArray($this->getRowData());
$pickup = Pickup::fromArray(json_decode(json_encode($row->pickups), true)[0]);
$this->assertEquals(4, $pickup->getId());
$this->assertEquals('Karlsruhe', $pickup->getCity());
$this->assertEquals('23:59', $pickup->getTime());
}
public function testPickupsWithoutAnIdAreDropped(): void
{
$row = DestinationRow::fromArray($this->getRowData(['pickups' => [
['city' => 'Karlsruhe'],
['busProId' => 0, 'city' => 'Köln'],
['busProId' => 27, 'city' => 'Bonn', 'street' => 'ZOB', 'time' => '02:15'],
]]));
$this->assertCount(1, $row->pickups);
$this->assertEquals(27, $row->pickups[0]['busProId']);
}
public function testARowWithoutPickupsIsAccepted(): void
{
$row = DestinationRow::fromArray($this->getRowData(['pickups' => []]));
$this->assertEquals([], $row->pickups);
}
public function testARowWithoutAHotelIsRejected(): void
{
$this->expectException(InvalidRowException::class);
DestinationRow::fromArray($this->getRowData(['hotel' => null]));
}
public function testARowWithoutIdsIsRejected(): void
{
$this->expectException(InvalidRowException::class);
DestinationRow::fromArray($this->getRowData(['busProId' => 0]));
}
public function testARowWithAnUnreadableDateIsRejected(): void
{
$this->expectException(InvalidRowException::class);
DestinationRow::fromArray($this->getRowData(['dateFrom' => '04.04.2026']));
}
public function testTheInsertPayloadCarriesEveryColumn(): void
{
$row = DestinationRow::fromArray($this->getRowData());
$payload = $row->toInsertPayload(new \DateTimeImmutable('2026-08-13 03:00:00'));
$this->assertEquals([
'code' => 'LPJPGJ040426',
'bus_pro_id' => 11886,
'date_from' => '2026-04-04',
'date_to' => '2026-04-11',
'product' => 'Lenzerheide - Sportclub Jenatsch',
'hotel' => 'Sportclub Jenatsch',
'hotel_code' => 'LPJGR',
'hotel_bus_pro_id' => 163959,
'pickups' => '[{"busProId":4,"city":"Karlsruhe","street":"A5 - Autohof Bruchsal","time":"23:59","datetime":"2026-04-04T23:59:00+02:00"}]',
'cost_unit' => '4711',
'country' => 'ch',
'created_at' => '2026-08-13 03:00:00',
], $payload);
}
public function testTheUpdatePayloadRefreshesTheHotelName(): void
{
// a renamed house has to reach existing rows, or it drops out of the house matching
$row = DestinationRow::fromArray($this->getRowData());
$payload = $row->toUpdatePayload(new \DateTimeImmutable('2026-08-13 03:00:00'));
$this->assertEquals('Sportclub Jenatsch', $payload['hotel']);
$this->assertEquals('LPJGR', $payload['hotel_code']);
$this->assertEquals('2026-08-13 03:00:00', $payload['updated_at']);
$this->assertArrayNotHasKey('created_at', $payload);
$this->assertArrayNotHasKey('bus_pro_id', $payload);
$this->assertArrayNotHasKey('hotel_bus_pro_id', $payload);
}
private function getRowData(array $overrides = []): array
{
return array_merge([
'busProId' => 11886,
'code' => 'LPJPGJ040426',
'product' => 'Lenzerheide - Sportclub Jenatsch',
'dateFrom' => '2026-04-04',
'dateTo' => '2026-04-11',
'hotel' => [
'busProId' => 163959,
'code' => 'LPJGR',
'name' => 'Sportclub Jenatsch',
'costUnit' => '4711',
'country' => 'CH',
'countryCode' => 'ch',
],
'pickups' => [[
'busProId' => 4,
'code' => '298',
'city' => 'Karlsruhe',
'street' => 'A5 - Autohof Bruchsal',
'time' => '23:59',
'datetime' => '2026-04-04T23:59:00+02:00',
]],
], $overrides);
}
}
@@ -0,0 +1,201 @@
<?php
namespace App\Tests\MyEp\Import;
use App\MyEp\Api\AccessTokenProvider;
use App\MyEp\Api\ApiClient;
use App\MyEp\Api\ApiException;
use App\MyEp\Import\TravelExportClient;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class TravelExportClientTest extends TestCase
{
public function testEveryPageIsRead(): void
{
$httpClient = $this->mockClient([
$this->page([$this->row(1, 100), $this->row(2, 200)], 1, 2),
$this->page([$this->row(3, 300)], 2, 2),
]);
$rows = $this->getClientInstance($httpClient)->fetchAll()->rows;
$this->assertCount(3, $rows);
$this->assertEquals([1, 2, 3], array_map(fn ($row) => $row->busProId, $rows));
$this->assertEquals(2, $httpClient->getRequestsCount());
}
public function testASinglePageIsNotFollowedByAnother(): void
{
$httpClient = $this->mockClient([$this->page([$this->row(1, 100)], 1, 1)]);
$this->getClientInstance($httpClient)->fetchAll();
$this->assertEquals(1, $httpClient->getRequestsCount());
}
public function testTheRequestedPageIsPassedOn(): void
{
$urls = [];
$httpClient = new MockHttpClient(function (string $method, string $url) use (&$urls) {
$urls[] = $url;
return $this->page([$this->row(count($urls), 100)], count($urls), 2);
}, 'https://myep.example/');
$this->getClientInstance($httpClient)->fetchAll();
// the path is asserted because it has already moved once - it was api/travels/export
// until MyE&P found that ambiguous against api/travels/{dateCode}
$this->assertStringStartsWith('https://myep.example/api/exports/travels?', $urls[0]);
$this->assertStringContainsString('page=1', $urls[0]);
$this->assertStringContainsString('page=2', $urls[1]);
$this->assertStringContainsString('perPage=500', $urls[0]);
}
public function testAnUnusableRowIsSkippedRatherThanFatal(): void
{
$httpClient = $this->mockClient([
$this->page([
['busProId' => 1],
$this->row(2, 200),
], 1, 1),
]);
$rows = $this->getClientInstance($httpClient)->fetchAll()->rows;
$this->assertCount(1, $rows);
$this->assertEquals(2, $rows[0]->busProId);
}
public function testAnEmptyExportYieldsNoRows(): void
{
$httpClient = $this->mockClient([$this->page([], 1, 1)]);
$this->assertEquals([], $this->getClientInstance($httpClient)->fetchAll()->rows);
}
public function testAPayloadWithoutADataListFails(): void
{
$httpClient = $this->mockClient([new MockResponse('{"meta":{"totalPages":1}}')]);
$this->expectException(ApiException::class);
$this->getClientInstance($httpClient)->fetchAll();
}
private function row(int $busProId, int $hotelBusProId): array
{
return [
'busProId' => $busProId,
'code' => 'CODE'.$busProId,
'product' => 'Produkt '.$busProId,
'dateFrom' => '2026-04-04',
'dateTo' => '2026-04-11',
'hotel' => [
'busProId' => $hotelBusProId,
'code' => 'AAA',
'name' => 'Haus',
'costUnit' => null,
'country' => 'CH',
'countryCode' => 'ch',
],
'pickups' => [],
];
}
/**
* Both counters are losses MyE&P made on its side - a dropped travel, a boarding point with no
* town - and the import is the only place they surface, so the client has to carry them out.
*/
public function testTheCountersMyEpReportsAreCarriedOut(): void
{
$httpClient = $this->mockClient([$this->page([$this->row(1, 100)], 1, 1, skipped: 3, pickupsWithoutMasterData: 21)]);
$export = $this->getClientInstance($httpClient)->fetchAll();
$this->assertSame(3, $export->skipped);
$this->assertSame(21, $export->pickupsWithoutMasterData);
$this->assertSame('2026-09-29T03:20:00+02:00', $export->generatedAt);
}
/**
* They describe the whole export rather than the page, so they repeat unchanged and the first
* page answers for the run. Reading the last one instead would be just as correct today and
* wrong the moment a page is served from a newer build.
*/
public function testTheCountersAreReadFromTheFirstPage(): void
{
$httpClient = $this->mockClient([
$this->page([$this->row(1, 100)], 1, 2, skipped: 3, pickupsWithoutMasterData: 21),
$this->page([$this->row(2, 200)], 2, 2, skipped: 99, pickupsWithoutMasterData: 99),
]);
$export = $this->getClientInstance($httpClient)->fetchAll();
$this->assertSame(3, $export->skipped);
$this->assertSame(21, $export->pickupsWithoutMasterData);
}
/**
* An export whose meta block says nothing must not read as one that dropped nothing by
* accident of a missing key, but zero is the only honest default available here.
*/
public function testAMetaBlockWithoutCountersReadsAsZero(): void
{
$httpClient = new MockHttpClient(
[new MockResponse(json_encode(['data' => [$this->row(1, 100)], 'meta' => ['totalPages' => 1]]))],
'https://myep.example/',
);
$export = $this->getClientInstance($httpClient)->fetchAll();
$this->assertSame(0, $export->skipped);
$this->assertSame(0, $export->pickupsWithoutMasterData);
$this->assertNull($export->generatedAt);
}
private function page(
array $rows,
int $page,
int $totalPages,
int $skipped = 0,
int $pickupsWithoutMasterData = 0,
): MockResponse {
return new MockResponse(json_encode([
'data' => $rows,
'meta' => [
'page' => $page,
'perPage' => 500,
'total' => count($rows),
'totalPages' => $totalPages,
'skipped' => $skipped,
'pickupsWithoutMasterData' => $pickupsWithoutMasterData,
'generatedAt' => '2026-09-29T03:20:00+02:00',
],
]));
}
private function mockClient(array $responses): MockHttpClient
{
return new MockHttpClient($responses, 'https://myep.example/');
}
private function getClientInstance(MockHttpClient $httpClient): TravelExportClient
{
$tokenClient = new MockHttpClient(
fn () => new MockResponse('{"access_token":"token","expires_in":600}'),
'https://myep.example/',
);
$tokens = new AccessTokenProvider($tokenClient, new ArrayAdapter(), new NullLogger(), [
'client_id' => 'team-app',
'client_secret' => 'secret',
]);
return new TravelExportClient(new ApiClient($httpClient, $tokens, new NullLogger()), new NullLogger());
}
}
+43 -19
View File
@@ -12,14 +12,12 @@ use App\Security\OAuth2\MyEpClient;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Flagception\Manager\FeatureManagerInterface;
use GuzzleHttp\Psr7\Request as Psr7Request;
use GuzzleHttp\Psr7\Response as Psr7Response;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Token\AccessToken;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
@@ -346,6 +344,38 @@ class MyEpAuthenticatorTest extends TestCase
$this->assertTrue($authenticator->supports($request));
}
public function testARejectedUserinfoRequestRefusesTheLogin(): void
{
$httpClient = new MockHttpClient(
new MockResponse('{"message":"Unauthorized"}', ['http_code' => 401]),
'https://my.example.com/',
);
$authenticator = $this->createAuthenticator($this->createUserinfo(['ROLE_TEAMER']), true, $httpClient);
$request = new Request(query: ['code' => 'code', 'state' => 'state']);
$request->setSession(new Session(new MockArraySessionStorage()));
$this->expectException(CustomUserMessageAuthenticationException::class);
$authenticator->authenticate($request);
}
public function testAnUnreadableUserinfoPayloadRefusesTheLogin(): void
{
$httpClient = new MockHttpClient(
new MockResponse('<html>gateway timeout</html>'),
'https://my.example.com/',
);
$authenticator = $this->createAuthenticator($this->createUserinfo(['ROLE_TEAMER']), true, $httpClient);
$request = new Request(query: ['code' => 'code', 'state' => 'state']);
$request->setSession(new Session(new MockArraySessionStorage()));
$this->expectException(CustomUserMessageAuthenticationException::class);
$authenticator->authenticate($request);
}
/**
* @param string[] $roles
*/
@@ -385,31 +415,25 @@ class MyEpAuthenticatorTest extends TestCase
return $user;
}
private function createAuthenticator(array $userinfo, bool $featureActive = true): MyEpAuthenticator
private function userinfoClient(array $userinfo): MockHttpClient
{
$httpClient = $this->createMock(ClientInterface::class);
$httpClient
->method('sendRequest')
->willReturn(new Psr7Response(200, [], json_encode($userinfo)))
;
$provider = $this->createMock(AbstractProvider::class);
$provider->method('getResourceOwnerDetailsUrl')->willReturn('https://my.example.com/api/userinfo');
$provider
->method('getAuthenticatedRequest')
->willReturn(new Psr7Request('GET', 'https://my.example.com/api/userinfo'))
;
$provider->method('getHttpClient')->willReturn($httpClient);
return new MockHttpClient(
new MockResponse(json_encode($userinfo)),
'https://my.example.com/',
);
}
private function createAuthenticator(array $userinfo, bool $featureActive = true, ?MockHttpClient $httpClient = null): MyEpAuthenticator
{
$client = $this->createMock(MyEpClient::class);
$client->method('fetchAccessToken')->willReturn(new AccessToken(['access_token' => 'token']));
$client->method('getProvider')->willReturn($provider);
$featureManager = $this->createMock(FeatureManagerInterface::class);
$featureManager->method('isActive')->willReturn($featureActive);
return new MyEpAuthenticator(
$client,
$httpClient ?? $this->userinfoClient($userinfo),
new UserDataHandler($this->entityManager, $this->createMock(LoggerInterface::class)),
$this->entityManager,
$this->createMock(UrlGeneratorInterface::class),
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service\Common;
use App\Model\AbstractFilterDto;
use App\Model\AssignmentFilterDto;
use App\Service\Common\AbstractFilterHandler;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* destination.country moved from the lowercased BusProNet abbreviations to ISO-2, but a
* session written before the deploy still holds the old value, and the filter is restored
* from the session rather than from the form. Without the translation those users would
* filter for a value no destination carries any more and see an empty list.
*
* Only a, ch, f and i can ever be in a session: those were the only four the filter forms
* offered. All four land inside the new choice list, so no stale value can fall outside it.
*/
class AbstractFilterHandlerTest extends TestCase
{
/**
* @dataProvider legacyCountries
*/
public function testALegacyCountryIsTranslatedToItsIsoCode(?string $stored, ?string $expected): void
{
$this->assertSame($expected, $this->handler()->translate($stored));
}
/**
* @return iterable<string, array{0: ?string, 1: ?string}>
*/
public static function legacyCountries(): iterable
{
// the four the filter forms offered, which is all a session can hold
yield 'Österreich' => ['a', 'at'];
yield 'Frankreich' => ['f', 'fr'];
yield 'Italien' => ['i', 'it'];
yield 'Schweiz was already ISO' => ['ch', 'ch'];
// never offered by a filter, so unreachable from a session - translated anyway
yield 'Deutschland' => ['d', 'de'];
yield 'Niederlande was already ISO' => ['nl', 'nl'];
yield 'no filter set' => [null, null];
yield 'an already migrated value is left alone' => ['at', 'at'];
yield 'an unknown value is not invented away' => ['xx', 'xx'];
}
public function testEveryTranslatedValueIsOfferedByTheFilterForm(): void
{
// what AssignmentFilterType and ApplicationFilterType offer
$offered = ['at', 'ch', 'fr', 'it'];
$handler = $this->handler();
foreach (['a', 'ch', 'f', 'i'] as $storable) {
$this->assertContains(
$handler->translate($storable),
$offered,
sprintf('A session holding "%s" would filter for a value the form cannot show', $storable),
);
}
}
private function handler(): object
{
return new class($this->createMock(RequestStack::class), $this->createMock(EntityManagerInterface::class)) extends AbstractFilterHandler {
protected string $modelClass = AssignmentFilterDto::class;
public function translate(?string $country): ?string
{
return $this->toIsoCountry($country);
}
public function getFilterSettings(): AbstractFilterDto
{
return new AssignmentFilterDto();
}
protected function saveFilterSettings(AbstractFilterDto $filterDto): void
{
}
};
}
}
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace App\Tests\Validator\Constraints;
use App\BusProNet\DataProvider\HotelDataProvider;
use App\BusProNet\Model\Hotel;
use App\Validator\Constraints\ResolvableHotel;
use App\Validator\Constraints\ResolvableHotelValidator;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* Everything a destination records about its house is derived from this lookup, so an id that
* does not resolve used to reach DestinationTrait::updateEntity() and fail there on a null -
* a 500 on a form submit rather than a message on a field.
*
* The two causes are reported apart on purpose. An unreachable MyE&P is not the operator's
* doing, and telling them their choice was invalid sends them hunting for a different answer
* when the one they gave was right.
*/
class ResolvableHotelValidatorTest extends ConstraintValidatorTestCase
{
public function testAResolvableHotelPasses(): void
{
$this->validator = $this->createValidator([163959 => $this->hotel()]);
$this->validator->initialize($this->context);
$this->validator->validate('163959', new ResolvableHotel());
$this->assertNoViolation();
}
public function testAHotelMissingFromALoadedListIsRejectedAsUnknown(): void
{
$constraint = new ResolvableHotel();
$this->validator = $this->createValidator([163959 => $this->hotel()]);
$this->validator->initialize($this->context);
$this->validator->validate('999999', $constraint);
$this->buildViolation($constraint->unknownMessage)->assertRaised();
}
/**
* StaleWhileErrorCache answers [] rather than throwing, so an empty list is the only signal
* that MyE&P could not be reached - and on a cold cache there is no stale copy to fall back to.
*/
public function testAnEmptyListIsReportedAsAnOutageRatherThanABadChoice(): void
{
$constraint = new ResolvableHotel();
$this->validator = $this->createValidator([]);
$this->validator->initialize($this->context);
$this->validator->validate('163959', $constraint);
$this->buildViolation($constraint->unavailableMessage)->assertRaised();
}
/**
* Whether a hotel was chosen at all belongs to NotBlank, which already sits on the property.
*/
public function testAnEmptyValueIsLeftToNotBlank(): void
{
$this->validator = $this->createValidator([]);
$this->validator->initialize($this->context);
$this->validator->validate(null, new ResolvableHotel());
$this->validator->validate('', new ResolvableHotel());
$this->assertNoViolation();
}
protected function createValidator(array $hotels = []): ResolvableHotelValidator
{
return new ResolvableHotelValidator($this->provider($hotels));
}
/**
* @return HotelDataProvider&MockObject
*/
private function provider(array $hotels): object
{
$provider = $this->createMock(HotelDataProvider::class);
$provider->method('getAll')->willReturn($hotels);
return $provider;
}
private function hotel(): Hotel
{
return (new Hotel())
->setBusProId(163959)
->setCode('LPJGR')
->setName('Sportclub Jenatsch')
;
}
}