diff --git a/composer.json b/composer.json index 2e19404..f53babb 100644 --- a/composer.json +++ b/composer.json @@ -39,7 +39,7 @@ "nowo-tech/form-kit-bundle": "^2.10", "nowo-tech/transaction-contract": "^1.0", "nowo-tech/transaction-doctrine": "^1.8.1", - "nowo-tech/ui-kit-bundle": "^2.2", + "nowo-tech/ui-kit-bundle": "^2.21", "psr/clock": "^1.0", "psr/event-dispatcher": "^1.0", "psr/log": "^1 || ^2 || ^3", diff --git a/composer.lock b/composer.lock index ef7efaa..1c9636d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "57a027a4b8c87ab7fb9b77a66df39354", + "content-hash": "f18a81467a4d6efbcd3a416a4dda1528", "packages": [ { "name": "doctrine/collections", @@ -7333,7 +7333,8 @@ "type": "github" } ], - "time": "2026-11-15T19:58:26+00:00" + "time": "2026-11-15T19:58:26+00:00", + "published-time": "2026-11-15T19:58:39+00:00" }, { "name": "phpstan/phpstan-phpunit", diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index bc3071f..e96dd52 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -58,6 +58,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `web_ui.header_actions` (`toolbar` default, `split`): `split` renders the list header through the UiKit split header (Export and Purge in the square more menu, Purge last, confirmation kept). The actions stay `page.header.actions`, so a host with the UiKit compact header (`compact_actions: bar`) takes them into its top bar. Default output unchanged. +- `web_ui.filter_actions` (`scaffold` default, `filter_bar`): `filter_bar` renders the filters as a UiKit `.nowo-ui-filter-bar` with the `_filter_actions` partial (Filter + Clear, Clear always shown). +- New translation keys `filter.any_method`, `filter.any_body_type`, `filter.any_channel`, `filter.client_ip_placeholder` (all 7 locales). + +### Changed + +- The method, body type and channel selects now offer a named empty option (Any method, ...) and the client IP field has a placeholder, so no filter field is an unlabelled box. Requires `nowo-tech/ui-kit-bundle` ^2.21. +- The method, body type and channel placeholders are `TranslatableMessage`s in the bundle domain: the choice placeholder is no longer left untranslated by `choice_translation_domain: false`. + ## [1.24.0] - 2026-11-21 ### Added diff --git a/docs/USAGE.md b/docs/USAGE.md index c0874cd..0f01bfe 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -146,6 +146,21 @@ nowo_http_log: access_checker: App\Security\MyHttpLogAccessChecker ``` +### Header actions and filter actions (1.25, opt-in) + +```yaml +nowo_http_log: + web_ui: + header_actions: split # toolbar (default) | split + filter_actions: filter_bar # scaffold (default) | filter_bar +``` + +- `split`: UiKit split header (needs UiKit >= 2.21): Export and *Purge old entries* go in the square more menu, Purge last, with its confirmation dialog. +- The header actions are always `page.header.actions` (`View\Action`, Purge last, with its confirmation). With the UiKit compact header and `compact_actions: bar` the host takes them into its top bar and the page header leaves them out; the bundle renders no menu of its own. +- `filter_bar`: the filters render as a UiKit filter bar and Filter + Clear come from `_filter_actions` (Clear is always shown). A host `web_ui.templates.filter` partial is not used in this mode. + +The method, body type and channel selects show a named empty option (*Any method*, *Any body type*, *Any channel*) and every field keeps its label. + ## Twig template overrides Since **1.8** the admin pages follow the UiKit 2.1 page contract (REQ-UI-003): `admin/index.html.twig` extends the diff --git a/src/Controller/HttpLogAdminController.php b/src/Controller/HttpLogAdminController.php index a2afba5..d12b1dc 100644 --- a/src/Controller/HttpLogAdminController.php +++ b/src/Controller/HttpLogAdminController.php @@ -139,25 +139,33 @@ public function index(Request $request): Response } } + $pages = $this->pages(); + $purgeForm = $this->createForm(HttpLogPurgeType::class, null, [ + 'action' => $this->generateUrl('nowo_http_log_admin_purge'), + ])->createView(); + $canExport = $this->canExport(); + $canPurge = $this->canPurge(); + $downloads = $canExport ? $this->readyExports() : []; + return $this->render($this->template('index'), [ - 'page' => $this->pages()->listPage( + 'page' => $pages->listPage( $result['items'], $result['total'], $page, $this->pageSize, $filterForm->createView(), $exportForms, - $this->createForm(HttpLogPurgeType::class, null, [ - 'action' => $this->generateUrl('nowo_http_log_admin_purge'), - ])->createView(), + $purgeForm, $criteria !== [], - $this->canExport(), - $this->canPurge(), - $this->canExport() ? $this->readyExports() : [], + $canExport, + $canPurge, + $downloads, $result['total_capped'], $result['cursor'], ), 'criteria' => $criteria, + // 1.25: web_ui.filter_actions + 'filter_actions' => $pages->filterActionsMode(), ]); } diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index c45fdd2..4ae6397 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -9,6 +9,7 @@ use Nowo\HttpLogBundle\Enum\ExportFormat; use Nowo\HttpLogBundle\Inbound\HttpRequestContextFactory; use Nowo\HttpLogBundle\View\AdminChrome; +use Nowo\HttpLogBundle\View\AdminPages; use Nowo\TransactionDoctrine\Symfony\Conflict\ConflictResponsePolicy; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\NodeDefinition; @@ -358,6 +359,16 @@ public function getConfigTreeBuilder(): TreeBuilder ->setDeprecated(self::PACKAGE, '1.8', 'The "%path%.%node%" option is deprecated and has no effect: the admin layout loads nowo-ui.css.') ->defaultTrue() ->end() + ->enumNode('header_actions') + ->info('1.25: how the list page presents its header actions (export, download, purge; always `page.header.actions`, Purge last with its confirmation). toolbar (default, the 1.24 output): one button per action in the page header. split: UiKit split header (needs nowo-tech/ui-kit-bundle >= 2.21) - the actions go in the square "more" menu. With the UiKit compact header and compact_actions `bar` the host takes `page.header.actions` into its top bar and the page header leaves them out; the bundle renders no menu of its own.') + ->values([AdminPages::HEADER_ACTIONS_TOOLBAR, AdminPages::HEADER_ACTIONS_SPLIT]) + ->defaultValue(AdminPages::HEADER_ACTIONS_TOOLBAR) + ->end() + ->enumNode('filter_actions') + ->info('1.25: scaffold (default, the 1.24 output): the filter row of the UiKit list scaffold. filter_bar: the filters render as a UiKit `.nowo-ui-filter-bar` whose Filter + Clear buttons come from the UiKit `_filter_actions` partial (Clear is always shown). A host that sets web_ui.templates.filter keeps the scaffold row.') + ->values([AdminPages::FILTER_ACTIONS_SCAFFOLD, AdminPages::FILTER_ACTIONS_FILTER_BAR]) + ->defaultValue(AdminPages::FILTER_ACTIONS_SCAFFOLD) + ->end() ->booleanNode('header_actions_in_layout') ->info('Deprecated, no effect: header actions are part of the page header the layout renders (nowo_ui_page_header).') ->setDeprecated(self::PACKAGE, '1.8', 'The "%path%.%node%" option is deprecated and has no effect: header actions render in the page header (nowo_ui_page_header block).') diff --git a/src/Form/HttpLogFilterType.php b/src/Form/HttpLogFilterType.php index f31df6b..f0a3db3 100644 --- a/src/Form/HttpLogFilterType.php +++ b/src/Form/HttpLogFilterType.php @@ -11,6 +11,7 @@ use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\Translation\TranslatableMessage; /** * @extends AbstractType> @@ -29,7 +30,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $this->addChoiceField('method', [ 'required' => false, 'label' => 'filter.method', - 'placeholder' => 'filter.any', + 'placeholder' => new TranslatableMessage('filter.any_method', [], 'NowoHttpLogBundle'), // HTTP methods are literals: not looked up in the bundle domain (REQ: no profiler missing messages). 'choice_translation_domain' => false, 'choices' => [ @@ -43,13 +44,13 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ], ]); $this->addIntegerField('statusCode', ['required' => false, 'label' => 'filter.status_code', 'attr' => ['min' => 100, 'max' => 599, 'placeholder' => 'filter.status_code_placeholder']]); - $this->addTextField('clientIp', ['required' => false, 'label' => 'filter.client_ip']); + $this->addTextField('clientIp', ['required' => false, 'label' => 'filter.client_ip', 'attr' => ['placeholder' => 'filter.client_ip_placeholder']]); $this->addTextField('path', ['required' => false, 'label' => 'filter.path', 'attr' => ['placeholder' => 'filter.path_placeholder']]); $this->addTextField('routeName', ['required' => false, 'label' => 'filter.route_name', 'attr' => ['placeholder' => 'filter.route_name_placeholder']]); $this->addChoiceField('bodyContentType', [ 'required' => false, 'label' => 'filter.body_content_type', - 'placeholder' => 'filter.any', + 'placeholder' => new TranslatableMessage('filter.any_body_type', [], 'NowoHttpLogBundle'), // Body types are enum values (json, xml…), not translation keys. 'choice_translation_domain' => false, 'choices' => array_combine( @@ -87,7 +88,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $this->addChoiceField('channel', [ 'required' => false, 'label' => 'filter.channel', - 'placeholder' => 'filter.any', + 'placeholder' => new TranslatableMessage('filter.any_channel', [], 'NowoHttpLogBundle'), // Channel names are literals (web, outbound, mailer), not translation keys. 'choice_translation_domain' => false, 'choices' => array_combine($channels, $channels), diff --git a/src/Resources/translations/NowoHttpLogBundle.de.yaml b/src/Resources/translations/NowoHttpLogBundle.de.yaml index 09f6927..4e921bf 100644 --- a/src/Resources/translations/NowoHttpLogBundle.de.yaml +++ b/src/Resources/translations/NowoHttpLogBundle.de.yaml @@ -66,3 +66,7 @@ filter.provider: 'Anbieter' filter.tenant_key: 'Mandant' filter.project_key: 'Projekt' filter.credential_kind: 'Art der Zugangsdaten' +filter.any_method: 'Jede Methode' +filter.any_body_type: 'Jeder Body-Typ' +filter.any_channel: 'Jeder Kanal' +filter.client_ip_placeholder: '203.0.113.7' diff --git a/src/Resources/translations/NowoHttpLogBundle.en.yaml b/src/Resources/translations/NowoHttpLogBundle.en.yaml index 023cf95..e42efc4 100644 --- a/src/Resources/translations/NowoHttpLogBundle.en.yaml +++ b/src/Resources/translations/NowoHttpLogBundle.en.yaml @@ -66,3 +66,7 @@ filter.provider: 'Provider' filter.tenant_key: 'Tenant' filter.project_key: 'Project' filter.credential_kind: 'Credential kind' +filter.any_method: 'Any method' +filter.any_body_type: 'Any body type' +filter.any_channel: 'Any channel' +filter.client_ip_placeholder: '203.0.113.7' diff --git a/src/Resources/translations/NowoHttpLogBundle.es.yaml b/src/Resources/translations/NowoHttpLogBundle.es.yaml index 711219c..2e6e5ee 100644 --- a/src/Resources/translations/NowoHttpLogBundle.es.yaml +++ b/src/Resources/translations/NowoHttpLogBundle.es.yaml @@ -66,3 +66,7 @@ filter.provider: 'Proveedor' filter.tenant_key: 'Organización' filter.project_key: 'Proyecto' filter.credential_kind: 'Tipo de credencial' +filter.any_method: 'Cualquier método' +filter.any_body_type: 'Cualquier tipo de cuerpo' +filter.any_channel: 'Cualquier canal' +filter.client_ip_placeholder: '203.0.113.7' diff --git a/src/Resources/translations/NowoHttpLogBundle.fr.yaml b/src/Resources/translations/NowoHttpLogBundle.fr.yaml index aa2903c..18460ed 100644 --- a/src/Resources/translations/NowoHttpLogBundle.fr.yaml +++ b/src/Resources/translations/NowoHttpLogBundle.fr.yaml @@ -66,3 +66,7 @@ filter.provider: 'Fournisseur' filter.tenant_key: 'Organisation' filter.project_key: 'Projet' filter.credential_kind: 'Type d''identifiant' +filter.any_method: 'Toutes les méthodes' +filter.any_body_type: 'Tous les types de corps' +filter.any_channel: 'Tous les canaux' +filter.client_ip_placeholder: '203.0.113.7' diff --git a/src/Resources/translations/NowoHttpLogBundle.it.yaml b/src/Resources/translations/NowoHttpLogBundle.it.yaml index 139b5c8..652f153 100644 --- a/src/Resources/translations/NowoHttpLogBundle.it.yaml +++ b/src/Resources/translations/NowoHttpLogBundle.it.yaml @@ -66,3 +66,7 @@ filter.provider: 'Fornitore' filter.tenant_key: 'Organizzazione' filter.project_key: 'Progetto' filter.credential_kind: 'Tipo di credenziale' +filter.any_method: 'Qualsiasi metodo' +filter.any_body_type: 'Qualsiasi tipo di corpo' +filter.any_channel: 'Qualsiasi canale' +filter.client_ip_placeholder: '203.0.113.7' diff --git a/src/Resources/translations/NowoHttpLogBundle.nl.yaml b/src/Resources/translations/NowoHttpLogBundle.nl.yaml index b3c6574..ac94ddf 100644 --- a/src/Resources/translations/NowoHttpLogBundle.nl.yaml +++ b/src/Resources/translations/NowoHttpLogBundle.nl.yaml @@ -66,3 +66,7 @@ filter.provider: 'Aanbieder' filter.tenant_key: 'Organisatie' filter.project_key: 'Project' filter.credential_kind: 'Soort referentie' +filter.any_method: 'Elke methode' +filter.any_body_type: 'Elk body-type' +filter.any_channel: 'Elk kanaal' +filter.client_ip_placeholder: '203.0.113.7' diff --git a/src/Resources/translations/NowoHttpLogBundle.pt.yaml b/src/Resources/translations/NowoHttpLogBundle.pt.yaml index a1e86e1..9648504 100644 --- a/src/Resources/translations/NowoHttpLogBundle.pt.yaml +++ b/src/Resources/translations/NowoHttpLogBundle.pt.yaml @@ -66,3 +66,7 @@ filter.provider: 'Fornecedor' filter.tenant_key: 'Organização' filter.project_key: 'Projeto' filter.credential_kind: 'Tipo de credencial' +filter.any_method: 'Qualquer método' +filter.any_body_type: 'Qualquer tipo de corpo' +filter.any_channel: 'Qualquer canal' +filter.client_ip_placeholder: '203.0.113.7' diff --git a/src/Resources/views/admin/_filter_bar.html.twig b/src/Resources/views/admin/_filter_bar.html.twig new file mode 100644 index 0000000..d1eba30 --- /dev/null +++ b/src/Resources/views/admin/_filter_bar.html.twig @@ -0,0 +1,24 @@ +{# + Filter bar of the list page (web_ui.filter_actions: filter_bar, 1.25): a UiKit `.nowo-ui-filter-bar` form — every + filter field as a labelled row — and the UiKit `_filter_actions` partial (Filter + Clear, Clear always shown). + + Variables: page (View\ListPage; page.filters is the filter FormView), region, bundle. + Fields keep the width tokens of page.filterFields; the input classes come from the `input` theme slot. +#} +{% set _b = bundle|default(page.bundle) %} +{% set _filters = page.filters %} +{{ form_start(_filters, {attr: {class: 'nowo-ui-filter-bar', role: 'search', 'data-nowo-ui-filters': '', 'data-nowo-ui-region': region|default('filters')}}) }} + {% for child in _filters %} + {% if not child.rendered %} + {% set _prefixes = child.vars.block_prefixes %} + {% set _attr = child.vars.attr %} + {% if 'checkbox' not in _prefixes and 'radio' not in _prefixes and 'hidden' not in _prefixes %} + {% set _attr = _attr|merge({class: ((_attr.class ?? '') ~ ' ' ~ nowo_ui_class('input', _b))|trim}) %} + {% endif %} +
+ {{ form_row(child, {attr: _attr}) }} +
+ {% endif %} + {% endfor %} + {{ include('@NowoUiKitBundle/partials/_filter_actions.html.twig', {clear_href: path('nowo_http_log_admin_index'), submit_label: 'admin.action.filter'|trans({}, 'NowoHttpLogBundle'), framework: null}, false) }} +{{ form_end(_filters) }} diff --git a/src/Resources/views/admin/index.html.twig b/src/Resources/views/admin/index.html.twig index 2e1d962..12a8de2 100644 --- a/src/Resources/views/admin/index.html.twig +++ b/src/Resources/views/admin/index.html.twig @@ -8,6 +8,20 @@ #} {% extends '@NowoUiKit/page/list.html.twig' %} +{# + 1.25 (opt-in, the default keeps the 1.24 output): web_ui.filter_actions: filter_bar -> `filter_actions` is 'filter_bar': the + filters render as a UiKit filter bar with the `_filter_actions` partial (Filter + Clear), see admin/_filter_bar.html.twig. + The header actions (export, purge) are always `page.header.actions`: a host layout with the UiKit compact header + and compact_actions `bar` takes them into its top bar; this template renders no menu of its own. +#} +{% block nowo_ui_list_filters %} + {% if page.filters and filter_actions|default('scaffold') == 'filter_bar' %} + {{ include('@NowoHttpLogBundle/admin/_filter_bar.html.twig', {page: page, region: 'filters', bundle: page.bundle}, false) }} + {% else %} + {{ parent() }} + {% endif %} +{% endblock %} + {% block nowo_ui_list_row %} {%- set _b = page.bundle -%} {%- set _cell = nowo_ui_class('table_cell', _b) -%} diff --git a/src/View/AdminPages.php b/src/View/AdminPages.php index 2ce9587..5380740 100644 --- a/src/View/AdminPages.php +++ b/src/View/AdminPages.php @@ -61,6 +61,18 @@ { public const DOMAIN = LegacyThemeBridge::BUNDLE; + /** `web_ui.header_actions`: one toolbar button per action (the 1.24 output, default). */ + public const HEADER_ACTIONS_TOOLBAR = 'toolbar'; + + /** `web_ui.header_actions`: UiKit split header (square "more" menu, destructive Purge last). */ + public const HEADER_ACTIONS_SPLIT = 'split'; + + /** `web_ui.filter_actions`: the filter row of the UiKit list scaffold (default). */ + public const FILTER_ACTIONS_SCAFFOLD = 'scaffold'; + + /** `web_ui.filter_actions`: a UiKit filter bar with the `_filter_actions` partial. */ + public const FILTER_ACTIONS_FILTER_BAR = 'filter_bar'; + /** * @param array $webUi processed `nowo_http_log.web_ui` (layout_template, deprecated attributes) */ @@ -95,41 +107,8 @@ public function listPage( bool $totalCapped = false, ?HttpLogListCursor $cursor = null, ): ListPage { - $exportUrl = $this->urls->generate('nowo_http_log_admin_export'); - $purgeUrl = $this->urls->generate('nowo_http_log_admin_purge'); - - $actions = []; - foreach ($exportForms as $format => $form) { - // the export form posts its hidden fields: CSRF token, format and the current criteria. - $actions[] = new Action( - 'export', - $this->label('admin.action.export_' . $format), - href: $exportUrl, - method: 'POST', - form: $form, - visible: $canExport, - ); - } - foreach ($downloads as $download) { - $actions[] = new Action( - 'export', - $this->label('admin.action.download_export', [ - '%format%' => strtoupper($download['format']->value), - '%date%' => $download['createdAt']->format('Y-m-d H:i'), - ]), - href: $this->urls->generate('nowo_http_log_admin_export_download', ['name' => $download['name']]), - visible: $canExport, - ); - } - $actions[] = new Action( - 'delete', - $this->label('admin.action.purge'), - href: $purgeUrl, - method: 'POST', - confirm: new Confirm($this->label('admin.action.purge'), $this->label('admin.purge.confirm'), $this->label('admin.action.purge')), - form: $purgeForm, - visible: $canPurge, - ); + $mode = $this->headerActionsMode(); + $actions = $this->headerActions($exportForms, $purgeForm, $canExport, $canPurge, $downloads); $columns = [ new Column('id', $this->label('admin.column.id'), required: true), @@ -164,7 +143,12 @@ public function listPage( } return new ListPage( - new PageHeader($this->label('admin.index.title'), $this->label('admin.index.total', ['%count%' => $totalCapped ? $total . '+' : $total]), $actions), + new PageHeader( + $this->label('admin.index.title'), + $this->label('admin.index.total', ['%count%' => $totalCapped ? $total . '+' : $total]), + $actions, + actionsLayout: $mode === self::HEADER_ACTIONS_SPLIT ? 'split' : 'toolbar', + ), $columns, $entries, $filters, @@ -183,6 +167,70 @@ public function listPage( ); } + /** + * The header actions of the list page (`page.header.actions`): export per enabled format, downloads of finished + * background exports and purge last (UiKit confirm dialog). + * + * @param array $exportForms + * @param list $downloads + * + * @return list + */ + public function headerActions(array $exportForms, FormView $purgeForm, bool $canExport = true, bool $canPurge = true, array $downloads = []): array + { + $exportUrl = $this->urls->generate('nowo_http_log_admin_export'); + $purgeUrl = $this->urls->generate('nowo_http_log_admin_purge'); + + $actions = []; + foreach ($exportForms as $format => $form) { + // the export form posts its hidden fields: CSRF token, format and the current criteria. + $actions[] = new Action( + 'export', + $this->label('admin.action.export_' . $format), + href: $exportUrl, + method: 'POST', + form: $form, + visible: $canExport, + ); + } + foreach ($downloads as $download) { + $actions[] = new Action( + 'export', + $this->label('admin.action.download_export', [ + '%format%' => strtoupper($download['format']->value), + '%date%' => $download['createdAt']->format('Y-m-d H:i'), + ]), + href: $this->urls->generate('nowo_http_log_admin_export_download', ['name' => $download['name']]), + visible: $canExport, + ); + } + $actions[] = new Action( + 'delete', + $this->label('admin.action.purge'), + href: $purgeUrl, + method: 'POST', + confirm: new Confirm($this->label('admin.action.purge'), $this->label('admin.purge.confirm'), $this->label('admin.action.purge')), + form: $purgeForm, + visible: $canPurge, + ); + + return $actions; + } + + /** `web_ui.header_actions` (toolbar when unset or unknown). */ + public function headerActionsMode(): string + { + $mode = $this->webUi['header_actions'] ?? self::HEADER_ACTIONS_TOOLBAR; + + return $mode === self::HEADER_ACTIONS_SPLIT ? $mode : self::HEADER_ACTIONS_TOOLBAR; + } + + /** `web_ui.filter_actions` (scaffold when unset or unknown). */ + public function filterActionsMode(): string + { + return ($this->webUi['filter_actions'] ?? self::FILTER_ACTIONS_SCAFFOLD) === self::FILTER_ACTIONS_FILTER_BAR ? self::FILTER_ACTIONS_FILTER_BAR : self::FILTER_ACTIONS_SCAFFOLD; + } + public function showPage(HttpLogEntry $entry, FormView $deleteForm, bool $canPurge = true): ShowPage { $indexUrl = $this->urls->generate('nowo_http_log_admin_index'); diff --git a/tests/Integration/AdminPagesUx1171Test.php b/tests/Integration/AdminPagesUx1171Test.php new file mode 100644 index 0000000..c7c88ce --- /dev/null +++ b/tests/Integration/AdminPagesUx1171Test.php @@ -0,0 +1,118 @@ +render(['page' => AdminPageFixtures::listPage(AdminPageFixtures::entries(), 3)]); + + self::assertStringContainsString('', $html); + self::assertStringContainsString('', $html); + self::assertStringNotContainsString('filter.any', $html); + foreach (['q' => 'Search', 'method' => 'Method', 'statusCode' => 'Status code', 'clientIp' => 'Client IP', 'path' => 'Path', 'routeName' => 'Route name', 'bodyContentType' => 'Body type', 'createdFrom' => 'Created from', 'createdTo' => 'Created to'] as $field => $label) { + self::assertStringContainsString('', $html); + } + self::assertStringContainsString('placeholder="203.0.113.7"', $html); + } + + #[Test] + public function thePlaceholdersAreTranslatedInTheRenderedFormInEnglishAndSpanish(): void + { + $expected = [ + 'en' => ['Any method', 'Any body type'], + 'es' => ['Cualquier método', 'Cualquier tipo de cuerpo'], + ]; + foreach ($expected as $locale => [$method, $body]) { + $html = (new AdminTwigHarness($locale))->createEnvironment()->render('@NowoHttpLogBundle/admin/index.html.twig', [ + 'page' => AdminPageFixtures::listPage(AdminPageFixtures::entries(), 3), 'criteria' => [], + ]); + + self::assertStringContainsString('', $html, $locale); + self::assertStringContainsString('', $html, $locale); + self::assertStringNotContainsString('filter.any', $html, $locale); + } + } + + #[Test] + public function defaultsKeepTheScaffoldFilterRowAndTheToolbarHeader(): void + { + $html = $this->render(['page' => AdminPageFixtures::listPage(AdminPageFixtures::entries(), 3)]); + + self::assertStringContainsString('nowo-ui-filters__submit', $html); + self::assertStringNotContainsString('nowo-ui-filter-bar', $html); + self::assertStringNotContainsString('data-nowo-ui-filter-actions', $html); + self::assertStringNotContainsString('data-nowo-ui-page-actions', $html); + self::assertStringNotContainsString('nowo-http-log-page-actions', $html); + // the 1.24 toolbar: Purge is a header button next to the exports + self::assertStringNotContainsString('data-nowo-ui-header-more', $html); + } + + #[Test] + public function filterBarModeRendersTheUiKitFilterActionsPartialWithAlwaysTheClearLink(): void + { + $html = $this->render(['page' => AdminPageFixtures::listPage(AdminPageFixtures::entries(), 3), 'filter_actions' => AdminPages::FILTER_ACTIONS_FILTER_BAR]); + + self::assertStringContainsString('class="nowo-ui-filter-bar"', $html); + self::assertStringContainsString('data-nowo-ui-filter-actions', $html); + self::assertStringContainsString('nowo-ui-filter-bar__submit', $html); + self::assertStringContainsString('nowo-ui-filter-bar__clear', $html); + self::assertStringContainsString('nowo-ui-filter-bar__submit">Filter', $html); + self::assertStringContainsString('href="/admin/http-log">Clear', $html); + self::assertStringNotContainsString('nowo-ui-filters__submit', $html); + self::assertStringContainsString('', $html); + self::assertStringContainsString('', $html); + self::assertStringContainsString('nowo-ui-filter-bar__field--search', $html); + // a role="search" form closes properly: exactly one filter form opened by the bar + self::assertSame(1, substr_count($html, 'class="nowo-ui-filter-bar"')); + } + + #[Test] + public function splitModeMovesExportAndPurgeIntoTheMoreMenuKeepingTheConfirmation(): void + { + $page = AdminPageFixtures::listPage(AdminPageFixtures::entries(), 3, false, ['header_actions' => AdminPages::HEADER_ACTIONS_SPLIT]); + $html = $this->render(['page' => $page]); + + self::assertSame('split', $page->header->actionsLayout); + self::assertStringContainsString('data-nowo-ui-header-more', $html); + self::assertStringContainsString('nowo-ui-menu__item--danger nowo-ui-action--delete', $html); + self::assertStringContainsString('Purge HTTP log entries matching the retention policy?', $html); + self::assertStringContainsString('headerActionsMode()); + self::assertSame('toolbar', AdminPageFixtures::pages(['header_actions' => 'bogus'])->headerActionsMode()); + self::assertSame('split', AdminPageFixtures::pages(['header_actions' => 'split'])->headerActionsMode()); + self::assertSame('scaffold', AdminPageFixtures::pages()->filterActionsMode()); + self::assertSame('scaffold', AdminPageFixtures::pages(['filter_actions' => 'bogus'])->filterActionsMode()); + self::assertSame('filter_bar', AdminPageFixtures::pages(['filter_actions' => 'filter_bar'])->filterActionsMode()); + } + + /** @param array $context */ + private function render(array $context): string + { + return (new AdminTwigHarness())->createEnvironment()->render('@NowoHttpLogBundle/admin/index.html.twig', $context + ['criteria' => []]); + } +} diff --git a/tests/Integration/Usage/ApiChannelKernelTest.php b/tests/Integration/Usage/ApiChannelKernelTest.php index 58db190..ec29f27 100644 --- a/tests/Integration/Usage/ApiChannelKernelTest.php +++ b/tests/Integration/Usage/ApiChannelKernelTest.php @@ -16,6 +16,7 @@ use Nowo\HttpLogBundle\Tests\Kernel\UsageKernel; use Nowo\HttpLogBundle\Tests\Kernel\UsageMockResponses; use Nowo\HttpLogBundle\Tests\Support\CollectingLogger; +use Nowo\HttpLogBundle\Tests\Support\NativeFileStreams; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -28,6 +29,7 @@ use function array_map; use function base64_encode; use function file_exists; +use function gc_collect_cycles; use function implode; use function intdiv; use function json_encode; @@ -219,17 +221,23 @@ public function outboundCallsServingAnApiRequestInheritItsTenant(): void public function noTenantOrCredentialLeaksAcrossAThousandRequestsInOneKernel(): void { [$kernel, $container] = $this->boot(['channels' => ['api' => ['path_prefixes' => ['/api']]], 'rollup' => ['enabled' => false]] + self::CONFIG); + $native = false; try { $context = $container->get(HttpLogContext::class); self::assertInstanceOf(HttpLogContext::class, $context); $memory = 0; for ($i = 0; $i < 1000; ++$i) { + if ($i === 2) { + // one warm-up request of each kind ran through BypassFinals: measure the bundle, not the harness + $native = NativeFileStreams::begin(); + } $headers = $i % 2 === 0 ? ['HTTP_X_TEST_ORG' => 'org-' . $i, 'HTTP_AUTHORIZATION' => 'Bearer ' . str_repeat('x', 10 + $i % 7)] : []; $this->request($kernel, '/api/sync', $headers); self::assertSame(0, $context->depth()); $container->get('services_resetter')->reset(); if ($i === 100) { + gc_collect_cycles(); $memory = memory_get_usage(); } } @@ -243,8 +251,10 @@ public function noTenantOrCredentialLeaksAcrossAThousandRequestsInOneKernel(): v self::assertNull($row['credential_id']); } } + gc_collect_cycles(); self::assertLessThan(4 * 1024 * 1024, memory_get_usage() - $memory, 'memory flat'); } finally { + NativeFileStreams::end($native); $kernel->shutdown(); } } diff --git a/tests/Integration/Usage/DddHostKernelTest.php b/tests/Integration/Usage/DddHostKernelTest.php index 4280aba..a055147 100644 --- a/tests/Integration/Usage/DddHostKernelTest.php +++ b/tests/Integration/Usage/DddHostKernelTest.php @@ -14,6 +14,7 @@ use Nowo\HttpLogBundle\Tests\Kernel\DddHostEntryListener; use Nowo\HttpLogBundle\Tests\Kernel\UsageKernel; use Nowo\HttpLogBundle\Tests\Kernel\UsageMockResponses; +use Nowo\HttpLogBundle\Tests\Support\NativeFileStreams; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; @@ -88,6 +89,7 @@ public function aHostWithOnlyTheFrameworkFreePortsRecordsAndIsNotified(): void public function alternatingTenantsNeverLeakWithTheResetterOff(): void { [$kernel, $container] = $this->boot(); + $native = false; try { $listener = $container->get(DddHostEntryListener::class); @@ -97,6 +99,10 @@ public function alternatingTenantsNeverLeakWithTheResetterOff(): void $memory = 0; for ($i = 0; $i < self::ITERATIONS; ++$i) { + if ($i === 4) { + // one warm-up request of each kind ran through BypassFinals: measure the bundle, not the harness + $native = NativeFileStreams::begin(); + } // even: org-a with a credential; odd: org-b, or no tenant at all every fourth request $server = match ($i % 4) { 0, 2 => ['HTTP_X_TEST_ORG' => 'org-a', 'HTTP_AUTHORIZATION' => 'Bearer SEED14placeholder'], @@ -129,6 +135,7 @@ public function alternatingTenantsNeverLeakWithTheResetterOff(): void gc_collect_cycles(); self::assertLessThan(self::MEMORY_MARGIN, memory_get_usage() - $memory, 'memory flat'); } finally { + NativeFileStreams::end($native); $kernel->shutdown(); } } diff --git a/tests/Integration/WorkerModeKeptAliveKernelTest.php b/tests/Integration/WorkerModeKeptAliveKernelTest.php index 211f2cd..194d9a8 100644 --- a/tests/Integration/WorkerModeKeptAliveKernelTest.php +++ b/tests/Integration/WorkerModeKeptAliveKernelTest.php @@ -10,6 +10,7 @@ use Nowo\HttpLogBundle\Service\HttpLogRecorder; use Nowo\HttpLogBundle\Tests\Kernel\PublicServicesPass; use Nowo\HttpLogBundle\Tests\Kernel\UsageKernel; +use Nowo\HttpLogBundle\Tests\Support\NativeFileStreams; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Compiler\PassConfig; @@ -45,6 +46,7 @@ public function aKeptAliveKernelRecordsManyRequestsWithFlatMemoryAndNoLeak(): vo $container->addCompilerPass(new PublicServicesPass([HttpLogRecorder::class, 'security.token_storage']), PassConfig::TYPE_BEFORE_REMOVING); }, 'worker-kept-alive'); $kernel->boot(); + $native = false; try { $container = $kernel->getContainer()->get('test.service_container'); @@ -60,6 +62,10 @@ public function aKeptAliveKernelRecordsManyRequestsWithFlatMemoryAndNoLeak(): vo self::assertInstanceOf(TerminableInterface::class, $httpKernel); $baseline = 0; for ($i = 0; $i < self::REQUESTS; ++$i) { + if ($i === 2) { + // one warm-up request of each visitor ran through BypassFinals: measure the bundle, not the harness + $native = NativeFileStreams::begin(); + } if ($i === self::WARMUP) { gc_collect_cycles(); $baseline = memory_get_usage(); @@ -93,6 +99,7 @@ public function aKeptAliveKernelRecordsManyRequestsWithFlatMemoryAndNoLeak(): vo self::assertSame(self::REQUESTS, (int) $em->getConnection()->fetchOne('SELECT COUNT(*) FROM nowo_http_log_entry')); self::assertSame(0, $em->getUnitOfWork()->size()); } finally { + NativeFileStreams::end($native); $kernel->shutdown(); } } diff --git a/tests/Support/AdminTwigHarness.php b/tests/Support/AdminTwigHarness.php index 7eea94c..9d5dbd7 100644 --- a/tests/Support/AdminTwigHarness.php +++ b/tests/Support/AdminTwigHarness.php @@ -44,6 +44,7 @@ use Twig\Loader\FilesystemLoader; use Twig\RuntimeLoader\FactoryRuntimeLoader; +use function array_unique; use function dirname; /** @@ -62,11 +63,14 @@ private UrlGenerator $router; - public function __construct() + public function __construct(string $locale = 'en') { - $this->translator = new Translator('en'); + $this->translator = new Translator($locale, null, null, false); + $this->translator->setFallbackLocales(['en']); $this->translator->addLoader('yaml', new YamlFileLoader()); - $this->translator->addResource('yaml', dirname(__DIR__, 2) . '/src/Resources/translations/NowoHttpLogBundle.en.yaml', 'en', 'NowoHttpLogBundle'); + foreach (array_unique(['en', $locale]) as $catalogueLocale) { + $this->translator->addResource('yaml', dirname(__DIR__, 2) . '/src/Resources/translations/NowoHttpLogBundle.' . $catalogueLocale . '.yaml', $catalogueLocale, 'NowoHttpLogBundle'); + } $this->translator->addResource('yaml', dirname(__DIR__, 2) . '/vendor/nowo-tech/ui-kit-bundle/src/Resources/translations/NowoUiKitBundle.en.yaml', 'en', 'NowoUiKitBundle'); $filterType = new HttpLogFilterType(); diff --git a/tests/Support/NativeFileStreams.php b/tests/Support/NativeFileStreams.php new file mode 100644 index 0000000..d9cf932 --- /dev/null +++ b/tests/Support/NativeFileStreams.php @@ -0,0 +1,63 @@ +index($request)->getContent()); } + #[Test] + public function indexPassesTheOptInModesToTheTemplate(): void + { + $request = Request::create('/admin/http-log', 'GET'); + + $form = $this->createMock(FormInterface::class); + $form->method('isSubmitted')->willReturn(false); + $form->method('createView')->willReturn(new FormView()); + + $repository = $this->createMock(HttpLogEntryRepository::class); + $repository->method('findListRows')->willReturn(['items' => [], 'total' => 0, 'total_capped' => false, 'page' => 1, 'cursor' => null]); + + $twig = $this->createMock(Environment::class); + $twig->expects(self::once()) + ->method('render') + ->with( + '@NowoHttpLogBundle/admin/index.html.twig', + self::callback(static fn (array $parameters): bool => $parameters['filter_actions'] === 'filter_bar' + && $parameters['page']->header->actionsLayout === 'split' + && count($parameters['page']->header->actions) === 3 + && $parameters['page']->header->actions[2]->confirm instanceof Confirm), + ) + ->willReturn('index'); + + $controller = $this->createController( + request: $request, + repository: $repository, + formFactory: $this->createIndexFormFactory($form), + twig: $twig, + allowUnauthenticated: true, + webUi: ['header_actions' => 'split', 'filter_actions' => 'filter_bar'], + ); + + self::assertSame('index', $controller->index($request)->getContent()); + } + #[Test] public function indexHidesHeaderActionsTheUserMayNotUse(): void { diff --git a/tests/Unit/DependencyInjection/ConfigurationTest.php b/tests/Unit/DependencyInjection/ConfigurationTest.php index a45aa54..bb6ddb9 100644 --- a/tests/Unit/DependencyInjection/ConfigurationTest.php +++ b/tests/Unit/DependencyInjection/ConfigurationTest.php @@ -48,6 +48,8 @@ public function testDefaultConfiguration(): void self::assertTrue($config['web_ui']['enabled']); self::assertSame('/admin/http-log', $config['web_ui']['path_prefix']); self::assertSame(CssFramework::Bootstrap5->value, $config['web_ui']['css_framework']); + self::assertSame('toolbar', $config['web_ui']['header_actions'], '1.25 opt-in: the 1.24 toolbar by default'); + self::assertSame('scaffold', $config['web_ui']['filter_actions'], '1.25 opt-in: the scaffold filter row by default'); self::assertSame(['ROLE_ADMIN'], $config['security']['access_roles']); self::assertFalse($config['security']['allow_unauthenticated']); } @@ -114,6 +116,18 @@ public function testRejectsInvalidPathPrefix(): void ]]); } + public function testHeaderAndFilterActionsAcceptOnlyTheirModes(): void + { + $config = (new Processor())->processConfiguration(new Configuration(), [[ + 'web_ui' => ['header_actions' => 'split', 'filter_actions' => 'filter_bar'], + ]]); + self::assertSame('split', $config['web_ui']['header_actions']); + self::assertSame('filter_bar', $config['web_ui']['filter_actions']); + + $this->expectException(InvalidConfigurationException::class); + (new Processor())->processConfiguration(new Configuration(), [['web_ui' => ['header_actions' => 'page_actions']]]); + } + public function testPathPrefixTrailingSlashIsTrimmed(): void { $config = (new Processor())->processConfiguration(new Configuration(), [[ diff --git a/tests/Unit/Form/HttpLogFilterTypeTest.php b/tests/Unit/Form/HttpLogFilterTypeTest.php index eb0321c..5d5d568 100644 --- a/tests/Unit/Form/HttpLogFilterTypeTest.php +++ b/tests/Unit/Form/HttpLogFilterTypeTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormFactoryBuilder; +use Symfony\Component\Translation\TranslatableMessage; use function array_keys; @@ -79,8 +80,12 @@ public function fieldsAreOrderedForTheFilterRowAndSelectsOfferAnAnyOption(): voi ['q', 'method', 'statusCode', 'clientIp', 'path', 'routeName', 'bodyContentType', 'createdFrom', 'createdTo'], array_keys($form->all()), ); - self::assertSame('filter.any', $form->get('method')->getConfig()->getOption('placeholder')); - self::assertSame('filter.any', $form->get('bodyContentType')->getConfig()->getOption('placeholder')); + $method = $form->get('method')->getConfig()->getOption('placeholder'); + self::assertInstanceOf(TranslatableMessage::class, $method); + self::assertSame(['filter.any_method', 'NowoHttpLogBundle'], [$method->getMessage(), $method->getDomain()]); + $body = $form->get('bodyContentType')->getConfig()->getOption('placeholder'); + self::assertInstanceOf(TranslatableMessage::class, $body); + self::assertSame(['filter.any_body_type', 'NowoHttpLogBundle'], [$body->getMessage(), $body->getDomain()]); self::assertFalse($form->get('createdFrom')->getConfig()->getOption('with_seconds')); self::assertSame('datetime-local', $form->createView()['createdTo']->vars['type']); } diff --git a/tests/Unit/Translations/FilterAnyTranslationsTest.php b/tests/Unit/Translations/FilterAnyTranslationsTest.php new file mode 100644 index 0000000..b5020dc --- /dev/null +++ b/tests/Unit/Translations/FilterAnyTranslationsTest.php @@ -0,0 +1,55 @@ + */ + public static function locales(): iterable + { + foreach (['en', 'es', 'fr', 'de', 'it', 'pt', 'nl'] as $locale) { + yield $locale => [$locale]; + } + } + + #[Test] + #[DataProvider('locales')] + public function everyAnyKeyIsTranslated(string $locale): void + { + $catalogue = $this->load($locale); + $english = $this->load('en'); + + foreach ([...self::KEYS, 'filter.client_ip_placeholder'] as $key) { + self::assertArrayHasKey($key, $catalogue, $key . ' (' . $locale . ')'); + self::assertNotSame('', $catalogue[$key]); + self::assertNotSame($key, $catalogue[$key]); + } + if ($locale !== 'en') { + foreach (self::KEYS as $key) { + self::assertNotSame($english[$key], $catalogue[$key], $key . ' still English in ' . $locale); + } + } + } + + /** @return array */ + private function load(string $locale): array + { + $data = Yaml::parseFile(dirname(__DIR__, 3) . '/src/Resources/translations/NowoHttpLogBundle.' . $locale . '.yaml'); + self::assertTrue(is_array($data)); + + return $data; + } +}