Author SHA1 Message Date
frommeandClaude Opus 5 3221008f90 refactor: move the bulk export to its own /api/exports resource
/api/travels/{dateCode} accepts an arbitrary string, so /api/travels/export
shared a namespace with every date code and stayed reachable only because
byCode() carried a negative lookahead ruling that one string out. Nothing
in the URL announced the constraint, and getting it wrong mis-routed
silently: the first attempt widened the segment to `.+` and swallowed
/api/travels/{dateId}/{hotelId}/{dateTo}/availability whole.

/api/exports never takes a parameterised segment, the same shape as
/api/contingents, so the collision stops existing instead of being
guarded. TravelController returns byte-for-byte to its state on master,
lookahead included, and the export moves to its own resource controller.

The routing test now also asserts that nothing is reintroduced under the
date code namespace.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-29 14:23:36 +02:00
frommeandClaude Opus 5 b27639c7fa fix: keep the travel date code to a single path segment
The dateCode requirement added with the export route was `.+`, which
replaces Symfony's default `[^/]+` and lets the segment span slashes.
`/api/travels/{dateId}/{hotelId}/{dateTo}/availability` was then matched
by byCode() -- declared above it -- with dateCode swallowing all four
segments, so availability answered 404 "Not found" instead of reaching
the upstream call.

Adds a routing test that reflects the controller's own attributes, so
both the declaration order and the segment class stay guarded. Neither
fails loudly on its own: a path falling through to the wrong route reads
like an endpoint that exists and holds no data.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-29 14:19:24 +02:00
frommeandClaude Opus 5 ca1ab17595 docs: document the travel export endpoint and the new hotel fields
Also corrects the token TTL: the guide claimed one hour for
client_credentials, which stopped being true when the tagged grant
service was dropped. Every grant now issues a PT10M token.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-29 12:14:59 +02:00
frommeandClaude Opus 5 c5685e6d7c feat: add paginated travel export endpoint for the teamer app
GET /api/travels/export flattens the XML export into one row per travel
date x hotel with its pickups resolved, so the Teamer app can import the
disposition in one walk instead of fanning out over /api/travels.

Built from the XML file map, not travel_snapshot: the snapshot table sits
at this grain but refreshes on its own schedule, while the loaders share
the bpn.cache pool under the xml-sync tag. That is what makes /api/hotels,
/api/pickups and this export move together for free.

Each Ziel_*.xml is walked once and TravelParser::getPickups() does the
zeit parsing, which buys both zeit shapes and adjustOvernightTimes() --
a time-only 02:15 listed after a 23:59 rolls onto the next calendar day.
Pickups join against PickupLoader::loadAll() rather than
patchPickupsDetails(), which sorts: the contract is source order.

The whole assembled export is cached, not a page, so skipped, total and
pickupsWithoutMasterData are whole-export figures identical on every page
and a consumer can abort after the first one. Errors stay real status
codes; the builder is deliberately not wrapped in a catch that would
answer 200 with an error body the way hotelAvailability() does.

The route is declared before api_travel_single_code and that route grows
a requirement, or /api/travels/export resolves to byCode('export') and
404s as though the endpoint existed with no data.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-29 12:13:55 +02:00
frommeandClaude Opus 5 0a5602fd41 fix: skip travels whose hotel is missing from the master data
generateFilesMap() read ->name straight off $hotels[$hotelId] with no
guard, so a travel referencing a hotel absent from hotel.xml produced an
undefined-key warning and an entry with a null label -- a hotel in
/api/travels that resolves nowhere. No row hits this in the current
snapshot, which is why it has never surfaced.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-29 12:08:07 +02:00
frommeandClaude Opus 5 f3745f918e feat: expose hotel cost unit and iso country code via the api
The Teamer app groups hotels by cost unit and renders a flag per
destination, and cannot derive either from what /api/hotels returns
today.

costUnit is the raw kostenstelle and stays a string: only 281 of 1931
hotels carry one and some hold a space-separated list such as "84 85".

countryCode goes through CountryCodeMapper, whose table is part of the
API contract: BusPro's land column mixes ISO-2, ISO-3 and European
vehicle registration codes for the same country, and a wrong entry
mislabels a destination's flag silently. An unmappable token is null and
warns on the bpn channel, never a guess. country itself is untouched --
it remains the join key into /api/countries[].token.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-29 12:07:13 +02:00
frommeandClaude Opus 5 65c1a7bd12 feat: enable client credentials grant for machine-to-machine api clients
The Teamer app imports travel and hotel master data nightly with no user
in the loop. AuthorizationCodeListener is bound to
AUTHORIZATION_REQUEST_RESOLVE, which only the auth code grant dispatches,
so a userless token never reaches the required_roles gate.

Drops the tagged grant service added in 79709e3a. That tag registered
client_credentials through the bundle's @deprecated grant configurator,
which runs regardless of enable_client_credentials_grant and re-enabled
the grant a second time with its own PT1H. Two enableGrantType() calls
for one grant left the lifetime decided by call order. M2M tokens now use
the shared access_token_ttl of PT10M.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-29 12:04:05 +02:00
20 changed files with 1432 additions and 13 deletions

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@ league_oauth2_server:
private_key_passphrase: null
encryption_key: '%env(resolve:OAUTH_ENCRYPTION_KEY)%'
require_code_challenge_for_public_clients: true
enable_client_credentials_grant: false
enable_client_credentials_grant: true
enable_auth_code_grant: true
enable_refresh_token_grant: true
enable_password_grant: false
+9 -5
View File
@@ -207,6 +207,10 @@ services:
arguments:
$cache: '@bpn.cache'
App\BusProNet\Utility\CountryCodeMapper:
arguments:
$logger: '@monolog.logger.bpn'
App\BusProNet\XmlLoader\HotelLoader:
arguments:
$cache: '@bpn.cache'
@@ -219,6 +223,11 @@ services:
arguments:
$cache: '@bpn.cache'
App\Service\TravelExportBuilder:
arguments:
$cache: '@bpn.cache'
$logger: '@monolog.logger.bpn'
App\Service\VoucherValidator:
arguments:
$cache: '@cache.app'
@@ -386,8 +395,3 @@ services:
whitelisted_ips: '%env(csv:MAINTENANCE_MODE_IP_WHITELIST)%'
whitelisted_routes: '%env(csv:MAINTENANCE_MODE_ROUTE_WHITELIST)%'
whitelisted_paths: '%env(csv:MAINTENANCE_MODE_PATH_WHITELIST)%'
league.oauth2_server.grant.client_credentials:
class: League\OAuth2\Server\Grant\ClientCredentialsGrant
tags:
- { name: league.oauth2_server.authorization_server.grant, accessTokenTTL: 'PT1H' }
+122 -5
View File
@@ -10,8 +10,10 @@ A Symfony application exposing a read-mostly JSON API under the `/api` prefix. A
- Token endpoint: `POST /token` (unauthenticated).
- Enabled grants: **client_credentials**, **authorization_code** (PKCE required for public clients), **refresh_token**. Password and implicit grants are disabled.
- Access token TTL depends on the grant: **1 hour** for client_credentials, **10 minutes** for authorization_code.
Do not hardcode either value — read `expires_in` from the token response, it is authoritative and may be tuned.
- Access token TTL is **10 minutes** for every grant.
Do not hardcode it — read `expires_in` from the token response, it is authoritative and may be tuned.
A token can therefore expire part-way through a long page walk of `GET /api/exports/travels`; re-request one on
401 and resume at the page you were on. At the default `perPage=500` the whole export is a single page today.
- Available scopes: `email`, `id`, `profile`, `roles`, `api`. Default scope if none requested: `email`.
- Each granted scope maps to a role `ROLE_OAUTH2_<SCOPE_UPPERCASE>` (e.g. scope `api` → `ROLE_OAUTH2_API`).
- Send the token as `Authorization: Bearer <access_token>`.
@@ -48,7 +50,9 @@ There is no single error envelope; three shapes occur:
- `{"error": "...", "type": "api_error"}` — upstream failures on some endpoints. **Caution:** on `/api/products` and `/api/travels/{dateId}/{hotelId}/{dateTo}/availability` this shape is returned with HTTP **200**, so clients must check for the presence of an `error` key, not only the status code.
- `{"success": false, "message": "..."}` — the write endpoints (contact form, newsletter).
Validation failures on endpoints using mapped query strings / payloads (`/api/contingents/*`, `/api/newsletter-subscriptions`) return **400** with Symfony's constraint-violation body. Missing/invalid token yields **401**; insufficient scope yields **403**.
Validation failures on endpoints using mapped query strings / payloads (`/api/contingents/*`, `/api/exports/*`, `/api/newsletter-subscriptions`) return **400** with Symfony's constraint-violation body. Missing/invalid token yields **401**; insufficient scope yields **403**.
`GET /api/exports/travels` deliberately uses real status codes throughout and never the 200-with-an-`error`-key shape: a failure there is a 5xx, so retry logic can key on the status code alone.
The HTTP methods listed below are the intended ones. Several read routes do not restrict methods server-side; clients should still use `GET` for them.
@@ -60,11 +64,23 @@ The HTTP methods listed below are the intended ones. Several read routes do not
#### `GET /api/hotels` — scope `api`
List of hotels. Array of objects: `id` (int), `code` (string), `name`, `city`, `street`, `phone`, `country`.
List of hotels. Array of objects: `id` (int), `code` (string), `name`, `city`, `street`, `phone`, `country`,
`costUnit`, `countryCode`.
- `country` is the **raw** upstream token, unnormalised, and is the join key into `GET /api/countries[].token`.
It mixes conventions: ISO-2 (`CH`, `NL`), European vehicle registration codes (`D`, `A`, `F`, `S`, `FL`) and
ISO-3 (`AUT`, `PRT`, `HRV`), sometimes several for the same country.
- `countryCode` (`string|null`) is that token mapped to a lowercase ISO 3166-1 alpha-2 code — use this one to pick
a flag. A token with no confident mapping yields **`null`**, never a guess and never `""`, so treat null as
"unknown" rather than as an error. New tokens appear upstream from time to time; they surface as null here until
the mapping table is extended.
- `costUnit` (`string|null`) is the raw upstream cost centre. It is a **string, not a number**: most hotels have
none, and some carry a space-separated list such as `"84 85"`. Store it as text and do not parse it.
#### `GET /api/hotels/{id}` — scope `api`
Single hotel by numeric id, same field set as the list. `404 {"message":"Not found"}` if unknown.
Single hotel by numeric id, same field set as the list, including `costUnit` and `countryCode`.
`404 {"message":"Not found"}` if unknown.
#### `GET /api/countries` — scope `api`
@@ -123,6 +139,107 @@ This is a full overwrite, not a merge.
---
### Bulk exports
#### `GET /api/exports/travels` — scope `api`
Bulk export of every travel date × hotel pair with its boarding points resolved, for clients that mirror the
disposition locally. One request replaces a walk over `GET /api/travels` plus a per-pair detail call.
This is the only paginated endpoint and the only one with a `meta` envelope.
It sits under `/api/exports`, not `/api/travels`, on purpose: `/api/travels/{dateCode}` accepts an
arbitrary string, so an export hung off that collection would share a namespace with every date code.
`/api/exports` never takes a parameterised segment, so there is nothing for it to collide with.
Query parameters:
| Parameter | Type | Default | Notes |
|---|---|---|---|
| `page` | int ≥ 1 | `1` | Out of range is **not** clamped — see below |
| `perPage` | int 1–1000 | `500` | |
| `changedSince` | — | — | **Reserved, not implemented.** Sending it today is ignored; it is named here only so it is not claimed for anything else. |
A `page`/`perPage` outside those bounds returns **400** with Symfony's constraint-violation body (send
`Accept: application/json` to get it as JSON rather than an HTML error page). A `page` past the last one is *not*
an error: it returns `200` with an empty `data` array and the usual `meta`.
```json
{
"data": [
{
"busProId": 12794,
"code": "PCJSER261226",
"product": "Semesterende - Portes du Soleil - Joliment",
"dateFrom": "2026-12-26",
"dateTo": "2026-12-30",
"hotel": {
"busProId": 225444,
"code": "PCJSER1",
"name": "NEU SER Jolimont 1",
"costUnit": "863",
"country": "CH",
"countryCode": "ch"
},
"pickups": [
{
"busProId": 18,
"code": "ESS-Route",
"city": "Essen",
"street": "Am Hauptbahnhof (Südausgang Fernbushaltestelle)",
"time": "20:15",
"datetime": "2026-12-25T20:15:00+01:00"
}
]
}
],
"meta": {
"page": 1,
"perPage": 500,
"total": 415,
"totalPages": 1,
"skipped": 0,
"pickupsWithoutMasterData": 0,
"generatedAt": "2026-09-29T12:10:06+02:00"
}
}
```
**Row identity.** `(busProId, hotel.busProId)` is unique across the whole export — upsert on that pair. `busProId`
is always an int and never null; `hotel` is always an object and never null; `pickups` is always an array, possibly
empty, never null.
**`meta` describes the whole export, not the page.** `total`, `totalPages`, `skipped`, `pickupsWithoutMasterData`
and `generatedAt` are identical on every page, so you can read them once on page 1 and decide whether to walk the
rest. `total` is the row count **after** skips, and `totalPages` is `ceil(total / perPage)`.
- `skipped` — (travel, hotel) pairs dropped as unusable: a travel date that could not be parsed, or a hotel absent
from the hotel master data. Expect `0`. A non-zero value means upstream data is inconsistent, not that you have
lost rows you previously had.
- `pickupsWithoutMasterData` — count of **distinct** pickup ids referenced by a travel but absent from
`GET /api/pickups`. Those entries are still emitted, with `code`, `city` and `street` null: a departure point
with no name is more useful to a disposition view than one that silently vanished.
**Pickup times.** `pickups` is in **source order** — the order the boarding list is driven in — not sorted by time.
- `time` is `"HH:MM"` for display; `datetime` is the same moment as a full ISO-8601 string with a
`Europe/Berlin` offset (`+01:00` / `+02:00` depending on DST). **Prefer `datetime`.**
- Upstream states a boarding time either as a full date and time or as a bare time. A bare time is resolved
against the departure date and, where the sequence demands it, rolled onto the following calendar day — so an
`02:15` listed after a `23:59` comes back on the next date, not the same one. `datetime` is emitted for
bare-time sources too, and carries that resolution.
- A boarding point with no time upstream comes back with **both** `time` and `datetime` null. They are always
null together.
- Caveat: where upstream states full datetimes for a whole boarding list, those dates are taken verbatim. Some
lists date every stop to the evening before departure, including stops after midnight, so an entry can appear a
day earlier than the running order implies. This is upstream data, not a transformation applied here.
**Consistency.** The export is built from the same cached master data as `GET /api/hotels` and `GET /api/pickups`,
under one cache tag, so all three move together on an upstream sync rather than drifting between your calls.
It is cached for 3 hours; `generatedAt` is when the cached copy was assembled, not when you requested it.
---
### Travels
#### `GET /api/travels` — scope `api`
+11
View File
@@ -35,4 +35,15 @@ class Hotel
#[Groups(['api:list', 'api:single', 'snapshot'])]
public ?string $country = null;
/**
* Raw `kostenstelle`, deliberately a string: coverage is thin and some hotels carry a
* space-separated list such as "84 85", so it is an opaque label, not a number.
*/
#[Groups(['api:list', 'api:single', 'snapshot'])]
public ?string $costUnit = null;
/** {@see \App\BusProNet\Utility\CountryCodeMapper} — lowercase ISO-2, null when unmappable. */
#[Groups(['api:list', 'api:single', 'snapshot'])]
public ?string $countryCode = null;
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\BusProNet\Utility;
use Psr\Log\LoggerInterface;
/**
* Maps BusPro's `hotel/land` token onto a lowercase ISO 3166-1 alpha-2 code.
*
* BusPro has no country vocabulary: the field is free text that has accumulated three
* conventions side by side — ISO-2 (`CH`, `NL`), the European vehicle registration codes
* (`D`, `A`, `F`, `S`, `FL`) and ISO-3 (`AUT`, `PRT`, `HRV`), with the same country often
* under several tokens. The table below is therefore part of the API contract rather than
* a derivation: consumers render a flag from it, and a wrong entry mislabels a destination
* silently, which is worse than no flag at all. An unknown token maps to null — never to a
* guess, never to an empty string.
*/
class CountryCodeMapper
{
/**
* Keys are upper-cased tokens, values lowercase ISO-2.
*
* Entries worth their explanation:
* - `IR` is Ireland, not Iran. Every row carrying it is Dublin or Carlow.
* - `SLO` is Slovakia here, not Slovenia: its only row is a Slovak company, and
* Slovenia already arrives under its own `SI`.
* - `S`, `N`, `FL` are vehicle codes (Sweden, Norway, Liechtenstein), consistent with
* the `D`/`A`/`F`/`I`/`E`/`B` in the same column.
* - `UK` is the colloquial form of the ISO `GB`.
*
* @var array<string, string>
*/
private const MAP = [
'A' => 'at',
'AT' => 'at',
'AUT' => 'at',
'B' => 'be',
'CA' => 'ca',
'CH' => 'ch',
'CZ' => 'cz',
'D' => 'de',
'DEU' => 'de',
'DK' => 'dk',
'E' => 'es',
'ES' => 'es',
'F' => 'fr',
'FI' => 'fi',
'FL' => 'li',
'FR' => 'fr',
'GR' => 'gr',
'GRE' => 'gr',
'HR' => 'hr',
'HRV' => 'hr',
'HU' => 'hu',
'I' => 'it',
'IL' => 'il',
'IR' => 'ie',
'IS' => 'is',
'IT' => 'it',
'LT' => 'lt',
'LV' => 'lv',
'MT' => 'mt',
'N' => 'no',
'NL' => 'nl',
'PL' => 'pl',
'PRT' => 'pt',
'PT' => 'pt',
'RUS' => 'ru',
'S' => 'se',
'SI' => 'si',
'SLO' => 'sk',
'UK' => 'gb',
'USA' => 'us',
'ZA' => 'za',
];
/**
* Tokens already reported in this process, so a master data file full of the same
* unknown token produces one log line rather than one per hotel.
*
* @var array<string, true>
*/
private array $reported = [];
public function __construct(
private readonly LoggerInterface $logger,
) {
}
/**
* @param string|null $token the raw `hotel/land` value
*
* @return string|null lowercase ISO-2, or null when absent, empty or unmappable
*/
public function map(?string $token): ?string
{
if (null === $token) {
return null;
}
$normalized = strtoupper(trim($token));
if ('' === $normalized) {
return null;
}
if (isset(self::MAP[$normalized])) {
return self::MAP[$normalized];
}
if (false === isset($this->reported[$normalized])) {
$this->reported[$normalized] = true;
$this->logger->warning('Unmapped BusPro country token', ['token' => $token]);
}
return null;
}
}
+15
View File
@@ -4,14 +4,25 @@ namespace App\BusProNet\XmlLoader;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Travel;
use App\BusProNet\Utility\CountryCodeMapper;
use App\BusProNet\XmlCrawlerFactory;
use App\Exception\HotelNotFoundException;
use League\Flysystem\FilesystemOperator;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
class HotelLoader extends AbstractLoader
{
public function __construct(
private readonly CountryCodeMapper $countryCodeMapper,
CacheInterface $cache,
FilesystemOperator $xmlExport,
) {
parent::__construct($cache, $xmlExport);
}
/** @return array<int, Hotel> */
public function loadAll(?string $filename = 'hotel.xml'): array
{
@@ -87,6 +98,10 @@ class HotelLoader extends AbstractLoader
$hotel->country = $this->getStringOrNullValue($node->filterXPath('//land'));
$hotel->street = $this->getStringOrNullValue($node->filterXPath('//strasse'));
$hotel->phone = $this->getStringOrNullValue($node->filterXPath('//telefon'));
// String, never int: see Hotel::$costUnit.
$hotel->costUnit = $this->getStringOrNullValue($node->filterXPath('//kostenstelle'));
// `country` itself stays the raw token — it is the join key into /api/countries[].token.
$hotel->countryCode = $this->countryCodeMapper->map($hotel->country);
return $hotel;
}
+7
View File
@@ -92,6 +92,13 @@ class TravelLoader extends AbstractLoader
->each(function (Crawler $hotelNode) use (&$mapping, $hotels, $travelId) {
$hotelId = (int) $hotelNode->attr('idbuspro');
// A travel may reference a hotel that hotel.xml does not carry.
// Reading ->name off the miss would fatal the whole mapping, not
// just this entry, and take /api/travels down with it.
if (false === isset($hotels[$hotelId])) {
return;
}
$mapping[$travelId]['hotels'][$hotelId] = [
'id' => $hotelId,
'code' => $hotelNode->attr('code'),
+66
View File
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace App\Controller\Api;
use App\Model\TravelExportQuery;
use App\Service\TravelExportBuilder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Bulk exports, for consumers that mirror our data rather than query it per row.
*
* Deliberately its own resource rather than a verb hung off the collection it exports.
* `/api/travels/{dateCode}` accepts an arbitrary string, so an `/api/travels/export` would
* share a namespace with every date code and could only be kept apart from one by a
* negative lookahead on the sibling route -- a constraint nothing in the URL announces and
* which silently mis-routes when it is wrong. Under `/api/exports` the collision does not
* exist: this prefix never takes a parameterised segment, exactly like `/api/contingents`.
*/
#[Route('/api/exports')]
#[IsGranted('ROLE_OAUTH2_API')]
class ExportController extends AbstractController
{
public function __construct(
private readonly TravelExportBuilder $travelExportBuilder,
) {
}
/**
* Every travel date x hotel pair with its pickups resolved, paginated.
*
* The counters in meta describe the whole export, not the page, so they repeat
* unchanged on every page and a consumer can abort after the first one.
*/
#[Route(path: '/travels', name: 'api_exports_travels', methods: ['GET'])]
public function travels(
#[MapQueryString(validationFailedStatusCode: Response::HTTP_BAD_REQUEST)]
TravelExportQuery $query = new TravelExportQuery(),
): JsonResponse {
// Deliberately not wrapped in a catch that answers 200 with an error body, the way
// TravelController::hotelAvailability() does: the consumer's retry logic keys on
// status codes, so a failure here has to surface as a 5xx.
$export = $this->travelExportBuilder->build();
$total = count($export->rows);
return $this->json([
'data' => array_slice($export->rows, ($query->page - 1) * $query->perPage, $query->perPage),
'meta' => [
'page' => $query->page,
'perPage' => $query->perPage,
'total' => $total,
'totalPages' => (int) ceil($total / $query->perPage),
'skipped' => $export->skipped,
'pickupsWithoutMasterData' => $export->pickupsWithoutMasterData,
'generatedAt' => $export->generatedAt->format('c'),
],
]);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Model;
/**
* The whole travel-date x hotel export plus the counters that describe how it was built.
*
* Held in the bpn.cache pool as one unit and paginated in the controller, which is what
* makes the counters identical on every page: they describe the export, not the page, so a
* consumer can read them once and abort the page walk on the first response.
*
* @see \App\Service\TravelExportBuilder
*/
final readonly class TravelExport
{
/**
* @param list<array<string, mixed>> $rows one row per (travel, hotel) pair
* @param int $skipped (travel, hotel) pairs 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 \DateTimeImmutable $generatedAt,
) {
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Model;
use Symfony\Component\Validator\Constraints as Assert;
final readonly class TravelExportQuery
{
public function __construct(
#[Assert\Positive]
public int $page = 1,
#[Assert\Range(min: 1, max: 1000)]
public int $perPage = 500,
) {
}
}
+253
View File
@@ -0,0 +1,253 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Pickup;
use App\BusProNet\Traits\TypeConversionTrait;
use App\BusProNet\XmlCrawlerFactory;
use App\BusProNet\XmlLoader\HotelLoader;
use App\BusProNet\XmlLoader\PickupLoader;
use App\BusProNet\XmlParser\TravelParser;
use App\Model\TravelExport;
use League\Flysystem\FilesystemOperator;
use League\Flysystem\StorageAttributes;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
/**
* Flattens the BusPro XML export into one row per travel date x hotel, pickups resolved.
*
* Built from the XML file map rather than the travel_snapshot table. The table sits at
* exactly this grain and is tempting, but it is refreshed on its own schedule, independent
* of the master-data caches. Only the loaders share the bpn.cache pool under the xml-sync
* tag, and that is what makes the consistency guarantee hold for free: /api/hotels,
* /api/pickups and this export all move together when app:bpn:xml-sync invalidates the tag.
*
* Each Ziel_*.xml is read and walked exactly once. Looping TravelLoader::loadById() per row
* would re-parse a whole file -- rooms, services, prices -- once per hotel on the date.
*/
class TravelExportBuilder
{
use TypeConversionTrait;
private const CACHE_KEY = 'bpn_travels_export';
public function __construct(
private readonly HotelLoader $hotelLoader,
private readonly PickupLoader $pickupLoader,
private readonly TravelParser $travelParser,
private readonly FilesystemOperator $xmlExport,
private readonly CacheInterface $cache,
private readonly LoggerInterface $logger,
) {
}
/**
* Assembles the whole export, cached as one unit alongside the sibling loaders.
*/
public function build(): TravelExport
{
try {
return $this->cache->get(self::CACHE_KEY, function (ItemInterface $item) {
$item->expiresAfter(3 * 60 * 60);
$item->tag(['xml-sync']);
return $this->assemble();
});
} catch (InvalidArgumentException $e) {
throw new \RuntimeException('Cache key error in TravelExportBuilder', 0, $e);
}
}
private function assemble(): TravelExport
{
$hotels = $this->hotelLoader->loadAll();
$pickupMasterData = $this->pickupLoader->loadAll();
/** @var array<string, array<string, mixed>> $rows keyed by travelId-hotelId */
$rows = [];
$skipped = 0;
/** @var array<int, true> $pickupsWithoutMasterData */
$pickupsWithoutMasterData = [];
$files = $this
->xmlExport
->listContents('.')
->filter(fn (StorageAttributes $attributes) => $attributes->isFile() && str_starts_with($attributes->path(), 'Ziel_'));
foreach ($files as $file) {
$crawler = XmlCrawlerFactory::create($this->xmlExport->read($file->path()));
$crawler->filterXPath('//reisen/reise/termin')->each(
function (Crawler $node) use (&$rows, &$skipped, &$pickupsWithoutMasterData, $hotels, $pickupMasterData) {
$this->collectTravel($node, $rows, $skipped, $pickupsWithoutMasterData, $hotels, $pickupMasterData);
}
);
}
return new TravelExport(
array_values($rows),
$skipped,
count($pickupsWithoutMasterData),
new \DateTimeImmutable(),
);
}
/**
* @param array<string, array<string, mixed>> $rows
* @param array<int, true> $pickupsWithoutMasterData
* @param array<int, Hotel> $hotels
* @param array<int|string, Pickup> $pickupMasterData
*/
private function collectTravel(
Crawler $node,
array &$rows,
int &$skipped,
array &$pickupsWithoutMasterData,
array $hotels,
array $pickupMasterData,
): void {
$hotelNodes = $node->filterXPath('.//hotel');
// Dates first: getPickups() needs a non-null default date for the time-only zeit
// shape, and parsing them up front is also what turns an unusable date into a
// dropped row rather than a row with a null date the consumer cannot key on.
$dateFrom = $this->stringToDate($node->attr('termin'));
$dateTo = $this->stringToDate($node->attr('bis'));
if (null === $dateFrom || null === $dateTo) {
$this->logger->warning('Travel export: unparseable travel date', [
'travel_id' => $node->attr('idbuspro'),
'termin' => $node->attr('termin'),
'bis' => $node->attr('bis'),
]);
$skipped += $hotelNodes->count();
return;
}
$travelId = (int) $node->attr('idbuspro');
// getPickups() is what buys stringToDateTimeFuzzy() for both zeit shapes and
// adjustOvernightTimes(), which rolls an 02:15 listed after a 23:59 onto the next
// calendar day. Resolved once per travel date, then shared by its hotel rows.
$pickups = $this->buildPickups(
$this->travelParser->getPickups($node->filterXPath('.//zustiege/zustieg'), $dateFrom, true),
$pickupMasterData,
$pickupsWithoutMasterData,
);
$travel = [
'busProId' => $travelId,
'code' => $node->attr('code'),
'product' => $this->trimOrNull($this->getStringOrNullValue($node->filterXPath('.//text'))),
'dateFrom' => $dateFrom->format('Y-m-d'),
'dateTo' => $dateTo->format('Y-m-d'),
];
$hotelNodes->each(function (Crawler $hotelNode) use (&$rows, &$skipped, $hotels, $travel, $travelId, $pickups) {
$hotelId = (int) $hotelNode->attr('idbuspro');
// Defensive: no travel in the current snapshot references a hotel that
// hotel.xml does not carry. A row without master data would reach the consumer
// with no name and no country, so it is dropped and counted instead.
if (false === isset($hotels[$hotelId])) {
$this->logger->warning('Travel export: hotel missing from master data', [
'travel_id' => $travelId,
'hotel_id' => $hotelId,
]);
++$skipped;
return;
}
$hotel = $hotels[$hotelId];
// Keyed by the pair the consumer upserts on, so a date repeated across files
// collapses last-wins instead of reaching it as a duplicate.
$rows[$travelId.'-'.$hotelId] = $travel + [
'hotel' => [
'busProId' => $hotelId,
'code' => $hotel->code,
'name' => $hotel->name,
'costUnit' => $hotel->costUnit,
'country' => $hotel->country,
'countryCode' => $hotel->countryCode,
],
'pickups' => $pickups,
];
});
}
/**
* Joins the travel XML's pickups against zustiege.xml.
*
* Deliberately not PickupLoader::patchPickupsDetails(), which sorts by time -- the
* contract is source order, which is the order the disposition lists them in. Nor
* enrichPickupDetails(), which is private and passes over a miss silently.
*
* @param array<int, Pickup> $pickups pickups indexed by id, in source order
* @param array<int|string, Pickup> $masterData
* @param array<int, true> $pickupsWithoutMasterData
*
* @return list<array<string, mixed>>
*/
private function buildPickups(array $pickups, array $masterData, array &$pickupsWithoutMasterData): array
{
$resolved = [];
foreach ($pickups as $pickup) {
$pickupId = $pickup->id;
// Defensive: none exist today. An entry with no id is not addressable by the
// consumer, so drop the entry -- never the row it belongs to.
if (null === $pickupId || 0 === $pickupId) {
continue;
}
$details = $masterData[$pickupId] ?? null;
// Around 21 ids referenced by travel XML have no entry in zustiege.xml. The
// entry is emitted anyway: dropping it would hide a real departure point from
// the disposition UI, where a nameless stop is still better than a missing one.
if (null === $details) {
$pickupsWithoutMasterData[$pickupId] = true;
}
$resolved[] = [
'busProId' => $pickupId,
'code' => $details?->code,
'city' => $details?->city,
'street' => $details?->street,
'time' => $pickup->time?->format('H:i'),
// Emitted for time-only sources too: adjustOvernightTimes() has already
// worked out the real day, and a null here would throw that away.
'datetime' => $pickup->time?->format('c'),
];
}
return $resolved;
}
private function getStringOrNullValue(Crawler $node): ?string
{
return 0 < $node->count() ? $node->text() : null;
}
private function trimOrNull(?string $value): ?string
{
if (null === $value) {
return null;
}
$trimmed = trim($value);
return '' === $trimmed ? null : $trimmed;
}
}
@@ -3,9 +3,11 @@
namespace App\Tests\BusProNet\DataLoader;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Utility\CountryCodeMapper;
use App\BusProNet\XmlLoader\HotelLoader;
use League\Flysystem\FilesystemOperator;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
@@ -34,7 +36,7 @@ class HotelDataLoaderTest extends TestCase
->willReturn($xmlContent);
$cache = new TagAwareAdapter(new ArrayAdapter());
$loader = new HotelLoader($cache, $filesystem);
$loader = new HotelLoader(new CountryCodeMapper(new NullLogger()), $cache, $filesystem);
$hotels = $loader->loadAll();
@@ -50,5 +52,7 @@ class HotelDataLoaderTest extends TestCase
$this->assertEquals('F', $hotel->country);
$this->assertEquals('Rue des Lacs', $hotel->street);
$this->assertEquals('', $hotel->phone);
$this->assertEquals('fr', $hotel->countryCode);
$this->assertNull($hotel->costUnit);
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace App\Tests\BusProNet\Utility;
use App\BusProNet\Utility\CountryCodeMapper;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
class CountryCodeMapperTest extends TestCase
{
/**
* @return array<string, array{string, string}>
*/
public static function tokenProvider(): array
{
return [
'iso-2 passes through' => ['CH', 'ch'],
'vehicle code D' => ['D', 'de'],
'iso-3 DEU' => ['DEU', 'de'],
'vehicle code A' => ['A', 'at'],
'iso-2 AT' => ['AT', 'at'],
'iso-3 AUT' => ['AUT', 'at'],
'vehicle code F' => ['F', 'fr'],
'vehicle code I' => ['I', 'it'],
'iso-2 IT' => ['IT', 'it'],
'vehicle code E' => ['E', 'es'],
'vehicle code B' => ['B', 'be'],
'vehicle code S is Sweden' => ['S', 'se'],
'vehicle code N is Norway' => ['N', 'no'],
'vehicle code FL is Liechtenstein' => ['FL', 'li'],
'IR is Ireland, not Iran' => ['IR', 'ie'],
'UK maps to the iso GB' => ['UK', 'gb'],
'iso-3 PRT' => ['PRT', 'pt'],
'iso-3 GRE' => ['GRE', 'gr'],
'iso-3 HRV' => ['HRV', 'hr'],
'iso-3 RUS' => ['RUS', 'ru'],
'iso-3 USA' => ['USA', 'us'],
'SI is Slovenia' => ['SI', 'si'],
'SLO is Slovakia' => ['SLO', 'sk'],
'ZA is South Africa' => ['ZA', 'za'],
];
}
#[DataProvider('tokenProvider')]
public function testMapsKnownToken(string $token, string $expected): void
{
$this->assertSame($expected, (new CountryCodeMapper(new NullLogger()))->map($token));
}
public function testEveryMappedCodeIsLowercaseIsoTwo(): void
{
$mapper = new CountryCodeMapper(new NullLogger());
foreach (array_keys(self::tokenProvider()) as $name) {
[$token] = self::tokenProvider()[$name];
$code = $mapper->map($token);
$this->assertNotNull($code);
$this->assertMatchesRegularExpression('/^[a-z]{2}$/', $code, $token.' must map to lowercase ISO-2');
}
}
public function testIsCaseAndWhitespaceInsensitive(): void
{
$mapper = new CountryCodeMapper(new NullLogger());
$this->assertSame('ch', $mapper->map('ch'));
$this->assertSame('at', $mapper->map(' aut '));
}
public function testUnknownTokenMapsToNullAndWarnsOnce(): void
{
$logger = $this->createMock(LoggerInterface::class);
$logger
->expects($this->once())
->method('warning')
->with('Unmapped BusPro country token', ['token' => 'XX']);
$mapper = new CountryCodeMapper($logger);
$this->assertNull($mapper->map('XX'));
$this->assertNull($mapper->map('XX'));
}
public function testAbsentTokenMapsToNullWithoutWarning(): void
{
$logger = $this->createMock(LoggerInterface::class);
$logger
->expects($this->never())
->method('warning');
$mapper = new CountryCodeMapper($logger);
$this->assertNull($mapper->map(null));
$this->assertNull($mapper->map(''));
$this->assertNull($mapper->map(' '));
}
}
+65 -1
View File
@@ -5,10 +5,14 @@ declare(strict_types=1);
namespace App\Tests\BusProNet\XmlLoader;
use App\BusProNet\Model\Travel;
use App\BusProNet\Utility\CountryCodeMapper;
use App\BusProNet\XmlCrawlerFactory;
use App\BusProNet\XmlLoader\HotelLoader;
use League\Flysystem\FilesystemOperator;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\DomCrawler\Crawler;
class HotelLoaderTest extends TestCase
{
@@ -19,7 +23,7 @@ class HotelLoaderTest extends TestCase
->expects($this->never())
->method('read');
$loader = new HotelLoader(new ArrayAdapter(), $filesystem);
$loader = $this->createLoader($filesystem);
$travel = new Travel();
$travel->hotelId = null;
$travel->hotel = null;
@@ -28,4 +32,64 @@ class HotelLoaderTest extends TestCase
$this->assertNull($travel->hotel);
}
public function testParseXmlMapsCostUnitAndCountryCode(): void
{
$hotel = $this->createLoader()->parseXml($this->hotelNode(
'<kostenstelle>83</kostenstelle><land>CH</land>'
));
$this->assertSame('83', $hotel->costUnit);
$this->assertSame('CH', $hotel->country, 'the raw token is the join key and must not be rewritten');
$this->assertSame('ch', $hotel->countryCode);
}
public function testParseXmlKeepsAListOfCostUnitsAsAString(): void
{
$hotel = $this->createLoader()->parseXml($this->hotelNode(
'<kostenstelle>84 85</kostenstelle><land>D</land>'
));
$this->assertSame('84 85', $hotel->costUnit);
}
public function testParseXmlLeavesCostUnitNullWhenAbsent(): void
{
$hotel = $this->createLoader()->parseXml($this->hotelNode('<land>D</land>'));
$this->assertNull($hotel->costUnit);
$this->assertSame('de', $hotel->countryCode);
}
public function testParseXmlLeavesBothCountryFieldsNullWhenLandIsAbsent(): void
{
$hotel = $this->createLoader()->parseXml($this->hotelNode('<name>Ohne Land</name>'));
$this->assertNull($hotel->country);
$this->assertNull($hotel->countryCode);
}
public function testParseXmlLeavesCountryCodeNullForAnUnmappableToken(): void
{
$hotel = $this->createLoader()->parseXml($this->hotelNode('<land>XX</land>'));
$this->assertSame('XX', $hotel->country);
$this->assertNull($hotel->countryCode, 'an unknown token must never be guessed into a code');
}
private function hotelNode(string $children): Crawler
{
$xml = sprintf('<hotels><hotel idbuspro="1" code="TEST">%s</hotel></hotels>', $children);
return XmlCrawlerFactory::create($xml)->filterXPath('//hotels/hotel');
}
private function createLoader(?FilesystemOperator $filesystem = null): HotelLoader
{
return new HotelLoader(
new CountryCodeMapper(new NullLogger()),
new ArrayAdapter(),
$filesystem ?? $this->createStub(FilesystemOperator::class),
);
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Tests\BusProNet\XmlLoader;
use App\BusProNet\Model\Hotel;
use App\BusProNet\XmlLoader\HotelLoader;
use App\BusProNet\XmlLoader\TravelLoader;
use App\BusProNet\XmlParser\TravelParser;
use League\Flysystem\DirectoryListing;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemOperator;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
class TravelLoaderFilesMapTest extends TestCase
{
private const XML = '<?xml version="1.0" encoding="utf-8"?>
<reisen>
<reise code="SBW">
<termin idbuspro="900" code="SBW250101" termin="01.01.2025" bis="08.01.2025">
<text>Skiwoche</text>
<hotel idbuspro="1" code="KNOWN"/>
<hotel idbuspro="999" code="GHOST"/>
</termin>
</reise>
</reisen>';
/**
* A travel may reference a hotel id that hotel.xml does not carry. Before the guard the
* miss was dereferenced, which fataled the whole cached mapping rather than one entry --
* so /api/travels went down entirely, not just the affected travel.
*/
public function testGenerateFilesMapSkipsHotelsMissingFromMasterData(): void
{
$known = new Hotel();
$known->id = 1;
$known->name = 'Hotel Bekannt';
$hotelLoader = $this->createStub(HotelLoader::class);
$hotelLoader->method('loadAll')->willReturn([1 => $known]);
$filesystem = $this->createStub(FilesystemOperator::class);
$filesystem->method('listContents')->willReturn(
new DirectoryListing([new FileAttributes('Ziel_1.xml')])
);
$filesystem->method('read')->willReturn(self::XML);
$loader = new TravelLoader(
$hotelLoader,
$this->createStub(TravelParser::class),
'https://example.test',
new TagAwareAdapter(new ArrayAdapter()),
$filesystem,
);
$mapping = $loader->generateFilesMap();
$this->assertArrayHasKey(900, $mapping);
$this->assertSame([1], array_keys($mapping[900]['hotels']));
$this->assertSame('Hotel Bekannt', $mapping[900]['hotels'][1]['label']);
}
}
@@ -0,0 +1,132 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Api;
use App\Controller\Api\ExportController;
use App\Model\TravelExport;
use App\Model\TravelExportQuery;
use App\Service\TravelExportBuilder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Response;
class ExportControllerTest extends TestCase
{
public function testPaginatesAndReportsWholeExportFigures(): void
{
$meta = $this->call(new TravelExportQuery(1, 5))['meta'];
self::assertSame(1, $meta['page']);
self::assertSame(5, $meta['perPage']);
self::assertSame(12, $meta['total'], 'total is the whole export, not this page');
self::assertSame(3, $meta['totalPages']);
}
public function testCountersAreIdenticalOnEveryPage(): void
{
// Whole-export figures repeated per page, so a consumer can abort after page 1.
$first = $this->call(new TravelExportQuery(1, 5))['meta'];
$last = $this->call(new TravelExportQuery(3, 5))['meta'];
foreach (['total', 'totalPages', 'skipped', 'pickupsWithoutMasterData', 'generatedAt'] as $key) {
self::assertSame($first[$key], $last[$key], $key.' must not vary by page');
}
}
public function testConsecutivePagesDoNotOverlap(): void
{
$first = array_column($this->call(new TravelExportQuery(1, 5))['data'], 'busProId');
$second = array_column($this->call(new TravelExportQuery(2, 5))['data'], 'busProId');
self::assertSame([1, 2, 3, 4, 5], $first);
self::assertSame([6, 7, 8, 9, 10], $second);
self::assertSame([], array_intersect($first, $second));
}
public function testTheLastPageIsShort(): void
{
$data = $this->call(new TravelExportQuery(3, 5))['data'];
self::assertCount(2, $data);
self::assertSame([11, 12], array_column($data, 'busProId'));
}
public function testAPageBeyondTheEndIsEmptyRatherThanAnError(): void
{
$body = $this->call(new TravelExportQuery(99, 5));
self::assertSame([], $body['data']);
self::assertSame(12, $body['meta']['total']);
}
public function testDefaultsToTheFirstPageOfFiveHundred(): void
{
$body = $this->call();
self::assertSame(1, $body['meta']['page']);
self::assertSame(500, $body['meta']['perPage']);
self::assertSame(1, $body['meta']['totalPages']);
self::assertCount(12, $body['data']);
}
public function testCarriesTheBuilderCounters(): void
{
$meta = $this->call(null, 7, 21)['meta'];
self::assertSame(7, $meta['skipped']);
self::assertSame(21, $meta['pickupsWithoutMasterData']);
self::assertSame('2026-09-29T03:20:00+02:00', $meta['generatedAt']);
}
/**
* A builder failure must reach the consumer as a 5xx, never as the 200-with-an-error-body
* shape TravelController::hotelAvailability() uses: the retry logic keys on the status code.
*/
public function testABuilderFailureIsNotDowngradedToATwoHundred(): void
{
$builder = $this->createStub(TravelExportBuilder::class);
$builder->method('build')->willThrowException(new \RuntimeException('cache exploded'));
$this->expectException(\RuntimeException::class);
$this->controller($builder)->travels(new TravelExportQuery());
}
/**
* @return array<string, mixed>
*/
private function call(?TravelExportQuery $query = null, int $skipped = 0, int $withoutMasterData = 0): array
{
$rows = [];
for ($i = 1; $i <= 12; ++$i) {
$rows[] = ['busProId' => $i, 'hotel' => ['busProId' => 1], 'pickups' => []];
}
$builder = $this->createStub(TravelExportBuilder::class);
$builder->method('build')->willReturn(new TravelExport(
$rows,
$skipped,
$withoutMasterData,
new \DateTimeImmutable('2026-09-29 03:20:00', new \DateTimeZone('Europe/Berlin')),
));
$response = $this->controller($builder)->travels($query ?? new TravelExportQuery());
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
return json_decode((string) $response->getContent(), true);
}
private function controller(TravelExportBuilder $builder): ExportController
{
$controller = new ExportController($builder);
// No 'serializer' service registered, so AbstractController::json() falls back to
// JsonResponse -- which is what this endpoint produces in production anyway.
$controller->setContainer(new Container());
return $controller;
}
}
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Api;
use App\Controller\Api\ExportController;
use App\Controller\Api\TravelController;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Routing\Attribute\Route as RouteAttribute;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Guards the /api/travels namespace against a sibling route being swallowed by byCode().
*
* `/api/travels/{dateCode}` accepts an arbitrary string, so anything else placed under
* `/api/travels/` competes with every date code, and a path falling through to the wrong
* route answers 404 with a body that reads like an endpoint holding no data. The bulk
* export lives at `/api/exports/travels` for exactly this reason. The collection is built
* by reflecting over the real attributes, so this breaks if the declarations change.
*/
class TravelControllerRoutingTest extends TestCase
{
/**
* @return array<string, array{string, string}>
*/
public static function pathProvider(): array
{
return [
'the export lives outside the travels namespace' => ['/api/exports/travels', 'api_exports_travels'],
// Regression: a dateCode requirement of `.+` instead of the default `[^/]+` widens
// the segment across slashes, and this four-segment path is then swallowed by byCode().
'availability is not shadowed by the code lookup' => [
'/api/travels/12794/225444/2026-12-30/availability',
'api_travel_hotel_availability',
],
'numeric ids still reach byId' => ['/api/travels/12794/225444', 'api_travel_single_id'],
'a date code alone reaches byCode' => ['/api/travels/SBW261226', 'api_travel_single_code'],
'a date and hotel code reach byCode' => ['/api/travels/SBW261226/H1', 'api_travel_single_code'],
'the mapping index is untouched' => ['/api/travels', 'api_travel_mapping'],
];
}
#[DataProvider('pathProvider')]
public function testPathResolvesToTheIntendedRoute(string $path, string $expected): void
{
$matcher = new UrlMatcher($this->collection(), new RequestContext('', 'GET'));
self::assertSame($expected, $matcher->match($path)['_route']);
}
public function testDateCodeNeverSpansSlashes(): void
{
$route = $this->collection()->get('api_travel_single_code');
self::assertNotNull($route);
self::assertStringNotContainsString(
'.+',
(string) $route->getRequirement('dateCode'),
'dateCode must keep the single-segment class, or it shadows the routes below it',
);
}
/**
* The export must stay out of `/api/travels/`, where it would be one date code away from
* ambiguity and would need a negative lookahead on byCode() to be reachable at all.
*/
public function testNothingButTravelLookupsLivesUnderTheTravelsNamespace(): void
{
foreach ($this->collection()->all() as $name => $route) {
self::assertStringNotContainsString(
'/api/travels/export',
$route->getPath(),
$name.' must not sit in the date code namespace',
);
}
}
/**
* Reflects the controller's own #[Route] attributes, in declaration order.
*/
private function collection(): RouteCollection
{
$collection = new RouteCollection();
foreach ([TravelController::class, ExportController::class] as $controller) {
$this->addRoutes($collection, $controller);
}
return $collection;
}
/**
* @param class-string $controller
*/
private function addRoutes(RouteCollection $collection, string $controller): void
{
$class = new \ReflectionClass($controller);
$prefix = '';
foreach ($class->getAttributes(RouteAttribute::class) as $attribute) {
$prefix = (string) $attribute->newInstance()->path;
}
foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
foreach ($method->getAttributes(RouteAttribute::class) as $attribute) {
$route = $attribute->newInstance();
$collection->add((string) $route->name, new Route(
$prefix.$route->path,
$route->defaults,
$route->requirements,
[],
'',
[],
$route->methods,
));
}
}
}
}
+41
View File
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<reisen>
<reise code="SBW">
<!-- Two hotels on one date: the cross product must produce one row per pair. -->
<termin id="1" idbuspro="900" idprodukt="1" termin="26.12.2026" bis="30.12.2026" code="SBW261226" reiseart="F">
<text> Semesterende - Portes du Soleil </text>
<hotel idbuspro="1" code="H1"/>
<hotel idbuspro="2" code="H2"/>
<zustiege>
<zustieg id="1" idbuspro="10" zeit="26.12.2026 23:59:00"/>
<!-- Time only, and earlier than the 23:59 above: rolls onto the next calendar day. -->
<zustieg id="2" idbuspro="11" zeit="02:15"/>
<!-- No zeit at all: the entry survives with both time fields null. -->
<zustieg id="3" idbuspro="12"/>
<!-- Referenced but absent from zustiege.xml. -->
<zustieg id="4" idbuspro="99" zeit="26.12.2026 21:00:00"/>
</zustiege>
</termin>
<!-- Summer date, to pin the +02:00 offset. -->
<termin id="2" idbuspro="901" termin="15.07.2027" bis="22.07.2027" code="SBW270715">
<text>Sommer</text>
<hotel idbuspro="1" code="H1"/>
<zustiege>
<zustieg id="1" idbuspro="10" zeit="15.07.2027 08:00:00"/>
<!-- Time only and after the full datetime above: stays on the departure date. -->
<zustieg id="2" idbuspro="11" zeit="09:30"/>
</zustiege>
</termin>
<!-- Hotel absent from hotel.xml: the row is dropped and counted. -->
<termin id="3" idbuspro="902" termin="01.02.2027" bis="08.02.2027" code="SBW270201">
<text>Ohne Hotel</text>
<hotel idbuspro="404" code="GHOST"/>
</termin>
<!-- Unparseable date: both its hotel rows are dropped and counted. -->
<termin id="4" idbuspro="903" termin="kaputt" bis="08.02.2027" code="SBW270301">
<text>Kaputtes Datum</text>
<hotel idbuspro="1" code="H1"/>
<hotel idbuspro="2" code="H2"/>
</termin>
</reise>
</reisen>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<reisen>
<reise code="SBW">
<termin id="1" idbuspro="900" termin="26.12.2026" bis="30.12.2026" code="SBW261226">
<text>Zweiter Treffer</text>
<hotel idbuspro="1" code="H1"/>
</termin>
</reise>
</reisen>
+235
View File
@@ -0,0 +1,235 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\BusProNet\Model\Hotel;
use App\BusProNet\Model\Pickup;
use App\BusProNet\XmlLoader\HotelLoader;
use App\BusProNet\XmlLoader\PickupLoader;
use App\BusProNet\XmlParser\AgeConstraintParserRegistry;
use App\BusProNet\XmlParser\TravelParser;
use App\Model\TravelExport;
use App\Service\TravelExportBuilder;
use League\Flysystem\DirectoryListing;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemOperator;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
class TravelExportBuilderTest extends TestCase
{
public function testEmitsOneRowPerTravelDateAndHotelPair(): void
{
$rows = $this->build()->rows;
$keys = array_map(
static fn (array $row): string => $row['busProId'].'-'.$row['hotel']['busProId'],
$rows,
);
self::assertSame(['900-1', '900-2', '901-1'], $keys);
self::assertSame($keys, array_unique($keys), 'the pair the consumer upserts on must be unique export-wide');
}
public function testCarriesTravelAndHotelMasterData(): void
{
$row = $this->rowFor('900-1');
self::assertSame(900, $row['busProId']);
self::assertIsInt($row['busProId']);
self::assertSame('SBW261226', $row['code']);
self::assertSame('Semesterende - Portes du Soleil', $row['product'], 'the product label is trimmed');
self::assertSame('2026-12-26', $row['dateFrom']);
self::assertSame('2026-12-30', $row['dateTo']);
self::assertSame([
'busProId' => 1,
'code' => 'H1',
'name' => 'Hotel Eins',
'costUnit' => '84 85',
'country' => 'CH',
'countryCode' => 'ch',
], $row['hotel']);
}
public function testResolvesBothZeitShapesAndRollsAnOvernightPickupOntoTheNextDay(): void
{
$pickups = array_column($this->rowFor('900-1')['pickups'], null, 'busProId');
self::assertSame('23:59', $pickups[10]['time']);
self::assertSame('2026-12-26T23:59:00+01:00', $pickups[10]['datetime']);
// Time only, so it defaults to the departure date -- which would put it before the
// 23:59 above. The coach cannot board backwards, so it rolls onto the next day.
self::assertSame('02:15', $pickups[11]['time']);
self::assertSame('2026-12-27T02:15:00+01:00', $pickups[11]['datetime']);
}
public function testEmitsTheSummerOffset(): void
{
$pickups = $this->rowFor('901-1')['pickups'];
self::assertSame('2027-07-15T08:00:00+02:00', $pickups[0]['datetime']);
}
public function testATimeOnlyPickupThatAlreadyFollowsTheLastDatedOneKeepsTheDepartureDate(): void
{
$pickups = array_column($this->rowFor('901-1')['pickups'], null, 'busProId');
self::assertSame('2027-07-15T09:30:00+02:00', $pickups[11]['datetime'], 'no roll when the order already holds');
}
public function testKeepsAPickupWithoutAZeitAndNullsBothTimeFields(): void
{
$pickups = array_column($this->rowFor('900-1')['pickups'], null, 'busProId');
self::assertArrayHasKey(12, $pickups);
self::assertNull($pickups[12]['time']);
self::assertNull($pickups[12]['datetime']);
self::assertSame('Z12', $pickups[12]['code'], 'master data still applies to an entry with no time');
}
public function testKeepsAPickupMissingFromMasterDataAndCountsIt(): void
{
$export = $this->build();
$pickups = array_column($export->rows[0]['pickups'], null, 'busProId');
// Dropping it would hide a real departure point from the disposition UI.
self::assertArrayHasKey(99, $pickups);
self::assertNull($pickups[99]['code']);
self::assertNull($pickups[99]['city']);
self::assertNull($pickups[99]['street']);
self::assertSame('21:00', $pickups[99]['time'], 'the time is from the travel XML, not master data');
self::assertSame('2026-12-26T21:00:00+01:00', $pickups[99]['datetime']);
// Counted once, not once per row that references it.
self::assertSame(1, $export->pickupsWithoutMasterData);
}
public function testPickupsKeepSourceOrder(): void
{
$order = array_column($this->rowFor('900-1')['pickups'], 'busProId');
self::assertSame([10, 11, 12, 99], $order, 'source order, never sorted by time');
}
public function testPickupsAreAnEmptyArrayRatherThanNullWhenThereAreNone(): void
{
$rows = $this->build('<?xml version="1.0"?><reisen><reise><termin idbuspro="1" termin="01.01.2027" bis="02.01.2027"><hotel idbuspro="1"/></termin></reise></reisen>')->rows;
self::assertSame([], $rows[0]['pickups']);
}
public function testDropsAndCountsRowsWhoseHotelIsMissingFromMasterData(): void
{
$export = $this->build();
self::assertSame([], array_filter($export->rows, static fn (array $r): bool => 902 === $r['busProId']));
// One hotel on travel 902, two on the travel with the unparseable date.
self::assertSame(3, $export->skipped);
}
public function testDropsEveryRowOfATravelWhoseDateCannotBeParsed(): void
{
$export = $this->build();
self::assertSame([], array_filter($export->rows, static fn (array $r): bool => 903 === $r['busProId']));
}
public function testCollapsesADuplicatePairLastWins(): void
{
$export = $this->build(null, ['Ziel_1.xml', 'Ziel_2.xml']);
$matching = array_values(array_filter(
$export->rows,
static fn (array $r): bool => 900 === $r['busProId'] && 1 === $r['hotel']['busProId'],
));
self::assertCount(1, $matching);
self::assertSame('Zweiter Treffer', $matching[0]['product']);
}
/**
* @return array<string, mixed>
*/
private function rowFor(string $key): array
{
foreach ($this->build()->rows as $row) {
if ($row['busProId'].'-'.$row['hotel']['busProId'] === $key) {
return $row;
}
}
self::fail('No row for '.$key);
}
/**
* @param list<string> $files
*/
private function build(?string $xml = null, array $files = ['Ziel_1.xml']): TravelExport
{
$contents = [
'Ziel_1.xml' => $xml ?? (string) file_get_contents(__DIR__.'/../Resources/travel_export_data.xml'),
'Ziel_2.xml' => (string) file_get_contents(__DIR__.'/../Resources/travel_export_data_duplicate.xml'),
];
$filesystem = $this->createStub(FilesystemOperator::class);
$filesystem->method('listContents')->willReturn(new DirectoryListing(array_map(
static fn (string $path): FileAttributes => new FileAttributes($path),
$files,
)));
$filesystem->method('read')->willReturnCallback(
static fn (string $path): string => $contents[$path] ?? ''
);
$hotelLoader = $this->createStub(HotelLoader::class);
$hotelLoader->method('loadAll')->willReturn([
1 => $this->hotel(1, 'H1', 'Hotel Eins', '84 85', 'CH', 'ch'),
2 => $this->hotel(2, 'H2', 'Hotel Zwei', null, 'D', 'de'),
]);
$pickupLoader = $this->createStub(PickupLoader::class);
$pickupLoader->method('loadAll')->willReturn([
10 => $this->pickup(10),
11 => $this->pickup(11),
12 => $this->pickup(12),
]);
return (new TravelExportBuilder(
$hotelLoader,
$pickupLoader,
new TravelParser(new AgeConstraintParserRegistry([]), false),
$filesystem,
new TagAwareAdapter(new ArrayAdapter()),
new NullLogger(),
))->build();
}
private function hotel(int $id, string $code, string $name, ?string $costUnit, string $country, string $countryCode): Hotel
{
$hotel = new Hotel();
$hotel->id = $id;
$hotel->code = $code;
$hotel->name = $name;
$hotel->costUnit = $costUnit;
$hotel->country = $country;
$hotel->countryCode = $countryCode;
return $hotel;
}
private function pickup(int $id): Pickup
{
$pickup = new Pickup();
$pickup->id = $id;
$pickup->code = 'Z'.$id;
$pickup->city = 'Stadt '.$id;
$pickup->street = 'Strasse '.$id;
return $pickup;
}
}