76 Commits
Author SHA1 Message Date
haylan 00d959e661 Merge pull request 'fix(dump): pass --column-statistics=0 for MySQL 8 mysqldump on MariaDB, release as 0.0.7' (!17) from fix/0.0.7-column-statistics into main
release / release (push) Successful in 1m8s
Reviewed-on: #17
2026-11-02 22:39:41 +00:00
haylanandClaude Bot fa50fa3343 ci(phpunit): install core patches that have no shopware/production tag
plugin-checks / version-changelog (pull_request) Successful in 19s
plugin-checks / package (pull_request) Successful in 1m3s
plugin-checks / phpunit (pull_request) Successful in 5m35s
The newest shopware/core in ~6.6.0 is 6.6.10.31, but shopware/production
is only tagged up to 6.6.10.30, so create-project failed. Install the newest
template inside the constraint and require the resolved core version on top.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:33:58 +01:00
haylanandClaude Bot 6b7ba3bc47 fix(dump): pass --column-statistics=0 for MySQL 8 mysqldump on MariaDB, release as 0.0.7
plugin-checks / version-changelog (pull_request) Successful in 20s
plugin-checks / phpunit (pull_request) Failing after 37s
plugin-checks / package (pull_request) Successful in 1m27s
Backport for the Shopware 6.6 line. When the server is MariaDB but only
MySQL 8's mysqldump is installed (e.g. dockware/web), the dump aborted
with "Unknown table 'COLUMN_STATISTICS' in information_schema (1109)".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:29:05 +01:00
haylan 1176d3c87d Merge pull request 'fix(release): repack zip root-level for the Composer registry' (!14) from fix/release-registry-zip into main
release / release (push) Successful in 12s
Reviewed-on: #14
2026-10-03 23:21:07 +00:00
haylanandClaude Bot bfb88a25b8 chore: release as 0.0.6; compare the version check against published releases
plugin-checks / version-changelog (pull_request) Successful in 15s
plugin-checks / package (pull_request) Successful in 1m8s
plugin-checks / phpunit (pull_request) Successful in 2m34s
- composer.json 0.0.6, CHANGELOG entries of the withdrawn 0.1.0/0.1.1 merged into [0.0.6]
- version-changelog: version must exceed the latest published release (main may carry a
  version whose release was withdrawn), instead of exceeding main's version

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 01:18:29 +02:00
haylanandClaude Bot 7f3e77a3e9 ci: retrigger to exercise the cache-hit path
plugin-checks / version-changelog (pull_request) Successful in 21s
plugin-checks / package (pull_request) Successful in 1m1s
plugin-checks / phpunit (pull_request) Successful in 2m35s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 01:12:21 +02:00
haylanandClaude Bot 8b2c2278d2 ci: resolve the Shopware version with Composer from the plugin constraint; harden the registry repack
plugin-checks / version-changelog (pull_request) Successful in 18s
plugin-checks / package (pull_request) Successful in 1m3s
plugin-checks / phpunit (pull_request) Successful in 6m14s
- phpunit: 'Resolve the latest Shopware Version' uses composer show against require.shopware/core
  from the plugin's composer.json (the Packagist scrape returned nothing on the first run)
- release: build the registry zip from an explicit file list without a leading ./ so the
  composer.json entry is stored at the zip root

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 01:05:25 +02:00
haylanandClaude Bot 18844718d2 ci(phpunit): cache the installed database, key the cache on the Shopware version
plugin-checks / version-changelog (pull_request) Successful in 16s
plugin-checks / phpunit (pull_request) Failing after 27s
plugin-checks / package (pull_request) Successful in 59s
- resolve the latest 6.6.x from Packagist; cache key shopware-<version>-installed-v1
- cache the project plus a SQL dump of the installed shopware_test database; on a hit restore
  the dump instead of running system:install (~4.6 min)
- rename the step 'Install Shopware (once)' to 'Install Shopware'

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 01:01:21 +02:00
haylanandClaude Bot eb2a3172e5 fix(package): exclude .config and .gitea from the zip
plugin-checks / version-changelog (pull_request) Successful in 25s
plugin-checks / package (pull_request) Successful in 1m9s
plugin-checks / phpunit (pull_request) Canceled after 2m30s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:58:42 +02:00
haylanandClaude Bot 953f4ee579 docs: research shopware-cli changelog handling and PHP floor
plugin-checks / version-changelog (pull_request) Successful in 22s
plugin-checks / package (pull_request) Successful in 1m1s
plugin-checks / phpunit (pull_request) Canceled after 5m12s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:53:26 +02:00
haylanandClaude Bot 391db5b621 docs: match CLAUDE.md to the idempotent release and registry repack
plugin-checks / version-changelog (pull_request) Successful in 22s
plugin-checks / package (pull_request) Successful in 1m12s
plugin-checks / phpunit (pull_request) Canceled after 3m1s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:50:20 +02:00
haylanandClaude Bot 8afe30b476 test: assert plugin logs to injected PSR logger
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:50:19 +02:00
haylanandClaude Bot 5f8cc9bdad docs: refresh CLAUDE.md and compliance spec after guideline PR
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:49:57 +02:00
haylanandClaude Bot c08d27c8e1 fix(release): repack the zip root-level for the Composer registry; make release steps idempotent
Gitea's registry answered 400 'composer.json file is missing' for the shopware-cli zip
(single top-level folder). Repack the same prebuilt content with composer.json at the root.
Drop the tag-exists skip guard so a half-finished release can be re-run; reuse an existing
release/asset. Bump to 0.1.1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:49:53 +02:00
haylan 85980ee3bf Merge pull request 'feat: align plugin and pipeline with Shopware guidelines' (!13) from ci/shopware-guideline-compliance into main
release / release (push) Failing after 11s
Reviewed-on: #13
2026-10-03 22:46:17 +00:00
haylanandClaude Bot 8a72751a14 ci: single Shopware install into shopware_test; serialize releases
plugin-checks / version-changelog (pull_request) Successful in 16s
plugin-checks / package (pull_request) Successful in 1m1s
plugin-checks / phpunit (pull_request) Successful in 6m2s
DATABASE_URL already ends in _test so the TestBootstrapper finds an installed DB and
skips its own migration run; FORCE_INSTALL (which failed with an unknown database) removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:36:22 +02:00
haylanandClaude Bot 233f3eb17f ci: merge version check into plugin-checks, share packaging as a composite action
plugin-checks / version-changelog (pull_request) Successful in 22s
plugin-checks / package (pull_request) Successful in 1m8s
plugin-checks / phpunit (pull_request) Failing after 1m53s
- one PR workflow (plugin-checks) with version-changelog, package, phpunit jobs
- .gitea/actions/package: package + validate + assert, used by PR and release
- phpunit: FORCE_INSTALL so the TestBootstrapper installs its own test DB
- protect-main.sh: required context is now plugin-checks / version-changelog

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:32:16 +02:00
haylanandClaude Bot 37aba5d2f0 ci: cache the Shopware project, drop duplicate install, reuse the tested zip in release
version-changelog / version-changelog (pull_request) Successful in 24s
plugin-checks / package (pull_request) Successful in 1m18s
plugin-checks / phpunit (pull_request) Failing after 1m33s
- phpunit: cache the prepared project (vendor + phpunit) monthly via cache restore/save;
  drop system:install/plugin:install (TestBootstrapper installs into its own test DB, so
  every migration ran twice, ~5.5 min each); relax InnoDB durability on the CI database
- package: save the tested zip keyed by the commit's tree hash; release restores it and
  only re-packages on a miss, but always validates and asserts the zip
- cancel superseded PR runs (concurrency)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:29:17 +02:00
haylanandClaude Bot 9f760cb6b0 chore: mark CI scripts executable
version-changelog / version-changelog (pull_request) Successful in 53s
plugin-checks / package (pull_request) Successful in 1m43s
plugin-checks / phpunit (pull_request) Failing after 14m43s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:15:33 +02:00
haylanandClaude Bot ff69377749 ci: dedupe validate into package, add caches, run phpunit in the shopware-cli image
version-changelog / version-changelog (pull_request) Successful in 51s
plugin-checks / package (pull_request) Failing after 1m26s
plugin-checks / phpunit (pull_request) Failing after 3m3s
- drop the separate validate job (the zip is validated after packaging); same in release
- shared scripts/ci/assert-built-assets.sh (BusyBox-safe), now also used by release
- actions/cache for npm, shopware-cli and composer
- phpunit: shopware-cli image instead of a 4.5 min apt install; MariaDB 10.11
  (11.4 broke Shopware's migrations: Duplicate column 'sorter_key')
- protect-main.sh: drop the removed validate context

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:15:25 +02:00
haylanandClaude Bot c3b242675e ci: run shopware-cli jobs in the official Docker image
version-changelog / version-changelog (pull_request) Successful in 59s
plugin-checks / validate (pull_request) Successful in 3m1s
plugin-checks / package (pull_request) Failing after 3m47s
plugin-checks / phpunit (pull_request) Failing after 6m38s
Replaces the curl/tar install and setup-node steps; the image ships the
CLI plus its PHP/Node toolchain.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:07:07 +02:00
haylanandClaude Bot 1ec194b464 ci: PHP via apt in a bookworm container, retry shopware-cli download
plugin-checks / validate (pull_request) Successful in 1m49s
version-changelog / version-changelog (pull_request) Successful in 1m55s
plugin-checks / package (pull_request) Successful in 2m15s
plugin-checks / phpunit (pull_request) Failing after 10m31s
setup-php hangs on the runner even with runner=self-hosted; the CLI download
returned a non-gzip body once under concurrent load.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 00:03:12 +02:00
haylanandClaude Bot 221ffece3f ci: fix hanging setup-php, wait for DB manually, add compatibility_date
version-changelog / version-changelog (pull_request) Successful in 26s
plugin-checks / validate (pull_request) Failing after 1m45s
plugin-checks / package (pull_request) Failing after 1m45s
plugin-checks / phpunit (pull_request) Canceled after 11m9s
- validate job needs no PHP (the package job already validates without it)
- phpunit: runner=self-hosted so setup-php does not hang under act; replace the
  unhealthy service healthcheck with a TCP wait loop
- .config/shopware-extension.yml: set compatibility_date

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 23:51:10 +02:00
haylan 54eeab70aa fix(plugin): reword descriptions, add transparent icon variant
version-changelog / version-changelog (pull_request) Successful in 42s
plugin-checks / package (pull_request) Successful in 1m38s
plugin-checks / phpunit (pull_request) Failing after 1m59s
plugin-checks / validate (pull_request) Canceled after 16m9s
2026-10-03 23:46:11 +02:00
haylanandClaude Bot 89a445f900 fix: satisfy shopware-cli validate (description length, icon under 30kb)
version-changelog / version-changelog (pull_request) Successful in 38s
plugin-checks / package (pull_request) Successful in 1m35s
plugin-checks / phpunit (pull_request) Failing after 2m1s
plugin-checks / validate (pull_request) Successful in 15m51s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 23:37:03 +02:00
haylanandClaude Bot a551034442 ci: plugin-agnostic PR checks and package-then-release pipeline
version-changelog / version-changelog (pull_request) Successful in 50s
plugin-checks / package (pull_request) Failing after 1m50s
plugin-checks / validate (pull_request) Failing after 31m29s
plugin-checks / phpunit (pull_request) Canceled after 33m2s
- plugin-checks workflow: shopware-cli validate, package + built-JS assertion, phpunit
- release: validate, package from the merge commit, validate the zip, create the release
  via the Gitea API, publish the same zip to the Composer registry
- scripts/protect-main.sh sets required status checks via tea api
- bump to 0.1.0

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 23:28:15 +02:00
haylanandClaude Bot 8efaef2042 feat(plugin): align with Shopware plugin guidelines
- add dedicated monolog channel aeon_dump_manager and log dump jobs
- migrate services.xml/routes.php to YAML
- require PHP ^8.2
- add extension icon and .config/shopware-extension.yml
- drop empty lifecycle overrides

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 23:26:21 +02:00
haylanandClaude Bot 29974928d2 docs(spec): add Shopware guideline compliance spec
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 23:22:23 +02:00
haylan 36ef203797 Merge pull request 'chore:(composer): namespace fix' (!12) from namespace-fix into main
release / release (push) Successful in 54s
Reviewed-on: #12
2026-09-21 19:31:07 +00:00
haylan ba2d1ec1d6 chroe(changelog): version dump
version-changelog / version-changelog (pull_request) Successful in 18s
2026-09-21 21:30:19 +02:00
haylan d117444bae chore(bump): version
version-changelog / version-changelog (pull_request) Failing after 4s
2026-09-21 21:29:04 +02:00
haylan 58df03216d chore:(composer): namespace fix
version-changelog / version-changelog (pull_request) Failing after 5s
2026-09-21 21:27:58 +02:00
haylan 29402a35ac Merge pull request 'ci: link published Composer packages to this repository' (!11) from ci/link-package-fix into main
release / release (push) Successful in 50s
2026-09-21 18:40:29 +00:00
haylan 63134f7de4 chore(release): bump to 0.0.4 for the Composer package-link fix
version-changelog / version-changelog (pull_request) Successful in 6s
2026-09-21 20:40:03 +02:00
haylan b8b8ee6284 ci: treat HTTP 400 (already linked) as expected on the package-link step 2026-09-21 20:39:10 +02:00
haylan b93217cc51 test: verify RELEASE_TOKEN can call the package-link endpoint 2026-09-21 20:11:54 +02:00
haylan 61b4b2b1af ci: link the published Composer package to this repository 2026-09-21 20:10:55 +02:00
haylan ec5c40c9f2 Merge pull request 'feat(dump): date-range filter, sortable columns, native date formatting' (!10) from feat/dump-list-view into main
release / release (push) Successful in 1m1s
2026-09-21 18:00:42 +00:00
haylan 56ada0cedc Merge remote-tracking branch 'origin/main' into feat/dump-list-view
version-changelog / version-changelog (pull_request) Successful in 5s
# Conflicts:
#	composer.json
2026-09-21 19:59:19 +02:00
haylan f50154b96b chore(release): bump to 0.0.3 for the date-range filter release 2026-09-21 19:58:04 +02:00
haylan 7aa11b0396 Merge pull request 'ci: add pre-merge version-and-changelog check' (!7) from ci/pr-version-check into main
release / release (push) Successful in 50s
2026-09-21 17:48:25 +00:00
haylan 161c35dc8a chore(release): bump to 0.0.2 for the CI/CD release pipeline itself
version-changelog / version-changelog (pull_request) Successful in 5s
2026-09-21 19:18:06 +02:00
haylan a1f0160ab9 Merge remote-tracking branch 'origin/ci/release-workflow' into ci/pr-version-check 2026-09-21 19:17:31 +02:00
haylan 1ee83aad37 ci: hardcode SERVER_URL as a workflow env var instead of an Actions variable 2026-09-21 19:10:24 +02:00
haylan b2c2a8d80b ci: add post-merge tag, package, and release workflow 2026-09-21 18:53:22 +02:00
haylan 31b9e61adb ci: add pre-merge version-and-changelog check for PRs into main
version-changelog / version-changelog (pull_request) Failing after 8s
2026-09-21 18:37:10 +02:00
haylanandClaude Bot 5a482b49bb feat(dump): add date-range filter, sortable columns, and native date formatting to admin list
- Wires the backend from/to filter into the UI via sw-filter-panel with
  a hand-built date-filter config (no DAL entity needed — sw-filter-panel's
  only external dependency, filterService, persists through the generic
  user_config entity, not one for the filtered resource).
- Makes the datetime and sizeBytes columns sortable (ascending/descending)
  using the same Mixin.getByName('listing') core list pages use, which
  also persists sort state in the URL query string.
- Replaces the ad hoc `new Date(value).toLocaleString()` with
  Shopware.Utils.format.date, matching the existing fileSize formatting
  and respecting the admin's locale/timezone.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:39:23 +02:00
haylanandClaude Bot 6094b6f49c test(dump): replace @dataProvider annotations with #[DataProvider] attributes
The installed PHPUnit (12.x, ahead of this plugin's ^10.0 dev
constraint) no longer parses the @dataProvider PHPDoc annotation,
so both tests silently ran their data-provider method with zero
arguments and failed with ArgumentCountError.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:39:08 +02:00
haylanandClaude Bot e5c3a5b28f fix(dump): normalize date-filter bounds to the app timezone before applying day boundary
The admin date filter can send a naive local date string for "from" but
a UTC Z-suffixed instant for "to" (sw-date-filter widens it client-side
via Date#toISOString()). Comparing those directly against dump
timestamps (parsed in PHP's default timezone) shifted the effective
cutoff by the timezone offset. Re-express both bounds in the app's
default timezone before applying the day boundary.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:38:54 +02:00
haylan f967ef7544 feat(dump): filter admin dump list by from/to date range
Adds optional from/to query params to the dumps list endpoint and
DumpLister::list(), and bumps the plugin version to 0.0.2.
2026-09-17 12:38:39 +02:00
haylan 20492e8c80 chore(dump): removed cahche git ignored files 2026-09-15 06:23:40 +02:00
haylan 2c7a105332 chore(dump): removed cahche git ignored files 2026-09-15 06:21:44 +02:00
haylan 0401859227 feat(dump): update .gitignore for frontend assets and add changelog 2026-09-15 06:19:45 +02:00
haylan 2683792fee feat(dump): add download functionality for dumps and improve UI interactions 2026-09-14 23:54:57 +02:00
haylan 29abb1cd59 docs(dump): add changelog 2026-09-14 23:01:16 +02:00
haylan 05e1d0eeb9 fix(dump): correct DI wiring, config types, and runtime version query 2026-09-14 23:01:16 +02:00
haylanandQwen-Coder 59e48c8f21 build(dump): migrate admin UI to TypeScript and commit built bundle
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-09-14 23:01:16 +02:00
haylan b89a878b92 chore: normalize file modes on root config files 2026-09-14 22:00:26 +02:00
haylan 9713f9f780 feat(dump): drop the job table when the plugin is uninstalled 2026-09-14 22:00:26 +02:00
haylan 3a7bcee096 build(dump): register dump services in the DI container 2026-09-14 22:00:26 +02:00
haylan 0b71a62d40 chore(dump): remove scaffold example command, task and admin module 2026-09-14 22:00:26 +02:00
haylan 92f8605dd0 feat(dump): add settings-page admin UI module 2026-09-14 22:00:26 +02:00
haylan 1d8d2de118 feat(dump): expose dumps through a settings-page admin API 2026-09-14 22:00:26 +02:00
haylan b66bc550cd feat(dump): add console commands to list, create and remove dumps 2026-09-14 22:00:26 +02:00
haylan a21b5aa73e feat(dump): purge expired dumps on a scheduled task 2026-09-14 22:00:26 +02:00
haylan 86069a51a3 feat(dump): run dump creation asynchronously via Messenger 2026-09-14 22:00:26 +02:00
haylan 0188a24278 feat(dump): create and delete dumps with retention config 2026-09-14 22:00:26 +02:00
haylan 309cdf3f09 feat(dump): list dumps stored in the plugin filesystem 2026-09-14 22:00:26 +02:00
haylan f982c3c3da feat(dump): track async dump jobs in a status table 2026-09-14 22:00:26 +02:00
haylan 44e7648e06 feat(dump): locate mysqldump/mariadb-dump binary 2026-09-14 22:00:26 +02:00
haylan d0e8ea582f test(dump): cover filename parsing and MySQL variant detection 2026-09-14 22:00:26 +02:00
haylan 957588d0b1 feat(dump): parse dump filenames and detect MySQL variant 2026-09-14 22:00:26 +02:00
haylan b4e84d0570 docs: add dump manager research notes 2026-09-14 22:00:26 +02:00
haylan 0dc19897a4 build: add Docker Compose for local Shopware 6.6 2026-09-14 22:00:26 +02:00
haylan e8121c701f docs: add agent guidance files 2026-09-14 22:00:25 +02:00
haylanandQwen-Coder 21d1f9f465 chore: ignore .scratch/ directory
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-09-14 22:00:25 +02:00
66 changed files with 3198 additions and 159 deletions

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
compatibility_date: 2026-02-11
# shopware-cli extension configuration (build/package/validate)
build:
zip:
pack:
excludes:
paths:
- tests
- docs
- scripts
- phpunit.xml
- docker-compose.yml
- skills-lock.json
- AGENTS.md
- CLAUDE.md
- QWEN.md
- .config
- .gitea
- .claude
- .scratch
- .wayfinder
- src/Resources/config/plugin-transparent.png
validation:
ignore: []
+35
View File
@@ -0,0 +1,35 @@
name: package-extension
description: >-
Package the Shopware extension with shopware-cli (builds admin/storefront assets), validate the
zip and assert it contains the built JS. Shared by the PR checks and the release workflow.
Must run in the ghcr.io/shopware/shopware-cli image, after actions/checkout.
inputs:
filename:
description: Name of the zip written to .build/
default: package.zip
build:
description: "'false' skips packaging (a prebuilt zip is already in .build/) and only validates it"
default: 'true'
runs:
using: composite
steps:
- uses: actions/cache@v4
if: inputs.build == 'true'
with:
path: |
~/.npm
~/.cache/shopware-cli
key: swcli-${{ runner.os }}-${{ hashFiles('composer.json', 'src/Resources/app/**/package*.json') }}
restore-keys: swcli-${{ runner.os }}-
- name: Package extension
if: inputs.build == 'true'
shell: bash
run: shopware-cli extension package . --output-directory .build --filename "${{ inputs.filename }}" --git-commit "$GITHUB_SHA"
- name: Validate packaged zip
shell: bash
run: shopware-cli extension validate ".build/${{ inputs.filename }}"
- name: Assert built JS is in the zip
shell: bash
run: scripts/ci/assert-built-assets.sh ".build/${{ inputs.filename }}"
+190
View File
@@ -0,0 +1,190 @@
name: plugin-checks
# Plugin-agnostic: nothing below names this plugin. Name, version and paths come from composer.json.
# shopware-cli runs from its official Docker image, intentionally unpinned (latest); a red build
# after a CLI release means fix the config.
on:
pull_request:
branches: [main]
permissions:
contents: read
# A new push to the PR cancels the superseded run.
concurrency:
group: plugin-checks-${{ github.ref }}
cancel-in-progress: true
jobs:
# Every PR into main must bump the version and document it in CHANGELOG.md.
version-changelog:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The version must be higher than the latest *published release* (not just higher than main), so main can
# carry a version whose release failed or was withdrawn without blocking the next PR.
- name: Check version is unreleased and changelog entry exists
env:
TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
set -e
PR_VERSION=$(grep -m1 '"version"' composer.json | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
LATEST=$(curl -sf -H "Authorization: token ${TOKEN}" "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/releases?limit=100" \
| jq -r '.[].tag_name' | sed 's/^v//' | sort -V | tail -n1)
LATEST="${LATEST:-0.0.0}"
echo "latest release: $LATEST"
echo "PR version: $PR_VERSION"
if [ "$PR_VERSION" = "$LATEST" ] || [ "$(printf '%s\n%s\n' "$LATEST" "$PR_VERSION" | sort -V | tail -n1)" != "$PR_VERSION" ]; then
echo "::error::composer.json version ($PR_VERSION) is not greater than the latest release ($LATEST)"
exit 1
fi
if ! grep -qF "## [$PR_VERSION]" CHANGELOG.md; then
echo "::error::CHANGELOG.md is missing a '## [$PR_VERSION]' heading"
exit 1
fi
echo "OK: $PR_VERSION is unreleased and documented in CHANGELOG.md"
# Packages the extension (builds admin/storefront assets) and validates the resulting zip,
# which is the artifact that ships. A separate directory validate would only repeat these checks.
package:
runs-on: ubuntu-latest
container:
image: ghcr.io/shopware/shopware-cli:latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: ./.gitea/actions/package
# The release workflow reuses this tested zip when main ends up with the same tree
# (it falls back to packaging again otherwise).
- name: Tree hash of the packaged commit
id: tree
run: echo "hash=$(git rev-parse "${GITHUB_SHA}^{tree}")" >> "$GITHUB_OUTPUT"
- name: Save tested zip for the release
uses: actions/cache/save@v4
with:
path: .build/package.zip
key: plugin-zip-${{ steps.tree.outputs.hash }}
phpunit:
runs-on: ubuntu-latest
# Same image as above: it already ships PHP, Composer and Node, so no apt install.
container:
image: ghcr.io/shopware/shopware-cli:latest
services:
database:
# Shopware 6.6 supports MariaDB 10.11 / MySQL 8; 11.4 broke Shopware's own migrations.
image: mariadb:10.11
env:
MARIADB_ROOT_PASSWORD: root
env:
# Already the *_test name: Shopware's TestBootstrapper would otherwise append _test and run every migration a second time.
DATABASE_URL: mysql://root:root@database:3306/shopware_test
APP_ENV: test
APP_URL: http://localhost
APP_SECRET: ci-secret-not-for-production
INSTANCE_ID: ci
COMPOSER_MEMORY_LIMIT: '-1'
COMPOSER_ALLOW_SUPERUSER: '1'
steps:
- uses: actions/checkout@v4
with:
path: plugin-src
# The cache key follows the Shopware version: a new release inside the plugin's supported range changes
# the key, so the old project + database are never reused. Bump -v1 to force a refresh by hand.
- name: Resolve the latest Shopware Version
id: sw
run: |
set -e
# The plugin's own constraint (require.shopware/core, e.g. ~6.6.0) decides which versions are acceptable;
# Composer lists the matching ones newest first, the first stable one is the latest.
CONSTRAINT=$(php -r 'echo json_decode(file_get_contents("plugin-src/composer.json"), true)["require"]["shopware/core"];')
VERSION=$(composer show shopware/core "$CONSTRAINT" --all --format=json --no-interaction 2>/dev/null \
| php -r '$d = json_decode(stream_get_contents(STDIN), true); foreach ($d["versions"] as $v) { if (preg_match("/^v?\d+(\.\d+)+$/", $v)) { echo ltrim($v, "v"); exit; } }')
test -n "$VERSION" || { echo "::error::could not resolve a Shopware version for ${CONSTRAINT}"; exit 1; }
echo "Shopware ${VERSION} (constraint ${CONSTRAINT})"
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "constraint=${CONSTRAINT}" >> "$GITHUB_OUTPUT"
# Project (vendor/, phpunit, config) and the installed database as a SQL dump. Neither depends on the plugin.
- name: Restore Shopware project and database
id: shopware
uses: actions/cache/restore@v4
with:
path: |
shopware
!shopware/var/cache
!shopware/var/log
shopware-db.sql.gz
key: shopware-${{ steps.sw.outputs.version }}-installed-v1
- name: Create Shopware project
if: steps.shopware.outputs.cache-hit != 'true'
run: |
set -e
# shopware/production pins one exact core version and is not tagged for every core patch
# (e.g. core 6.6.10.31, template only up to 6.6.10.30): take the newest template inside the
# constraint, then require the resolved core version on top of it.
composer create-project "shopware/production:${{ steps.sw.outputs.constraint }}" shopware --no-interaction --no-scripts --no-install
composer require "shopware/core:${{ steps.sw.outputs.version }}" --no-update -d shopware
composer require --dev phpunit/phpunit:^10 --no-update -d shopware
composer update -W --no-interaction --no-scripts -d shopware
- name: Ensure the MariaDB client
run: |
command -v mariadb-dump >/dev/null || command -v mysqldump >/dev/null && exit 0
(apt-get update -q && apt-get install -y -q --no-install-recommends mariadb-client) || apk add --no-cache mariadb-client
- name: Wait for the database
run: |
for i in $(seq 60); do
(echo > /dev/tcp/database/3306) 2>/dev/null && exit 0
sleep 2
done
echo "::error::database service did not come up"; exit 1
- name: Relax database durability (throwaway CI database, speeds up the install and the restore)
run: |
php -r '$p = new PDO("mysql:host=database;port=3306", "root", "root"); $p->exec("SET GLOBAL innodb_flush_log_at_trx_commit=0"); $p->exec("SET GLOBAL sync_binlog=0");'
# One install into shopware_test; the bootstrapper then sees an installed DB, skips its own install and
# only activates the plugin (tests/TestBootstrap.php forces plugin installation).
- name: Install Shopware
if: steps.shopware.outputs.cache-hit != 'true'
working-directory: shopware
run: bin/console system:install --basic-setup --create-database --force --no-interaction
- name: Dump the installed database
if: steps.shopware.outputs.cache-hit != 'true'
run: |
set -e
DUMP=$(command -v mariadb-dump || command -v mysqldump)
"$DUMP" -h database -P 3306 -u root -proot --skip-ssl --single-transaction --routines --triggers \
--databases shopware_test | gzip > shopware-db.sql.gz
ls -l shopware-db.sql.gz
- name: Save Shopware project and database
if: steps.shopware.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: |
shopware
!shopware/var/cache
!shopware/var/log
shopware-db.sql.gz
key: shopware-${{ steps.sw.outputs.version }}-installed-v1
- name: Restore the database from the cache
if: steps.shopware.outputs.cache-hit == 'true'
run: |
set -e
CLIENT=$(command -v mariadb || command -v mysql)
gunzip -c shopware-db.sql.gz | "$CLIENT" -h database -P 3306 -u root -proot --skip-ssl
- name: Resolve plugin name and install the plugin sources
run: |
# plugin directory name = short class name of extra.shopware-plugin-class
CLASS=$(php -r 'echo json_decode(file_get_contents("plugin-src/composer.json"), true)["extra"]["shopware-plugin-class"];')
PLUGIN_NAME="${CLASS##*\\}"
echo "PLUGIN_NAME=${PLUGIN_NAME}" >> "$GITHUB_ENV"
rm -rf "shopware/custom/plugins/${PLUGIN_NAME}"
cp -r plugin-src "shopware/custom/plugins/${PLUGIN_NAME}"
- name: Run phpunit
working-directory: shopware
run: vendor/bin/phpunit -c "custom/plugins/${PLUGIN_NAME}/phpunit.xml"
+154
View File
@@ -0,0 +1,154 @@
name: release
# Plugin-agnostic: owner, repo, host, package name and version come from the `github` context
# and composer.json. shopware-cli runs from its official Docker image, intentionally unpinned (latest).
# RELEASE_TOKEN is the single token used for releases, assets and the Composer registry.
#
# Every step is idempotent (release/asset reuse, registry 409 = already published), so a failed run can
# simply be re-run and picks up where it stopped. There is deliberately no "tag exists -> skip" guard:
# it made a half-finished release (tag + release but no registry package) impossible to heal.
on:
push:
branches: [main]
permissions:
contents: write
packages: write
# Never run two releases at once; a second push waits instead of racing on the tag.
concurrency:
group: release
cancel-in-progress: false
jobs:
release:
runs-on: ubuntu-latest
container:
image: ghcr.io/shopware/shopware-cli:latest
steps:
- name: Ensure helper tools (jq, curl, unzip, zip, git)
run: |
command -v jq >/dev/null && command -v curl >/dev/null && command -v unzip >/dev/null && command -v zip >/dev/null && command -v git >/dev/null && exit 0
(apt-get update -q && apt-get install -y -q --no-install-recommends jq curl unzip zip git) || apk add --no-cache jq curl unzip zip git
- uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.RELEASE_TOKEN }}
- name: Determine version, tag and file names
id: meta
run: |
set -e
VERSION=$(jq -r .version composer.json)
PACKAGE_NAME=$(jq -r .name composer.json)
REPO_NAME="${GITHUB_REPOSITORY#*/}"
TAG="v${VERSION}"
{
echo "version=${VERSION}"
echo "package_name=${PACKAGE_NAME}"
echo "tag=${TAG}"
echo "zip=${REPO_NAME}-${TAG}.zip"
} >> "$GITHUB_OUTPUT"
# Reuse the zip the PR workflow already built and tested for this exact tree.
- name: Tree hash of this commit
id: tree
run: echo "hash=$(git rev-parse "${GITHUB_SHA}^{tree}")" >> "$GITHUB_OUTPUT"
- name: Restore the tested zip from the PR run
id: prebuilt
uses: actions/cache/restore@v4
with:
path: .build/package.zip
key: plugin-zip-${{ steps.tree.outputs.hash }}
- name: Name the prebuilt zip
if: steps.prebuilt.outputs.cache-hit == 'true'
run: mv .build/package.zip ".build/${{ steps.meta.outputs.zip }}"
# Packages only on a cache miss; always validates and asserts what ships (guards a bad cache entry).
- uses: ./.gitea/actions/package
with:
filename: ${{ steps.meta.outputs.zip }}
build: ${{ steps.prebuilt.outputs.cache-hit != 'true' }}
- name: Extract changelog section
run: |
awk -v ver="${{ steps.meta.outputs.version }}" '
BEGIN { found=0 }
/^## \[/ {
if (found) exit
if ($0 ~ "\\[" ver "\\]") { found=1; next }
}
found { print }
' CHANGELOG.md > release-notes.md
cat release-notes.md
- name: Create Gitea release (creates the tag) and upload the zip
env:
TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
set -e
API="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
TAG="${{ steps.meta.outputs.tag }}"
ZIP="${{ steps.meta.outputs.zip }}"
CODE=$(curl -s -o /tmp/release.json -w "%{http_code}" -H "Authorization: token ${TOKEN}" "${API}/releases/tags/${TAG}")
if [ "$CODE" = "200" ]; then
echo "Release ${TAG} already exists, reusing it."
else
BODY=$(jq -n --arg tag "$TAG" --arg sha "$GITHUB_SHA" --rawfile notes release-notes.md \
'{tag_name:$tag, target_commitish:$sha, name:$tag, body:$notes}')
curl -sf -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" -d "$BODY" "${API}/releases" > /tmp/release.json
fi
RELEASE_ID=$(jq -r .id /tmp/release.json)
echo "release id: ${RELEASE_ID}"
if jq -e --arg n "$ZIP" '.assets[]? | select(.name == $n)' /tmp/release.json > /dev/null; then
echo "Asset ${ZIP} already uploaded."
else
curl -sf -H "Authorization: token ${TOKEN}" -F "attachment=@.build/${ZIP}" \
"${API}/releases/${RELEASE_ID}/assets?name=${ZIP}" > /dev/null
fi
# Gitea's Composer registry needs composer.json at the zip root, but shopware-cli zips wrap
# everything in one top-level folder (the registry answers 400 "composer.json file is missing").
# Same prebuilt content, repacked root-level.
- name: Repack the zip for the Composer registry
run: |
set -e
rm -rf /tmp/repack && mkdir /tmp/repack
unzip -q ".build/${{ steps.meta.outputs.zip }}" -d /tmp/repack
if [ -f /tmp/repack/composer.json ]; then
ROOT=/tmp/repack
else
ROOT=$(find /tmp/repack -mindepth 1 -maxdepth 1 -type d | head -1)
fi
test -f "$ROOT/composer.json" || { echo "::error::no composer.json found in the packaged zip"; exit 1; }
OUT="$PWD/.build/composer-${{ steps.meta.outputs.zip }}"
# explicit file list with the leading "./" stripped, so entries are stored as "composer.json", "src/..."
(cd "$ROOT" && find . -mindepth 1 | sed 's|^\./||' | zip -q "$OUT" -@)
unzip -l "$OUT" | grep -E ' composer\.json$' > /dev/null || { echo "::error::repacked zip has no root-level composer.json"; exit 1; }
echo "repacked: $OUT"
- name: Publish to the Composer registry
run: |
STATUS=$(curl -s -o /tmp/composer-publish.log -w "%{http_code}" \
-u "${GITHUB_REPOSITORY_OWNER}:${{ secrets.RELEASE_TOKEN }}" \
-T ".build/composer-${{ steps.meta.outputs.zip }}" \
"${GITHUB_SERVER_URL}/api/packages/${GITHUB_REPOSITORY_OWNER}/composer")
cat /tmp/composer-publish.log
if [ "$STATUS" != "201" ] && [ "$STATUS" != "409" ]; then
echo "Unexpected HTTP status $STATUS publishing to the Composer registry"
exit 1
fi
- name: Link Composer package to this repository
run: |
ENCODED_NAME=$(printf '%s' "${{ steps.meta.outputs.package_name }}" | sed 's#/#%2F#g')
STATUS=$(curl -s -o /dev/null -w "%{http_code}" -u "${GITHUB_REPOSITORY_OWNER}:${{ secrets.RELEASE_TOKEN }}" -X POST \
"${GITHUB_SERVER_URL}/api/v1/packages/${GITHUB_REPOSITORY_OWNER}/composer/${ENCODED_NAME}/-/link/${GITHUB_REPOSITORY#*/}")
echo "link status: $STATUS"
if [ "$STATUS" != "201" ] && [ "$STATUS" != "400" ]; then
echo "::warning::Unexpected status linking the Composer package to this repository (HTTP $STATUS) - not fatal, release already published"
fi
Regular → Executable
+6
View File
@@ -12,6 +12,11 @@ composer.phar
/custom/ /custom/
/src/Shopware/Platform /src/Shopware/Platform
# Frontend
*.vite/
**/public/administration/js/
**/public/static/js/
# Environment # Environment
.env .env
.env.local .env.local
@@ -22,6 +27,7 @@ composer.phar
/.claude/ /.claude/
/.qwen/ /.qwen/
/.opencode/ /.opencode/
/.scratch/
# IDE # IDE
.idea/ .idea/
+1
View File
@@ -0,0 +1 @@
@CLAUDE.md
+81
View File
@@ -0,0 +1,81 @@
# Changelog
All notable changes to AeonDumpManager will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.0.7] - 2026-11-02
### Fixed
- Creating a dump failed on MariaDB when only MySQL 8's `mysqldump` was installed (`Unknown table 'COLUMN_STATISTICS'`); it now passes `--column-statistics=0` in that case.
## [0.0.6] - 2026-10-04
### Changed
- Services and routes are now configured in YAML; the plugin requires PHP `^8.2`.
- Release pipeline: the packaged `shopware-cli` zip (with prebuilt assets) is validated and used for the Gitea Release; the Composer registry gets the same content repacked root-level (Gitea requires `composer.json` at the zip root). The release is created through the Gitea API after packaging, so a failed build no longer leaves an orphan tag.
- New PR checks: `shopware-cli` validate, package build and phpunit (with a cached Shopware project and database).
- The PR version check compares against the latest published release instead of the version on `main`.
### Added
- Dedicated `aeon_dump_manager` monolog channel; dump jobs, deletions and purges are logged.
- Extension icon and `.config/shopware-extension.yml`.
### Fixed
- The packaged zip no longer contains `.gitea/` and `.config/`.
- Release steps are idempotent (existing release and asset are reused, registry 409 counts as published), so a failed release can be re-run to completion.
### Removed
- Empty plugin lifecycle overrides.
## [0.0.5] - 2026-09-21
### Fixed
- Changed namespace
## [0.0.4] - 2026-09-21
### Fixed
- Published Composer packages are now linked to this repository (previously the release workflow
published them without a repository association, so they did not appear under the repo's
Packages tab).
## [0.0.3] - 2026-09-17
### Added
- Filter the dump list by date range and sort by date or size; dates use Shopware's locale-aware
formatting.
## [0.0.2] - 2026-09-21
### Added
- Automated release pipeline: a pre-merge check enforcing a semver version bump and a matching
CHANGELOG entry on every PR into `main`, and a post-merge workflow that tags the release,
packages the plugin with `shopware-cli`, publishes a Gitea Release with the packaged zip, and
publishes the package to this Gitea instance's Composer registry.
- `main` is now a protected branch: no direct pushes, merges require the version/changelog check
to pass.
## [0.0.1] - 2026-09-15
### Added
- List, create, delete, and download gzip-compressed SQL dumps from a Settings admin page (async
creation with a polling progress bar) or via the `aeon:dump:list`, `aeon:dump:create`, and
`aeon:dump:remove` console commands (sync). Dumps are produced with `mysqldump`/`mariadb-dump`
(auto-detected, overridable via `dumpBinaryName`) and stored in the plugin's private filesystem.
- Retention controls: `maxDumps` purges the oldest dump when the limit is reached; `retantionDays`
purges expired dumps and stale job rows via a scheduled task.
- ACL-gated by `aeon_dump_manager.viewer`/`.creator`/`.deleter`, enforced client- and server-side.
+101
View File
@@ -0,0 +1,101 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this is
AeonDumpManager is a Shopware 6 plugin (`shopware-platform-plugin`) that manages database dumps for
Shopware 6 development environments. It lists, creates, and deletes gzip-compressed `mysqldump`/
`mariadb-dump` SQL dumps, both from a Settings-page admin UI (async creation with a polling progress
bar) and via `aeon:dump:{list,create,remove}` console commands (sync creation). Design decisions and
the full build spec live under `.scratch/admin-dump-manager/` and `.scratch/dump-manager-implementation-spec/`
(Wayfinder maps) — consult those before changing the dump-creation/retention/ACL behavior.
- Plugin bootstrap class: `src/AeonDumpManager.php` (extends `Shopware\Core\Framework\Plugin`) — this
is the entry point Shopware calls for install/uninstall/activate/deactivate/update lifecycle hooks.
- Plugin class name is wired via `composer.json` → `extra.shopware-plugin-class`.
- Services are registered manually in `src/Resources/config/services.yaml` (Symfony DI, YAML format,
autowiring is not configured — every new service/command/task must be added here explicitly with
its tag, e.g. `console.command` or `shopware.scheduled.task`).
- Plugin store-config UI fields (e.g. `maxDumps`, `retantionDays`) are defined in
`src/Resources/config/config.xml` and read at runtime via Shopware's SystemConfigService.
- `src/Resources/app/administration/` holds the admin UI module (Vue-based Shopware Administration
extension). The `aeon-dump-manager` module (`src/module/aeon-dump-manager/`) provides the list page
(`page/aeon-dump-manager-list`), en-GB/de-DE snippets and ACL privilege roles (`acl/`: `viewer`,
`creator`, `deleter`); `src/service/dump-api.service.ts` is the client for the dump API routes.
## Running the plugin
There is no standalone runtime — this plugin only runs inside a Shopware 6 instance. Local dev uses
`docker-compose.yml`, which mounts the repo into a `dockware/shopware` container at
`custom/plugins/AeonDumpManager`:
```bash
docker compose up -d
```
Shop/Admin/Adminer are all served on port 80/443; SSH into the container on port 22
(`SSH_USER=shopware` / `SSH_PWD=shopware`); admin-watcher and storefront-watcher proxies are exposed
on 8888/9998/9999 for `bin/build-administration.sh --watch` style workflows run inside the container.
Plugin install/activate must be done through Shopware's own tooling inside the container (e.g.
`bin/console plugin:refresh`, `bin/console plugin:install --activate AeonDumpManager`) — there is no
composer script for this in this repo.
The container's internal processes run as uid/gid 33 (`www-data`). The repo directory on the host is
group-owned by that group with setgid bit set (`chgrp -R 33` + `chmod g+s`), so both the container and
host users in group 33 can write without ownership fights.
## Tests
PHPUnit, bootstrapped through Shopware's own `TestBootstrapper` (`tests/TestBootstrap.php`), which
activates this plugin inside a real Shopware kernel for the test run (`KERNEL_CLASS` is set to
`Shopware\Core\Kernel` in `phpunit.xml`). This means tests require a working Shopware installation/DB
to bootstrap against — they are not runnable as an isolated PHP package.
In CI (`phpunit` job) the latest Shopware version allowed by the plugin's `require.shopware/core` constraint
is resolved with Composer. The prepared project (`composer create-project` + phpunit, then `system:install`
into `shopware_test` on a MariaDB 10.11 service) plus a SQL dump of the installed database are cached under
a key that contains that version, so a new Shopware release invalidates the cache. On a hit the dump is restored instead of reinstalling; the plugin
is then copied into `custom/plugins` and the bootstrapper only activates it.
```bash
vendor/bin/phpunit # full suite
vendor/bin/phpunit --filter TestClassName # single test class
vendor/bin/phpunit tests/SomeTest.php # single file
```
## Dependencies
- PHP `^8.2`, `shopware/core` `~6.6.0` (from `composer.json`); `phpunit/phpunit` `^10.0` as the only
dev dependency.
- PSR-4 autoload: `AeonDumpManager\` → `src/`, `AeonDumpManager\Tests\` → `tests/`.
## CI / release pipeline
Gitea workflows in `.gitea/`, plugin-agnostic (name/version come from `composer.json`). `shopware-cli`
runs from its official Docker image, intentionally unpinned (`latest`): a red build after a CLI release
means fix the config.
- `workflows/plugin-checks.yml` (PRs into `main`) has three jobs: `version-changelog` (the
`composer.json` version must be greater than the latest published Gitea release and have a matching
`## [x.y.z]` CHANGELOG heading), `package`
(shared composite action `actions/package`: `shopware-cli extension package`, `extension validate` on
the zip, `scripts/ci/assert-built-assets.sh`), and `phpunit`. The package job caches the tested zip
keyed by the commit's tree hash.
- `workflows/release.yml` (push to `main`, serialized; every step is idempotent so a failed run can simply be re-run): reuses the
cached zip when the tree hash matches (else packages again, always re-validates), creates the Gitea
release + tag via API with the zip as asset, publishes a root-level repack of the zip to the Composer registry
(Gitea requires `composer.json` at the zip root), then links the
package to the repo. Uses `RELEASE_TOKEN`.
- Required checks on `main` (`plugin-checks / version-changelog|package|phpunit (pull_request)`) are set
once with `scripts/protect-main.sh` (`tea api`). Build excludes/validation live in
`.config/shopware-extension.yml`. Background: `docs/spec/shopware-guideline-compliance.md`.
## Adding functionality
- New console commands go in `src/Command/`, new scheduled tasks in `src/ScheduledTask/` — both must
be registered in `src/Resources/config/services.yaml` with the appropriate tag or Shopware will not
discover them.
- Scheduled tasks need a matching handler (tagged `messenger.message_handler`) to actually run; a bare
`ScheduledTask` subclass like `ExampleTask` only defines the schedule, not the behavior.
+1
View File
@@ -0,0 +1 @@
@CLAUDE.md
Regular → Executable
+7 -7
View File
@@ -1,9 +1,9 @@
{ {
"name": "aeon/dump-manager", "name": "arthurerlich/aeon-dump-manager",
"description": "Export database dumps for Shopware 6 environments.", "description": "Export database dumps for Shopware 6 environments.",
"type": "shopware-platform-plugin", "type": "shopware-platform-plugin",
"license": "MIT", "license": "MIT",
"version": "0.0.1", "version": "0.0.7",
"keywords": [ "keywords": [
"shopware", "shopware",
"shopware6", "shopware6",
@@ -25,7 +25,7 @@
"source": "https://git.arthurerlich.de/haylan/AeonDumpManager" "source": "https://git.arthurerlich.de/haylan/AeonDumpManager"
}, },
"require": { "require": {
"php": "^8.1", "php": "^8.2",
"shopware/core": "~6.6.0" "shopware/core": "~6.6.0"
}, },
"require-dev": { "require-dev": {
@@ -35,12 +35,12 @@
"shopware-plugin-class": "AeonDumpManager\\AeonDumpManager", "shopware-plugin-class": "AeonDumpManager\\AeonDumpManager",
"copyright": "(c) by Arthur Erlich", "copyright": "(c) by Arthur Erlich",
"label": { "label": {
"de-DE": "Aeon Dump Manager", "de-DE": "Dump Manager",
"en-GB": "Aeon Dump Manager" "en-GB": "Dump Manager"
}, },
"description": { "description": {
"de-DE": "Verwaltet Datenbank-Dumps für Shopware 6 Entwicklungsumgebungen.", "de-DE": "Für Datenbank-Backups in Shopware 6 Umgebungen erzeugt Dump Manager komprimierte SQL-Dumps per Backend oder Konsole, listet und löscht sie und räumt alte Dumps automatisch auf.",
"en-GB": "Manages database dumps for Shopware 6 development environments." "en-GB": "To get a database dump for Shopware 6 environments, Dump Manager creates compressed SQL dumps from the admin or console, lists and deletes them, and purges old dumps automatically."
}, },
"manufacturerLink": { "manufacturerLink": {
"de-DE": "https://arthurerlich.de", "de-DE": "https://arthurerlich.de",
+31
View File
@@ -0,0 +1,31 @@
services:
shopware:
image: dockware/shopware:6.6.10.12
container_name: shopware
ports:
- "80:80" # Shop / Admin / Adminer / Mailcatcher (all served via path on this port)
- "443:443" # HTTPS
#- "3306:3306" # MySQL (exposed for external DB clients, e.g. TablePlus/DBeaver)
- "22:22" # SSH into the container
- "8888:8888" # Admin watcher (bin/build-administration.sh --watch)
- "9998:9998" # Storefront watcher proxy
- "9999:9999" # Storefront watcher
volumes:
- "db_volume:/var/lib/mysql"
- "shop_volume:/var/www/html"
- "./:/var/www/html/custom/plugins/AeonDumpManager"
networks:
- web
environment:
- PHP_VERSION=8.3
- XDEBUG_ENABLED=1
- SW_CURRENCY=EUR
- SSH_USER=shopware
- SSH_PWD=shopware
volumes:
db_volume:
shop_volume:
networks:
web:
+137
View File
@@ -0,0 +1,137 @@
# Research: Administration UI for AeonDumpManager (list/create/delete SQL dumps)
Target: Shopware 6.6 administration plugin development. Differences for 6.7 noted per section.
## Summary / Recommendations
- **Menu**: Register a module with `Shopware.Module.register()` and a `navigation` entry whose `parent` is an existing settings-area id (e.g. `sw-settings` or a dedicated top-level *is not allowed* for plugins — see §1). For a dev-tooling plugin like AeonDumpManager, nest under Settings rather than trying to create a first-level item; Shopware Store review explicitly rejects plugins that add first-level menu entries.
- **Module structure**: One `module/aeon-dump-manager` folder with `index.js` (routes/navigation/snippets), a single list page component, no detail/create page needed as a separate route — a create action can be a button + modal on the list page since dumps aren't Shopware entities. Bind `sw-data-grid` directly to a plain JS array (`this.dumps`) returned from your own API, not an `EntityCollection`/`repository.search()` flow.
- **Backend communication**: Write one custom PHP controller extending `AbstractController`, scoped with `#[Route(defaults: [PlatformRequest::ATTRIBUTE_ROUTE_SCOPE => [ApiRouteScope::ID]])]` (or `AdministrationRouteScope::ID`) under `/api/_action/aeon-dump-manager/...`, tagged as a service (`shopware.controller` context via `routes.xml`/`routes.php` auto-discovery). Pair it with a small JS `ApiService` subclass (`Shopware.Classes.ApiService`) registered via `Application.addServiceProvider`, injected into the component via `inject: ['aeonDumpManagerApiService']`. Do **not** rely on client-side ACL checks alone (`acl.can()` only hides UI) — do the real permission check server-side, e.g. via `AclRoleDefinition` privilege validation, since ACL in the admin can be bypassed by direct API calls.
- **TypeScript**: There is no first-class "TypeScript for admin plugins" guide; official support is limited to extending the webpack build (`build/webpack.config.js`, pre-6.7) or Vite config (`vite.config.mts`, 6.7+) to add `ts-loader`/`@babel/preset-typescript`, and core is now written largely in TS internally. Unless the project already needs TS, skip it — plain JS with the existing Vue 2-options-API-via-compat conventions is the supported default and avoids one more moving build part for a small plugin.
- **File size formatting**: Do not reimplement byte formatting — the admin core already ships `fileSize(bytes, locale)` under `Shopware.Utils.format.fileSize`. Reuse it directly in the grid column renderer.
- **6.7**: Biggest relevant changes are the Vue 2 compat-layer removal (must be genuinely Vue 3 compatible components — no `$set`/`$delete`, watch `this.$…` internal API usage), Vuex→Pinia (`Shopware.State` → `Shopware.Store`, only relevant if you add a custom store), and Webpack→Vite (only relevant if you extend the build). None of this blocks writing the module against 6.6 now, provided the components avoid deprecated Vue 2-only patterns.
---
## 1. Admin menu registration
A plugin adds an admin module (and its menu entry) via `Shopware.Module.register(moduleId, config)` called from `src/Resources/app/administration/src/module/<name>/index.js`, imported by `main.js`. The `navigation` property of the config is an array of navigation-entry objects; the documented fields are `id`, `label`, `path` (a dot-notation route id matching a `routes` entry), `icon`, `color`, `parent`, and `position` (numeric ordering). [Add Menu Entry — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/routing-navigation/add-menu-entry.html)
**Important restriction**: plugin modules cannot add entries at the first level of the main menu — a `parent` pointing at an existing menu node (Shopware supports infinite nesting) is required. The Shopware Store plugin review process explicitly rejects plugins that create their own first-level menu entry. [Add Menu Entry — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/routing-navigation/add-menu-entry.html)
**ACL-gated visibility**: a `navigation` entry (and individual `routes` entries via `meta.privilege`) can carry a `privilege` key so the menu item / route is hidden unless the logged-in admin user has that privilege — privileges are declared separately via `Shopware.Service('privileges').addPrivilegeMappingEntry(...)` in a module's `acl/index.js`. [Adding Permissions — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/permissions-error-handling/add-acl-rules.html)
**Where to hook in for a dev-tooling plugin**: Shopware's own settings modules (e.g. `sw-settings`) are the conventional parent for administrative/operational tooling that isn't a merchandising concept (products, orders, etc.). Since AeonDumpManager already exposes a store-config panel via `config.xml` (per `CLAUDE.md`), placing the module's navigation entry as a child of the existing settings area is the natural, non-first-level location and matches the plugin's job (dev/ops tooling, not a customer-facing catalog feature).
**6.7 differences**: The `Module.register` / navigation API itself is not called out as changed in the 6.7 upgrade materials found. The changes that *do* land in 6.7 and affect any admin module (menu module included) are:
- Removal of the Vue 2 compatibility build — plugin components must be genuinely Vue-3-compatible (no `$set`/`$delete`, check `this.$…` internal Vue API usage, `sw-field` replaced by its successor components). [Vue 3 Upgrade guide — developer.shopware.com](https://developer.shopware.com/docs/guides/upgrades-migrations/administration/vue3.html), [Removing Vue Migration Build roadmap — developer.shopware.com](https://developer.shopware.com/docs/guides/upgrades-migrations/administration/vue-migration-build.html)
- Vuex → Pinia: any plugin-registered Vuex store must move from `Shopware.State` to `Shopware.Store` (not applicable here unless AeonDumpManager adds its own store, which is not necessary for a dump list). [Vue 3 Upgrade guide — developer.shopware.com](https://developer.shopware.com/docs/guides/upgrades-migrations/administration/vue3.html)
- Webpack → Vite for the admin build (see §4).
No meteor-admin-sdk vs. core-plugin distinction is relevant here: `meteor-admin-sdk` (the "app extension SDK", formerly `admin-extension-sdk`) is the mechanism for **Shopware Apps** (no PHP backend, communicate over `postMessage`/iframe), not for a classic PHP+JS **plugin** like AeonDumpManager, which uses the core plugin administration extension mechanism documented above. This plugin is a PHP plugin (`shopware-platform-plugin`, confirmed by `CLAUDE.md`), so the core `Shopware.Module.register` path is the correct one, not the SDK.
## 2. Building the admin UI module structure
Conventional directory layout under `src/Resources/app/administration/src/`:
```
main.js # imports the module: import './module/aeon-dump-manager';
module/aeon-dump-manager/
index.js # Shopware.Module.register(...) — routes, navigation, snippets
acl/index.js # addPrivilegeMappingEntry (optional but recommended)
snippet/
en-GB.json
de-DE.json
page/
aeon-dump-manager-list/
index.js # Shopware.Component.register(...)
aeon-dump-manager-list.html.twig
```
`index.js` registers routes (e.g. `list: { component: 'aeon-dump-manager-list', path: 'list' }`), the `navigation` array (§1), and `snippets` per locale. [Add Custom Module — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/module-component-management/add-custom-module.html), [Add Custom Route — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/routing-navigation/add-custom-route.html)
**List rendering — plain array, not `EntityCollection`**: `sw-data-grid` is documented and used with a plain array of plain objects assigned to component `data()`, not necessarily an entity repository result:
```html
<sw-data-grid :data-source="dataSource" :columns="columns"></sw-data-grid>
```
```js
data() {
return {
dataSource: [ { id: 'uuid1', company: 'Wordify', name: 'Portia Jobson' }, ... ],
columns: [ { property: 'name', label: 'Name' }, { property: 'company', label: 'Company' } ]
};
}
```
[Using the Data Grid Component — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/data-handling-processing/using-the-data-grid-component.html)
This is exactly the right fit for AeonDumpManager: dump files are filesystem entries, not DAL entities, so the list page's `data()` should hold the array returned by your custom API (§3) — each row `{ id/filename, createdAt, name, sizeBytes }` — with a `columns` config of `name`, a datetime column (format via existing Shopware date filter/util), and a size column whose `label` renders `Shopware.Utils.format.fileSize(row.sizeBytes)` (§5). Do not build an `EntityCollection` or wire a `repositoryFactory` for this list — that machinery is for DAL entities and would be pure overhead here.
**Create/delete flow**: a "Create dump" `sw-button` triggers your API service's create call and reloads the list; per-row delete uses a row action (`sw-context-button`/action column) that opens a confirmation dialog before calling delete. Shopware's own standard confirmation component is `sw-confirm-modal` (added in 6.3.5.0 as the standard confirm-modal component for exactly this kind of "are you sure you want to delete" flow) — reuse it rather than hand-rolling a `sw-modal` yes/no dialog. [changelog: added-sw-confirm-modal.md — github.com/shopware/shopware](https://github.com/shopware/shopware/blob/trunk/changelog/release-6-3-5-0/2021-01-06-added-sw-confirm-modal.md), [sw-confirm-modal — component-library.shopware.com](https://component-library.shopware.com/components/sw-confirm-modal)
## 3. Frontend-to-backend communication
**JS side**: define a custom API service class extending `Shopware.Classes.ApiService`, register it through `Shopware.Application.addServiceProvider('aeonDumpManagerApiService', (container) => { const initContainer = Application.getContainer('init'); return new AeonDumpManagerApiService(initContainer.httpClient, container.loginService); })`, and inject it into components with `inject: ['aeonDumpManagerApiService']` → available as `this.aeonDumpManagerApiService`. The base class supplies `getBasicHeaders()` (auth token handling) and `ApiService.handleResponse()` for uniform error handling; a GET/POST/DELETE call is `this.httpClient.get(route, { headers: this.getBasicHeaders() })` etc. [Adding Services — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/add-custom-service.html), [Making API Requests — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/services-utilities/making-api-requests.html)
**PHP side**: create a controller extending `AbstractController`, scoped to the admin/API domain via the class-level attribute
```php
#[Route(defaults: [PlatformRequest::ATTRIBUTE_ROUTE_SCOPE => [ApiRouteScope::ID]])]
class DumpController extends AbstractController
{
#[Route(
path: '/api/_action/aeon-dump-manager/dumps',
name: 'api.action.aeon_dump_manager.dumps.list',
methods: ['GET']
)]
public function list(Context $context): JsonResponse { ... }
}
```
This mirrors the core `ApiController`'s own pattern (`#[Route(defaults: [PlatformRequest::ATTRIBUTE_ROUTE_SCOPE => [ApiRouteScope::ID]])]` at class level, with `/api/_action/...` action routes at method level, e.g. its `clone` action at `/api/_action/clone/{entity}/{id}`). [ApiController.php — github.com/shopware/core (trunk)](https://github.com/shopware/core/blob/trunk/Framework/Api/Controller/ApiController.php); Administration-specific controllers use `AdministrationRouteScope::ID` from `Shopware\Administration\Framework\Routing\AdministrationRouteScope` instead when the endpoint is administration-only rather than general Admin API. [AdministrationController.php — github.com/shopware/administration (trunk)](https://github.com/shopware/administration/blob/trunk/Controller/AdministrationController.php)
Controller discovery uses the plugin's `src/Resources/config/routes.php` (or `routes.xml`) importing `../../Controller/*Controller.php` via the `attribute` type loader — the same auto-discovery mechanism documented for storefront controllers, generalized to any controller directory. [Add Custom Controller — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-custom-controller.html)
**ACL/authorization**: All admin and API routes are authentication-protected by default (bearer token from the admin's own OAuth session, attached automatically by `getBasicHeaders()`/`loginService` on the JS side — no separate manual OAuth dance needed in the component code). [UPGRADE-6.1.md — github.com/shopware/shopware](https://github.com/shopware/shopware/blob/trunk/UPGRADE-6.1.md) Client-side privilege checks (`this.acl.can('aeon_dump_manager.viewer')`, `v-if="acl.can(...)"`) only toggle UI visibility and are documented as bypassable via direct API calls — the actual authorization must be enforced in the controller itself, e.g. by validating against `AclRoleDefinition` privilege constants the way `ApiController::clone()` does (`$this->validateAclPermissions($context, $definition, AclRoleDefinition::PRIVILEGE_CREATE)`, throwing `ApiException::missingPrivileges()` on failure), or via the `#[Acl(...)]` attribute mechanism that superseded the deprecated `@Acl` annotation for controller-level privilege gating. [Adding Permissions — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/permissions-error-handling/add-acl-rules.html), [ApiController.php — github.com/shopware/core (trunk)](https://github.com/shopware/core/blob/trunk/Framework/Api/Controller/ApiController.php), [ADR: controller-configuration-route-defaults — developer.shopware.com](https://developer.shopware.com/docs/resources/references/adr/2022-02-09-controller-configuration-route-defaults.html)
For AeonDumpManager, declare a plugin-specific privilege set (e.g. `aeon_dump_manager.viewer` / `.creator` / `.deleter`) via `acl/index.js` (`addPrivilegeMappingEntry`), gate the menu/routes with it client-side for UX, and re-check an equivalent permission (or at minimum require an authenticated admin session, which is already default) server-side before actually running a `mysqldump`/file-delete operation — these are filesystem/process-level actions, so being defensive here matters more than for a typical read-only entity list.
*Gap note*: the official docs found do not show a first-party doc page titled specifically "add custom admin API route" with a full worked PHP example (the closest, `add-custom-route.html`, only covers the **Vue Router** side, i.e. `routes:` in `Module.register`, not the PHP controller) — the PHP-side pattern above is instead verified directly against the shipped `ApiController`/`AdministrationController` source in `shopware/core` and `shopware/administration`, which is authoritative but means there's no single canonical doc page combining both halves end-to-end for a plugin.
## 4. TypeScript setup for Shopware 6 administration
There is no dedicated "TypeScript for administration plugins" guide among the fetched official pages. What exists officially:
- **Build extension mechanism (6.6 and earlier)**: a plugin can provide `src/Resources/app/administration/build/webpack.config.js` exporting a function that returns webpack config overrides — this is the documented, supported extension point (`Extending Webpack`). [Extending Webpack — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/extending-webpack.html) That page itself contains **no TypeScript-specific guidance** (no `.ts`/`.tsx`, `ts-loader`, or `tsconfig` mention) — adding `ts-loader` or `@babel/preset-typescript` there is a community pattern layered on top of a documented extension point, not something the official page walks through.
- **6.7: Webpack → Vite**. Per the roadmap doc, plugins are only affected if they currently ship a custom `webpack.config.js`; those must migrate to a `vite.config.mts` file (note the `.mts` extension — TypeScript by convention for the config file itself) under `.../administration/src/`, and delete the old webpack config/dependencies. [Future Development Roadmap: Changing from Webpack to Vite — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/system-updates/vite.html)
- Shopware's own administration source has increasingly moved to `.ts`/`.vue`+TS internally (e.g. core factory files like `async-component.factory.ts` in `shopware/shopware` trunk), i.e. the *core team's own code* is TypeScript, but this is not the same as an officially documented, supported path for **plugin** authors to write their own module in TypeScript out of the box.
**Recommendation for AeonDumpManager**: skip TypeScript. Per the ponytail ladder, there's no existing TS need in this repo (PHP `^8.1` project per `CLAUDE.md`, no existing frontend TS tooling), and the admin plugin surface here is small (one list page, one service). Adding a custom `webpack.config.js`/`vite.config.mts` + `ts-loader`/tsconfig just to type a handful of small Vue components is speculative infrastructure for a plugin whose entire admin footprint is one grid and one API service; plain JS following the documented module/service conventions is both fully supported and the shorter path. Revisit only if the plugin's admin surface grows substantially or the team adopts TS project-wide.
## 5. File size formatting
Shopware's administration core already ships a byte-formatting helper — do not reimplement it. It's documented in the Utils reference (`Shopware.Utils.format.fileSize`, described as "Formats a number of bytes to a string with a unit") [Utils Reference — developer.shopware.com](https://developer.shopware.com/docs/resources/references/administration-reference/utils.html), and its exact implementation in the `shopware/shopware` monorepo (Administration bundle) is:
```ts
// src/Administration/Resources/app/administration/src/core/service/utils/format.utils.ts (shopware/shopware, trunk)
export function fileSize(bytes: number, locale = 'de-DE'): string {
const denominator = 1024;
const units = ['B', 'KB', 'MB', 'GB'];
let result = Number.parseInt(String(bytes), 10);
let i = 0;
for (; i < units.length; i += 1) {
const currentResult = result / denominator;
if (currentResult < 0.9) break;
result = currentResult;
}
return `${result.toFixed(2).toLocaleString(locale)}${units[i]}`;
}
```
[format.utils.ts — github.com/shopware/shopware (trunk)](https://github.com/shopware/shopware/blob/trunk/src/Administration/Resources/app/administration/src/core/service/utils/format.utils.ts)
Usage in a plugin component: `Shopware.Utils.format.fileSize(row.sizeBytes)` (accessed via the global `Shopware.Utils` object per the "Using utility functions" guide). [Using utility functions — developer.shopware.com](https://developer.shopware.com/docs/guides/plugins/plugins/administration/using-utils.html) This directly satisfies the "MB/GB human-readable size column" requirement with zero custom code — pass the dump file's byte size straight through it in the `sw-data-grid` column renderer/slot.
Note it only goes up to `GB` (no `TB` step) and defaults to `de-DE` locale formatting unless a locale is passed — pass the admin's current locale (`Shopware.State.get('session').currentLocale` in 6.6, or its `Shopware.Store` equivalent post-Pinia-migration in 6.7) if locale-correct number formatting matters, otherwise the default is fine for dump files (unlikely to exceed a few GB).
+167
View File
@@ -0,0 +1,167 @@
# Research: shopware-cli changelog handling and the PHP floor for a Shopware 6.6 plugin
Sources are primary only: `shopware/shopware-cli` source (main branch, fetched 2026-10-04),
`shopware/docs` (the repo behind developer.shopware.com, main), and `shopware/shopware` tags.
Paths below are relative to those repos. Refs are branch heads or tags as noted; no commit SHAs
were pinned.
## Summary
- **`extension package --release` does not parse CHANGELOG.md.** It only generates one, from git commits, and only if `changelog.enabled: true` is set in `.config/shopware-extension.yml`. Our pipeline does not pass `--release`.
- **Parsing happens elsewhere:** in `account producer extension upload` (Store push) and in `extension get-changelog`. The parser treats every line starting with `#` as a version key.
- **Our Keep-a-Changelog file is not compatible with that parser.** The key becomes `# [0.1.0] - 2026-10-03`, never `0.1.0`, so the Store upload would fail with "english changelog is missing". This only matters if we later use `account producer extension upload`; today we publish to Gitea and a Composer registry.
- **Minimal fix if we ever upload to the Store:** add `CHANGELOG_en-GB.md` with `# x.y.z` headings and flat bullets, with no `###` sub-headings. Keep `CHANGELOG.md` for humans; the localized file wins for `en-GB`.
- **PHP:** Shopware 6.6.x requires `~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0` (6.6.0.0 was `~8.2.0 || ~8.3.0`). Our `php: ^8.2` is consistent but broader than core; it is harmless because `shopware/core ~6.6.0` already pins the effective range.
- **Recommendation:** keep `^8.2` or use `>=8.2`. Do not copy core's tilde list. Shopware's own docs skeleton declares no `php` at all, only `shopware/core`.
## Q1. Changelog handling
### 1.1 What the parser does (verified in source)
File: `internal/extension/changelog.go` (shopware-cli, main).
File discovery and locale:
```go
files, err := filepath.Glob(path + "/CHANGELOG*.md")
...
language := strings.Trim(strings.ReplaceAll(strings.ReplaceAll(filepath.Base(file), "CHANGELOG", ""), ".md", ""), "_")
if len(language) == 0 { language = "en-GB" }
```
- `CHANGELOG.md` maps to `en-GB`.
- `CHANGELOG_en-GB.md` maps to `en-GB`, and `CHANGELOG_de-DE.md` maps to `de-DE`.
- If both `CHANGELOG.md` and `CHANGELOG_en-GB.md` exist, both land in the same map slot. `filepath.Glob` returns lexically sorted names and `.` sorts before `_`, so `CHANGELOG_en-GB.md` is processed last and overwrites. This ordering is inferred from Go's documented sorted-directory behaviour; I did not run it.
Section splitting (`parseMarkdownChangelog`):
```go
for _, line := range strings.Split(content, "\n") {
if strings.HasPrefix(line, "#") {
...
currentVersion = strings.Trim(strings.TrimPrefix(line, "#"), " ")
```
- Every line that starts with `#`, at any heading depth, starts a new "version" section.
- The key is the line minus one leading `#`, with spaces trimmed. Only a single `#` is removed.
- The body is converted to HTML with goldmark via `internal/markdown`. Headings inside bodies are rendered as `<span class="hN">`.
- Upstream's own tests use this exact shape: `"# 1.0.0\n\n- Test\n- Test2\n# 2.0.0\n- Test3\n- Test4\n"` (`internal/extension/changelog_test.go`).
Version lookup (`parseExtensionMarkdownChangelog`):
- The key looked up is `ext.GetVersion().String()`, which is the plain version from `composer.json`, for example `0.1.0`.
- `changelogs["en-GB"][version]` must exist, or it returns an error ("english changelog is missing").
- `de-DE` is optional and falls back to the English file. If a `de-DE` file exists but lacks the version, it errors.
- The docs agree: "The zip file contains a `CHANGELOG*.md` file with a changelog entry for the new version. Having a German changelog is optional." (`products/tools/cli/shopware-account-commands/releasing-extension-to-shopware-store.md`).
### 1.2 Where it is used
`GetChangelog()` is called in only two non-test places:
- `internal/account-api/producer_store_upload.go`: `account producer extension upload` sends `de_DE` and `en_GB` texts as the Store changelog.
- `cmd/extension/extension_changelog.go`: `extension get-changelog`.
Not called from `cmd/extension/extension_package.go`, nor from validation: no `changelog` reference was found under `internal/validation`.
### 1.3 What `--release` does
`cmd/extension/extension_package.go`:
```go
extensionPackageCmd.Flags().BoolVar(&extensionReleaseMode, "release", false, "Prepare a release build: generate the changelog if enabled and, for apps, remove the secret from manifest.xml")
```
`internal/extension/zip.go`, `PrepareExtensionForRelease`:
```go
if ext.GetExtensionConfig().Changelog.Enabled {
...
changelogFile := fmt.Sprintf("# %s\n%s", v.String(), content)
os.WriteFile(path.Join(extensionRoot, "CHANGELOG_en-GB.md"), ...)
}
if ext.GetType() == "plugin" { return nil }
// apps only: remove setup/secret from manifest.xml
```
- **Added:** a generated `CHANGELOG_en-GB.md`, containing `# <version>` plus one bullet per git commit between the last tag and the current commit (template `internal/changelog/changelog.tpl`). It only happens if `changelog.enabled: true`. The default is false (`internal/changelog/changelog.go`, `Enabled bool`).
- **Stripped:** the app secret in `manifest.xml`. This does not apply to plugins, which return early.
- **Not stripped or rewritten:** an existing `CHANGELOG.md` is left untouched. When enabled, the generated file overwrites any existing `CHANGELOG_en-GB.md`.
- This confirms `# x.y.z` is the format the tool itself writes.
- Docs on release mode and `changelog.enabled`: `products/tools/cli/extension-commands/build.md`, "Release mode" section.
### 1.4 Our repo
- `.gitea/actions/package/action.yml:29` runs `shopware-cli extension package . --output-directory .build --filename ... --git-commit "$GITHUB_SHA"`. There is no `--release`, and no `changelog:` key was found in `.config` or `.gitea`.
- The release notes come from our own awk in `.gitea/workflows/release.yml`, which matches `## [x.y.z]`. That is independent of shopware-cli.
- `CHANGELOG.md` uses `## [0.1.0] - 2026-10-03` and `### Added/Changed/...`.
### 1.5 Compatibility verdict
Walking `CHANGELOG.md` through `parseMarkdownChangelog` by hand (not executed):
- `## [0.1.0] - 2026-10-03` gives key `# [0.1.0] - 2026-10-03`, which never equals `0.1.0`.
- Each `### Added` and similar heading becomes its own bogus "version", so the entries under it are split off.
Result: **incompatible.** `account producer extension upload` and `extension get-changelog` would fail with "english changelog is missing". `extension package`, with or without `--release`, would not fail, because it does not call the parser. `extension validate` does not parse it either, as far as I could find.
Minimal change, only needed if we adopt Store upload:
```markdown
# 0.1.0
- Services and routes are now configured in YAML; the plugin requires PHP `^8.2`.
- Release pipeline: ...
```
- Put it in `CHANGELOG_en-GB.md` at the plugin root, with one `# <exact composer version>` section per release and flat bullets. Prefix bullets with Added/Changed/Fixed if the categories matter.
- No `###` sub-headings, and no brackets or dates in the heading.
- `CHANGELOG_de-DE.md` is optional.
- The alternative is to enable `changelog.enabled: true` plus `--release` and let the CLI generate it from commits. That would not use our hand-written entries.
- The packaged zip must contain the file. I did not verify whether `.config/shopware-extension.yml` pack excludes would remove it.
Not verified: the Store's own server-side handling of the changelog HTML. The CLI source only shows what is sent (`de_DE`/`en_GB` text), not what the Store renders. The Store API and backend are not public.
## Q2. PHP constraint
### 2.1 What Shopware 6.6 requires
`require.php` in `shopware/shopware` `src/Core/composer.json` and the root `composer.json`:
| Ref | `require.php` |
|---|---|
| `v6.6.0.0` | `"php": "~8.2.0 \|\| ~8.3.0"` |
| `v6.6.10.28` (latest 6.6 tag seen) | `"php": "~8.2.0 \|\| ~8.3.0 \|\| ~8.4.0 \|\| ~8.5.0"` |
- The `v6.6.10.28` root `composer.json` has the same line as core.
- A fetch of the `6.6.x` branch-head `composer.json` returned no usable content, so only the two tags above are verified.
- Official docs, `guides/hosting/index.md` ("Recommended stack and supported versions"): PHP minimum `8.2+`, recommended `8.4`.
- `guides/development/dev-environment.md`: "PHP Version | `8.2`, `8.3`, `8.4`, `8.5`".
- Fetching the rendered developer.shopware.com requirements page returned no PHP row. It defers to the hosting guide, which is the source above.
- The repo's own `CLAUDE.md` says PHP `^8.1`. That is stale for 6.6, since core requires 8.2+. It is outside this task's scope.
### 2.2 Is `php: ^8.2` right?
`composer.json` today:
```json
"require": { "php": "^8.2", "shopware/core": "~6.6.0" }
```
- `^8.2` means `>=8.2.0 <9.0.0`. It is consistent with core's floor.
- It is wider than core's ceiling (`<8.6`). The plugin's PHP range is the intersection of its own constraint and core's. Because `shopware/core ~6.6.0` is also required, Composer resolves to core's tilde list anyway. The plugin constraint adds no extra restriction in practice.
- Copying core's `~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0` would only make sense if the plugin itself breaks on a specific PHP minor. That would also force a release every time Shopware adds a PHP minor.
- Practical conclusion: `^8.2` is fine and not too strict. `>=8.2` behaves the same in practice. The only real argument for changing it is wanting the plugin's PHP floor to stay visible in its own metadata, which `^8.2` already does.
### 2.3 What Shopware's skeletons recommend
- `guides/plugins/plugins/creating-plugins.md` (docs repo): the example plugin `composer.json` has only `"require": { "shopware/core": "~6.7.0" }`. There is no `php` key, and "Depending on other plugins" repeats the same shape.
- shopware-cli's scaffolding (`internal/extension/create.go`) does not set a `php` constraint; the only `"php"` hit in that package is a test fixture, `internal/extension/root_test.go:233`, with `">=8.1"`.
- So the official guidance is to constrain `shopware/core` and leave PHP to core. A plugin `php` constraint is optional. If you want one, mirroring the supported floor (`>=8.2` or `^8.2`) is reasonable.
- I did not find a `SwagPluginSkeleton` repo (fetching `shopware/SwagPluginSkeleton` returned 404).
## Could not verify
- That the Store's server-side processing matches what the CLI sends. The Store backend is not public.
- That `.config/shopware-extension.yml` pack excludes would keep or remove a `CHANGELOG_en-GB.md` in the zip.
- The exact ordering behaviour of `filepath.Glob` for the two `en-GB` files was inferred from Go's documented sorted results, not run.
- No source evidence of whether the Store accepts HTML headings; the CLI renders headings as `<span class="hN">` per a comment in `internal/markdown`.
+178
View File
@@ -0,0 +1,178 @@
# Research: Admin-configurable dump binary path — is it an attack surface?
Target: `src/Service/DumpBinaryLocator.php`'s `dumpBinaryPath` config field and how it feeds
`src/Service/DumpService.php::buildProcess()`.
## Summary / Recommendation
- **Not a shell-injection vector.** `Process` built from an array (`new Process([$binary, ...])`)
never goes through a shell — PHP's `proc_open()` execs the array directly, so whatever string sits
in `$binary` is passed straight to `exec()` as the program path. There's no shell metacharacter
parsing to exploit via that string's *content* (§1).
- **The real concern is authorization scope, not injection**: `dumpBinaryPath` is whatever
`SystemConfigService::getString()` returns, gated only by Shopware's `system_config:read`/`:update`
ACL privilege — a privilege that can be granted independently of shell/SSH access to the box. A
role with system-config write access but *no* shell access can currently point this field at any
executable already reachable on disk and have the plugin run it as `www-data`. That's a real,
if narrow, privilege-escalation surface for this one specific plugin — not a "trusts itself" non-issue,
because system-config-write and filesystem/shell access are not the same trust tier in Shopware's ACL
model (§1).
- **Recommendation for this plugin**: drop `dumpBinaryPath` (arbitrary absolute path) in favor of a
`dumpBinaryName` override, resolved through `ExecutableFinder::find($name)` exactly like the
auto-detected default — never returned as a raw path straight from config. This closes the
arbitrary-path surface (an admin can only ever get a `PATH`-resolved binary, never point at
`/etc/shadow`-adjacent binaries or an arbitrarily uploaded file) while still covering the one
legitimate reason to override at all: a distro/environment that names the client something
nonstandard. Given dockware ships `mysqldump` on `PATH` already (confirmed in the prior research doc,
`.scratch/admin-dump-manager/issues/01-detect-dump-binary.md` §3), the override will sit unused in
the common case — which is fine, it's a two-line fallback, not new infrastructure (§2, §3).
- An env-var override was considered and rejected as the *primary* mechanism for this plugin — it's
the right shape for ops-owned infra config, but this plugin already has a config-field UI and
`SystemConfigService` wired in for `maxDumps`/`retantionDays`; adding a second override channel
(env var) alongside the DB-stored one is more moving parts than the problem needs (§2, §3).
## 1. Is there a real security concern?
`DumpService::buildProcess()` builds the command as an array:
```php
$command = [$binary, '--single-transaction', '--quick', '-h', ..., '-u', ..., $dbname];
$process = new Process($command, null, ['MYSQL_PWD' => $password]);
```
Symfony's own docs are explicit that array form is the safe form and *why*:
> "Using an array of arguments is the recommended way to define commands. This saves you from any
> escaping and allows sending signals seamlessly." — and contrasts it with `Process::fromShellCommandline()`,
> where "it becomes your responsibility to deal with escaping and portability."
> [Symfony Process component docs](https://symfony.com/doc/current/components/process.html)
Mechanically: `Process` (array constructor) hands the array straight to PHP's `proc_open()`, which —
given an array `command` argument — execs the binary directly (no `/bin/sh -c` wrapping), per PHP's
own `proc_open()` behavior for array-form commands (bypasses the shell entirely on Linux since PHP
7.4). So `$binary`'s *string content* can't be used to inject additional shell commands (no `;`, `` ` ``,
`$()`, pipes, etc. get interpreted) — the entire "shell injection via a crafted path string" concern
the user was worried about does not apply to this code as written. This holds **regardless of whether
`$binary` comes from `ExecutableFinder::find()` or directly from `SystemConfigService::getString()`** —
both are just strings landing in the same array slot.
**So what is the actual concern?** Not injection — authorization scope. `dumpBinaryPath` is read via:
```php
$configuredPath = $this->systemConfigService->getString('AeonDumpManager.config.dumpBinaryPath');
if ($configuredPath !== '') {
return $configuredPath;
}
```
This value is *whatever an admin with write access to this plugin's store-config typed*, used
**verbatim** as the program to exec — no `is_executable()` check, no restriction to a known directory,
no validation at all beyond non-empty. Setting it, in Shopware's ACL model, requires the
`system_config:read`/`system_config:update` privilege (or a role with `administration` access broadly).
That privilege is not the same tier as "has a shell on the container" — Shopware routinely grants
narrower admin roles (e.g. a merchandising-ops role scoped to a handful of modules including this
plugin's settings card) without granting SSH/exec access to the underlying host. For *this specific
field*, anyone who can write plugin config can make the plugin exec an arbitrary path on disk as
`www-data` — e.g. pointing it at any already-present script/binary, or (in a shared-hosting-style setup)
a path they can write to via some unrelated upload feature. That's a real, if narrow and
low-severity-in-practice (dev-tooling plugin, dockware-only target per `CLAUDE.md`), escalation: it
turns "can edit this plugin's config" into "can execute an arbitrary path as the PHP process user,"
which is a strictly larger capability than the plugin should need to grant. It is not an
*unauthenticated-attacker* vector — Shopware's admin panel is authenticated and this requires a
specific privilege — but "only a privileged admin can trigger it" doesn't make it a non-issue when the
privilege in question (system-config write) is deliberately a narrower grant than shell access in
Shopware's own permission model.
## 2. Alternatives, evaluated
### a. Drop the field entirely, `ExecutableFinder::find()` only, fail loudly
Simplest option. `ExecutableFinder::find($name)` (confirmed against `symfony/process` source,
`ExecutableFinder.php`, current branch) searches, in order:
1. Directories from the `PATH` env var (`getenv('PATH')`, or `Path` on Windows), merged with any
`$extraDirs` argument.
2. For each directory, `is_file($dir/$name$suffix) && is_executable(...)` (suffix loop is a no-op on
Linux; Windows-only `PATHEXT` extensions).
3. As a last resort on non-Windows, shells out to `command -v -- $name` (via `escapeshellarg()`) —
this is the *only* place `ExecutableFinder` itself touches a shell, and it shell-escapes the binary
*name* being searched for, not a path being executed.
[`ExecutableFinder.php` — symfony/process, GitHub](https://github.com/symfony/process/blob/7.1/ExecutableFinder.php)
Pro: zero config-surface, nothing to misconfigure. Con: on the (rare, per the linked prior research)
case where `mysqldump`/`mariadb-dump` genuinely isn't on `PATH` for `www-data`, there's no way to
recover without an env var or code change — for a plugin whose whole job is producing dumps, a hard
dependency on `PATH` composition an admin can't influence from the plugin's own UI is a mildly awkward
dead end.
### b. Binary *name* override (`dumpBinaryName`), still resolved via `ExecutableFinder::find()`
```php
$configuredName = $this->systemConfigService->getString('AeonDumpManager.config.dumpBinaryName');
$binaryNames = $configuredName !== ''
? [$configuredName]
: ($this->isMariaDb() ? ['mariadb-dump', 'mysqldump'] : ['mysqldump']);
foreach ($binaryNames as $binaryName) {
$path = $this->executableFinder->find($binaryName);
if ($path !== null) {
return $path;
}
}
```
This is a ~3-line diff from the current code — same shape, same loop, just the value coming out of
config is *always* passed through `find()` rather than ever being returned directly. Every path
`buildProcess()` can end up executing is a `PATH`-resolved, `is_executable()`-checked file — an admin
can redirect *which name* gets looked up (covers a renamed/nonstandard binary on an unusual
distro/environment) but can never point the plugin at an arbitrary filesystem path outside `PATH`.
This directly closes the gap in §1 while preserving the one legitimate override use case the original
field existed for.
### c. Environment variable override (`getenv('AEON_DUMP_BINARY_PATH')` or similar)
Moves the override from "whoever has Shopware admin-config write access" to "whoever controls the
container/deployment env" (ops/devops, via `docker-compose.yml`, `.env`, or the container's process
environment) — a meaningfully different, generally higher, trust tier, and consistent with how
`docker-compose.yml` already configures this repo's dev container (`SSH_USER`/`SSH_PWD` env vars per
`CLAUDE.md`). This is a legitimate pattern in general. For *this* plugin specifically it's more
machinery than the problem justifies: it adds a second config source (env var) next to the existing
`SystemConfigService`-backed admin UI field, for a value that (per §3) essentially never needs
overriding in the actual target environment (dockware). It's the right tool if this were, say, a
plugin deployed across heterogeneous customer infrastructure where ops teams routinely differ from
Shopware-admin teams — not proportionate for a project-local dev-tooling plugin with one target
container image.
## 3. Recommendation for this plugin
Use **(b)** — replace `dumpBinaryPath` (text, absolute path) with `dumpBinaryName` (text, binary name,
default empty → falls back to the existing MariaDB/MySQL name-detection list) in
`src/Resources/config/config.xml`, and change `DumpBinaryLocator::locate()` to prepend the configured
name (if any) to the existing `$binaryNames` loop instead of short-circuiting with a raw path. This is
sized right for a dev-tooling plugin that per the prior research (`.scratch/.../01-detect-dump-binary.md`
§3) targets dockware, where `mysqldump` is already confirmed present on `PATH` — the override becomes
a rarely-touched escape hatch rather than the primary mechanism, and it removes the one place in this
plugin where admin-supplied config was executed as a program path with no validation. Skip (c)/env-var:
it solves a deployment-heterogeneity problem this single-container plugin doesn't have, and would be a
second override mechanism doing the same job as the config field, for no concrete gain here. Skip
(a)/no-override-at-all: it's the smallest diff but removes a genuine, if narrow, recovery path for a
`PATH`-less edge case at effectively zero cost to keep (b) instead — (b) is one loop-entry away from (a)
and already sits inside the existing `foreach ($binaryNames as $binaryName)` structure in
`DumpBinaryLocator::locate()`.
No code changes were made as part of this research task — see
`src/Service/DumpBinaryLocator.php`, `src/Service/DumpService.php::buildProcess()`, and
`src/Resources/config/config.xml` for the current state to build (b) against.
## Sources
- [Symfony Process component docs — command arrays vs `fromShellCommandline()`](https://symfony.com/doc/current/components/process.html)
- [`ExecutableFinder.php` — symfony/process, GitHub (7.1 branch)](https://github.com/symfony/process/blob/7.1/ExecutableFinder.php)
- PHP manual, `proc_open()` — array-form `command` execs directly without a shell wrapper (documented
behavior since PHP 7.4 for the array-command form on non-Windows).
- `src/Service/DumpBinaryLocator.php`, `src/Service/DumpService.php` (this repo, current state).
- `.scratch/admin-dump-manager/issues/01-detect-dump-binary.md` (prior locked research: dockware ships
`mysqldump` on `PATH`, MariaDB binary-naming history, `ExecutableFinder` recommendation).
- `.scratch/dump-manager-implementation-spec/spec.md` §0, §2.2 (locked design context for the
`dumpBinaryPath` field and `DumpBinaryLocator` shape being reconsidered here).
@@ -0,0 +1,72 @@
# Spec: Shopware plugin guideline compliance (build/release pipeline)
Outcome of the Wayfinder map `.scratch/shopware-guideline-compliance/` (tickets 01-05; research evidence
on branches `research/shopware-guideline-checklist`, `research/shopware-cli-ci-behaviour`,
`research/gitea-28-pipeline-standards`). Target: **Store-ready** artifacts, published to Gitea only
(Gitea Release + Composer registry). Uploading to the Shopware Store is out of scope.
## 1. Principles
- Workflows are **plugin-agnostic**: no plugin name, package name, owner, repo or host is hard-coded;
all derive from `composer.json` and the `gitea` context. The same files must work unchanged for a
second plugin and be extractable to Gitea's shared-workflow repository later.
- One artifact: the `shopware-cli extension package` zip (prebuilt admin/storefront JS) is the Gitea
Release asset; the Composer registry gets the same content repacked root-level (the registry needs
`composer.json` at the zip root, see section 4).
- `shopware-cli` is intentionally **unpinned** (`latest`). Known tradeoff: a CLI release can turn PRs
red without a repo change; treat that as a signal to fix config.
- `RELEASE_TOKEN` is the only token (release, assets, registry publish, link). Workflows still declare
`permissions:`.
## 2. Plugin changes
| # | Change |
|---|--------|
| P1 | Commit `src/Resources/config/plugin.png` (256x256). Do not ship `plugin-transparent.png`. |
| P2 | Logging: monolog channel `aeon_dump_manager` (`Resources/config/packages/monolog.yaml`, `build()` in the plugin class loading `packages/*.yaml`); inject `monolog.logger.aeon_dump_manager` into `PurgeDumpsTaskHandler`, `DumpService`, `CreateDumpHandler`; log dump job start/finish/failure. |
| P3 | Migrate `services.xml` -> `services.yaml` and `routes.php` -> `routes.yaml`. No validation ignore for this. Update the "XML services" rule in `CLAUDE.md`. |
| P4 | `composer.json`: `php` -> `^8.2`. Verify Shopware 6.6's own PHP requirement. |
| P5 | Delete the empty lifecycle overrides in `AeonDumpManager`; keep `uninstall`. |
| P6 | `.config/shopware-extension.yml` for build excludes and validation settings (add ignores only for real, accepted findings). |
| P7 | Keep Keep-a-Changelog `CHANGELOG.md`; verify with a local `shopware-cli extension package --release` how the changelog is read. |
## 3. Pipeline
### PR workflows
Jobs (all required checks on `main`):
`plugin-checks.yml` (the former `pr-version-check.yml` was deleted; `version-changelog` is now a job in it):
0. `version-changelog` - version bump vs `main` and matching CHANGELOG heading.
1. `package` - `extension package` with `--git-commit "$GITHUB_SHA"`, `extension validate` on the resulting zip (hard gate; replaces a separate directory validate, which only repeats those checks), then `scripts/ci/assert-built-assets.sh` (built admin/storefront JS present when sources exist). All shopware-cli jobs run in `ghcr.io/shopware/shopware-cli:latest`; npm and shopware-cli caches via `actions/cache`.
2. `phpunit` - `composer create-project shopware/production` (6.6.x) + MariaDB service, copy the plugin into `custom/plugins`, install/activate, run phpunit. Runs in the same `shopware-cli` image (PHP and Composer included; `shivammathur/setup-php` hangs on this runner and apt installs cost ~4.5 min). MariaDB 10.11, because 11.4 broke Shopware's own migrations.
### Release workflow (`.gitea/workflows/release.yml`)
On push to `main`, guarded against re-release by an existing tag:
`extension package --git-commit "$GITHUB_SHA"` -> **validate the zip** -> assert built assets -> create the Gitea
release via API (`POST /repos/{owner}/{repo}/releases`, creates the tag) with the zip as asset ->
upload the same zip to the Composer registry -> link package to repository.
Removes the manual `git tag` step, the `akkuman` action and the `git archive` zip. Packaging happens
before the tag exists, so a failed build leaves no orphan tag.
### Branch protection (one-time, manual)
`scripts/protect-main.sh` using `tea api PATCH repos/{owner}/{repo}/branch_protections/main` to set the
required status-check contexts (now `plugin-checks / version-changelog|package|phpunit (pull_request)`,
set on `main`). `tea branches protect` cannot set status checks. Not run by the pipeline.
## 4. Open items (status after the first pipeline run)
- Release POST creates a missing tag: **resolved** - the POST created the tag and release for v0.1.0 (release id 55).
- Meaning of HTTP 400 on the package-link endpoint: **open** (not evidenced yet).
- Whether bare `validate` runs PHPStan/ESLint; Node availability on the runner image: **open** (not evidenced; the zip validate passes in the `shopware-cli` image).
- Accepted size for `metadata.icon.size`; error-vs-warning rule list of validate: **resolved** - `validate` on the zip reports "No problems found", so the icon size is accepted.
- Whether `routes.php` is flagged by validate: **resolved** - not flagged ("No problems found"). `shopware-cli extension fix` correctness for the YAML migration: **open**.
- Exact status-check context names: **resolved** - final: `plugin-checks / version-changelog (pull_request)`, `plugin-checks / package (pull_request)`, `plugin-checks / phpunit (pull_request)`, set on `main`.
- **Finding:** the Composer registry rejected the `shopware-cli` zip with "composer.json file is missing"; Gitea needs `composer.json` at the zip root, while the `shopware-cli` zip nests everything in a top-level folder. Fix (implemented separately): repack the zip with the top-level folder stripped for the registry upload; the Release asset stays the `shopware-cli` zip.
## 5. Out of scope / later
Shopware Store upload; Gitea shared-workflow repository; phpunit lowest-version matrix; Store listing metadata.
Regular → Executable
View File
File mode changed.
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Assert that a packaged extension zip contains the built admin/storefront JS when the sources exist.
# Usage: scripts/ci/assert-built-assets.sh <zip> (run from the repo root; BusyBox-safe: uses unzip -l)
set -euo pipefail
ZIP="${1:?usage: assert-built-assets.sh <zip>}"
LIST=$(unzip -l "$ZIP")
check() { # <label> <entry-glob-prefix> <expected path in zip>
local label="$1" entry="$2" expected="$3"
if [ -f "${entry}/main.js" ] || [ -f "${entry}/main.ts" ]; then
echo "$LIST" | grep -q "$expected" || { echo "::error::${label} entry exists but the zip has no built ${label} JS (${expected})"; exit 1; }
echo "ok: ${label} JS is in the zip"
fi
}
check admin src/Resources/app/administration/src "Resources/public/administration/js/"
check storefront src/Resources/app/storefront/src "Resources/app/storefront/dist/"
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# One-time (re-runnable) setup: require the PR checks on `main` using the Gitea `tea` CLI.
# `tea branches protect` cannot set status-check contexts, hence `tea api`.
# Usage: scripts/protect-main.sh [owner/repo] (default: derived from the git remote)
set -euo pipefail
REPO="${1:-$(git config --get remote.origin.url | sed -E 's#^.*[:/]([^/]+/[^/]+)$#\1#; s#\.git$##')}"
tea api -X PATCH "repos/${REPO}/branch_protections/main" -d '{
"enable_status_check": true,
"status_check_contexts": [
"plugin-checks / version-changelog (pull_request)",
"plugin-checks / package (pull_request)",
"plugin-checks / phpunit (pull_request)"
]
}'
Regular → Executable
View File
File mode changed.
Regular → Executable
+26 -32
View File
@@ -2,18 +2,35 @@
namespace AeonDumpManager; namespace AeonDumpManager;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Plugin; use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\ActivateContext;
use Shopware\Core\Framework\Plugin\Context\DeactivateContext;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Plugin\Context\UninstallContext; use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Shopware\Core\Framework\Plugin\Context\UpdateContext; use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
use Symfony\Component\DependencyInjection\Loader\GlobFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class AeonDumpManager extends Plugin class AeonDumpManager extends Plugin
{ {
public function install(InstallContext $installContext): void public function build(ContainerBuilder $container): void
{ {
// Do stuff such as creating a new payment method parent::build($container);
// Registers the dedicated monolog channel (Resources/config/packages/monolog.yaml)
$locator = new FileLocator('Resources/config');
$resolver = new LoaderResolver([
new YamlFileLoader($container, $locator),
new GlobFileLoader($container, $locator),
new DirectoryLoader($container, $locator),
]);
(new DelegatingLoader($resolver))->load(
\rtrim($this->getPath(), '/') . '/Resources/config/packages/*.yaml',
'glob'
);
} }
public function uninstall(UninstallContext $uninstallContext): void public function uninstall(UninstallContext $uninstallContext): void
@@ -24,31 +41,8 @@ class AeonDumpManager extends Plugin
return; return;
} }
// Remove or deactivate the data created by the plugin /** @var Connection $connection */
} $connection = $this->container->get(Connection::class);
$connection->executeStatement('DROP TABLE IF EXISTS `aeon_dump_manager_job`');
public function activate(ActivateContext $activateContext): void
{
// Activate entities, such as a new payment method
// Or create new entities here, because now your plugin is installed and active for sure
}
public function deactivate(DeactivateContext $deactivateContext): void
{
// Deactivate entities, such as a new payment method
// Or remove previously created entities
}
public function update(UpdateContext $updateContext): void
{
// Update necessary stuff, mostly non-database related
}
public function postInstall(InstallContext $installContext): void
{
}
public function postUpdate(UpdateContext $updateContext): void
{
} }
} }
+39
View File
@@ -0,0 +1,39 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Command;
use AeonDumpManager\Service\DumpService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'aeon:dump:create',
description: 'Create a new SQL dump',
)]
class DumpCreateCommand extends Command
{
public function __construct(private readonly DumpService $dumpService)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
try {
$dumpFile = $this->dumpService->createSync();
} catch (\Throwable $exception) {
$io->error($exception->getMessage());
return Command::FAILURE;
}
$io->success(sprintf('Dump created: %s', $dumpFile->filename));
return Command::SUCCESS;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Command;
use AeonDumpManager\Service\DumpLister;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'aeon:dump:list',
description: 'List the existing SQL dumps',
)]
class DumpListCommand extends Command
{
public function __construct(private readonly DumpLister $dumpLister)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$dumps = $this->dumpLister->list();
if ($dumps === []) {
$io->info('No dumps found.');
return Command::SUCCESS;
}
$io->table(
['Filename', 'Datetime', 'Size'],
array_map(
static fn ($dumpFile) => [
$dumpFile->filename,
$dumpFile->datetime->format('Y-m-d H:i:s'),
self::formatSize($dumpFile->sizeBytes),
],
$dumps
)
);
return Command::SUCCESS;
}
private static function formatSize(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$result = (float) $bytes;
$i = 0;
for (; $i < count($units) - 1; $i++) {
if ($result / 1024 < 0.9) {
break;
}
$result /= 1024;
}
return number_format($result, 2) . $units[$i];
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Command;
use AeonDumpManager\Service\DumpService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'aeon:dump:remove',
description: 'Remove an existing SQL dump',
)]
class DumpRemoveCommand extends Command
{
public function __construct(private readonly DumpService $dumpService)
{
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('filename', InputArgument::REQUIRED, 'Filename of the dump to remove, as shown by aeon:dump:list');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$filename = (string) $input->getArgument('filename');
try {
$this->dumpService->delete($filename);
} catch (\Throwable $exception) {
$io->error($exception->getMessage());
return Command::FAILURE;
}
$io->success(sprintf('Dump removed: %s', $filename));
return Command::SUCCESS;
}
}
-30
View File
@@ -1,30 +0,0 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'aeon:example',
description: 'Add a short description for your command',
)]
class ExampleCommand extends Command
{
// Provides a description, printed out in bin/console
protected function configure(): void
{
$this->setDescription('Does something very special.');
}
// Actual code executed in the command
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('It works!');
// Exit code 0 for success
return 0;
}
}
+155
View File
@@ -0,0 +1,155 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Controller;
use AeonDumpManager\MessageQueue\Message\CreateDumpMessage;
use AeonDumpManager\Service\DumpJobStatusService;
use AeonDumpManager\Service\DumpLister;
use AeonDumpManager\Service\DumpService;
use AeonDumpManager\Service\Exception\DumpNotFoundException;
use Shopware\Core\Framework\Routing\ApiRouteScope;
use Shopware\Core\PlatformRequest;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
/**
* Client-side acl.can() in the admin UI only hides buttons — real
* enforcement is the PlatformRequest::ATTRIBUTE_ACL route default below,
* checked server-side by AclAnnotationValidator against Context::isAllowed().
*/
#[Route(defaults: [PlatformRequest::ATTRIBUTE_ROUTE_SCOPE => [ApiRouteScope::ID]])]
class DumpController
{
public function __construct(
private readonly DumpLister $dumpLister,
private readonly DumpService $dumpService,
private readonly DumpJobStatusService $jobStatus,
private readonly MessageBusInterface $bus,
) {
}
#[Route(
path: '/api/_action/aeon-dump-manager/dumps',
name: 'api.action.aeon_dump_manager.dumps.list',
defaults: [PlatformRequest::ATTRIBUTE_ACL => ['aeon_dump_manager.viewer']],
methods: ['GET']
)]
public function list(Request $request): JsonResponse
{
$dumps = array_map(
static fn ($dumpFile) => $dumpFile->jsonSerialize(),
$this->dumpLister->list(
$this->parseBoundDate($request->query->get('from'), false),
$this->parseBoundDate($request->query->get('to'), true),
)
);
return new JsonResponse(['dumps' => $dumps]);
}
/**
* The admin's date filter sends mixed shapes: the "from" bound is a naive local
* date string with no timezone marker (e.g. "2026-03-01T00:00:00"), while
* sw-date-filter widens "to" to end-of-day client-side via `Date#toISOString()`,
* which is always UTC (e.g. "2026-03-01T23:59:59.000Z"). Re-expressing both in
* PHP's default timezone (the same one DumpFilenameParser uses) before applying
* our own day-boundary keeps the calendar day the user actually picked, regardless
* of which shape arrived. An empty bound (no date set) stays null so the range is
* open on that side.
*/
private function parseBoundDate(?string $value, bool $endOfDay): ?\DateTimeImmutable
{
if ($value === null || trim($value) === '') {
return null;
}
try {
$dateTime = (new \DateTimeImmutable($value))->setTimezone(new \DateTimeZone(date_default_timezone_get()));
} catch (\Exception) {
return null;
}
return $endOfDay
? $dateTime->setTime(23, 59, 59)
: $dateTime->setTime(0, 0, 0);
}
#[Route(
path: '/api/_action/aeon-dump-manager/dumps',
name: 'api.action.aeon_dump_manager.dumps.create',
defaults: [PlatformRequest::ATTRIBUTE_ACL => ['aeon_dump_manager.creator']],
methods: ['POST']
)]
public function create(): JsonResponse
{
$jobId = $this->jobStatus->createPending();
$this->bus->dispatch(new CreateDumpMessage($jobId));
return new JsonResponse(['jobId' => $jobId], Response::HTTP_ACCEPTED);
}
#[Route(
path: '/api/_action/aeon-dump-manager/dumps/{filename}',
name: 'api.action.aeon_dump_manager.dumps.delete',
defaults: [PlatformRequest::ATTRIBUTE_ACL => ['aeon_dump_manager.deleter']],
methods: ['DELETE']
)]
public function delete(string $filename): JsonResponse
{
try {
$this->dumpService->delete($filename);
} catch (DumpNotFoundException $exception) {
return new JsonResponse(['message' => $exception->getMessage()], Response::HTTP_NOT_FOUND);
}
return new JsonResponse(null, Response::HTTP_NO_CONTENT);
}
#[Route(
path: '/api/_action/aeon-dump-manager/dumps/{filename}/download',
name: 'api.action.aeon_dump_manager.dumps.download',
defaults: [PlatformRequest::ATTRIBUTE_ACL => ['aeon_dump_manager.viewer']],
methods: ['GET']
)]
public function download(string $filename): StreamedResponse
{
try {
$stream = $this->dumpService->readStream($filename);
} catch (DumpNotFoundException $exception) {
throw new NotFoundHttpException($exception->getMessage());
}
$response = new StreamedResponse(static function () use ($stream): void {
fpassthru($stream);
});
$response->headers->set('Content-Type', 'application/gzip');
$response->headers->set(
'Content-Disposition',
HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, $filename)
);
return $response;
}
#[Route(
path: '/api/_action/aeon-dump-manager/dumps/jobs/{jobId}',
name: 'api.action.aeon_dump_manager.dumps.jobs.status',
defaults: [PlatformRequest::ATTRIBUTE_ACL => ['aeon_dump_manager.viewer']],
methods: ['GET']
)]
public function jobStatus(string $jobId): JsonResponse
{
$job = $this->jobStatus->find($jobId);
if ($job === null) {
return new JsonResponse(['message' => 'Job not found'], Response::HTTP_NOT_FOUND);
}
return new JsonResponse($job);
}
}
@@ -0,0 +1,34 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\MessageQueue\Handler;
use AeonDumpManager\MessageQueue\Message\CreateDumpMessage;
use AeonDumpManager\Service\DumpJobStatusService;
use AeonDumpManager\Service\DumpService;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
class CreateDumpHandler
{
public function __construct(
private readonly DumpService $dumpService,
private readonly DumpJobStatusService $jobStatus,
private readonly LoggerInterface $logger,
) {
}
public function __invoke(CreateDumpMessage $message): void
{
$jobId = $message->getJobId();
$this->jobStatus->markRunning($jobId);
$this->logger->info('Dump job started.', ['jobId' => $jobId]);
try {
$this->dumpService->createAsync($jobId, $this->jobStatus);
} catch (\Throwable $exception) {
$this->logger->error('Dump job failed.', ['jobId' => $jobId, 'exception' => $exception]);
$this->jobStatus->markFailed($jobId, $exception->getMessage());
}
}
}
@@ -0,0 +1,17 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\MessageQueue\Message;
use Shopware\Core\Framework\MessageQueue\AsyncMessageInterface;
class CreateDumpMessage implements AsyncMessageInterface
{
public function __construct(private readonly string $jobId)
{
}
public function getJobId(): string
{
return $this->jobId;
}
}
@@ -0,0 +1,35 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Migration;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Migration\MigrationStep;
class Migration1789413583CreateDumpJobTable extends MigrationStep
{
public function getCreationTimestamp(): int
{
return 1789413583;
}
public function update(Connection $connection): void
{
$connection->executeStatement(<<<'SQL'
CREATE TABLE IF NOT EXISTS `aeon_dump_manager_job` (
`id` BINARY(16) NOT NULL,
`status` VARCHAR(20) NOT NULL,
`percent` SMALLINT UNSIGNED NULL,
`filename` VARCHAR(255) NULL,
`error_message` TEXT NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3) NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
SQL);
}
public function updateDestructive(Connection $connection): void
{
// nothing destructive to do
}
}
+20
View File
@@ -0,0 +1,20 @@
// Shopware injects its Administration API as untyped globals at runtime; there's
// no official @shopware-ag type package for plugin authors to install against
// (per docs/research/admin-dump-manager-ui.md §4), so these are declared loosely
// as `any` — good enough for editor support, and the build (swc, type-stripping
// only, no tsc typecheck) doesn't need them at all.
declare const Shopware: any;
interface Window {
Shopware: typeof Shopware;
}
declare module '*.html.twig' {
const template: string;
export default template;
}
declare module '*.json' {
const value: Record<string, unknown>;
export default value;
}
@@ -1,2 +0,0 @@
// Import admin module
import './module/swag-example';
+8
View File
@@ -0,0 +1,8 @@
import DumpApiService from './service/dump-api.service';
import './module/aeon-dump-manager';
Shopware.Application.addServiceProvider('aeonDumpManagerApiService', (container: { loginService: unknown }) => {
const initContainer = Shopware.Application.getContainer('init');
return new DumpApiService(initContainer.httpClient, container.loginService);
});
@@ -0,0 +1,19 @@
Shopware.Service('privileges').addPrivilegeMappingEntry({
category: 'permissions',
parent: null,
key: 'aeon_dump_manager',
roles: {
viewer: {
privileges: ['aeon_dump_manager.viewer'],
dependencies: [],
},
creator: {
privileges: ['aeon_dump_manager.creator'],
dependencies: ['aeon_dump_manager.viewer'],
},
deleter: {
privileges: ['aeon_dump_manager.deleter'],
dependencies: ['aeon_dump_manager.viewer'],
},
},
});
@@ -0,0 +1,53 @@
import './acl';
import './page/aeon-dump-manager-list';
import deDE from './snippet/de-DE.json';
import enGB from './snippet/en-GB.json';
Shopware.Module.register('aeon-dump-manager', {
type: 'plugin',
name: 'DumpManager',
title: 'aeon-dump-manager.general.mainMenuItemGeneral',
description: 'aeon-dump-manager.general.descriptionTextModule',
color: '#ff3d58',
icon: 'regular-database',
snippets: {
'de-DE': deDE,
'en-GB': enGB,
},
routes: {
list: {
component: 'aeon-dump-manager-list',
path: 'list',
meta: {
parentPath: 'sw.settings.index.system',
privilege: 'aeon_dump_manager.viewer',
},
},
},
// Per https://developer.shopware.com/docs/v6.6/guides/plugins/plugins/administration/routing-navigation/add-menu-entry.html —
// plugins can't register a first-level main-menu entry, so this nests
// under the core 'sw-settings' navigation node. Clicking Settings in the
// main sidebar shows this as a sub-item, landing at #/sw/settings/.
navigation: [{
id: 'aeon-dump-manager-list',
label: 'aeon-dump-manager.general.mainMenuItemGeneral',
color: '#ff3d58',
path: 'aeon.dump.manager.list',
icon: 'regular-database',
parent: 'sw-settings',
position: 100,
privilege: 'aeon_dump_manager.viewer',
}],
// Also shown as a card on the Settings overview page's "System" group,
// next to Plugins/Cache — complements the navigation entry above.
settingsItem: {
group: 'system',
to: 'aeon.dump.manager.list',
icon: 'regular-database',
privilege: 'aeon_dump_manager.viewer',
},
});
@@ -0,0 +1,124 @@
{% block aeon_dump_manager_list %}
<sw-page class="aeon-dump-manager-list">
<template #smart-bar-actions>
<sw-button
v-if="acl.can('aeon_dump_manager.creator')"
variant="primary"
:is-loading="pendingJob !== null"
:disabled="pendingJob !== null"
@click="onCreate"
>
{{ $tc('aeon-dump-manager.list.buttonCreate') }}
</sw-button>
</template>
<template #content>
<div class="aeon-dump-manager-list__content">
<sw-filter-panel
:filters="listFilters"
:defaults="defaultFilters"
:store-key="storeKey"
@criteria-changed="onCriteriaChanged"
/>
<sw-data-grid
:data-source="sortedDumps"
:columns="columns"
:is-loading="isLoading"
:show-selection="acl.can('aeon_dump_manager.deleter')"
:full-page="true"
:sort-by="sortBy"
:sort-direction="sortDirection"
identifier="filename"
@selection-change="onSelectionChange"
@column-sort="onSortColumn"
>
<template #bulk>
<a
v-if="acl.can('aeon_dump_manager.deleter')"
class="link link-danger aeon-dump-manager-list__bulk-delete"
role="button"
tabindex="0"
@click="onRequestBulkDelete"
@keydown.enter="onRequestBulkDelete"
>
{{ $tc('aeon-dump-manager.list.bulkDeleteButton', 0, { count: selectionCount }) }}
</a>
</template>
<template #column-datetime="{ item }">
{{ formatDatetime(item.datetime) }}
</template>
<template #column-sizeBytes="{ item }">
{{ formatSize(item.sizeBytes) }}
</template>
<template #actions="{ item }">
<sw-context-menu-item
v-if="acl.can('aeon_dump_manager.viewer')"
@click="onDownload(item.filename)"
>
{{ $tc('aeon-dump-manager.list.buttonDownload') }}
</sw-context-menu-item>
<sw-context-menu-item
v-if="acl.can('aeon_dump_manager.deleter')"
variant="danger"
@click="onRequestDelete(item.filename)"
>
{{ $tc('aeon-dump-manager.list.buttonDelete') }}
</sw-context-menu-item>
</template>
<template #empty-state>
{{ $tc('aeon-dump-manager.list.empty') }}
</template>
</sw-data-grid>
</div>
</template>
{% block aeon_dump_manager_list_progress_modal %}
<sw-modal
v-if="pendingJob !== null"
:title="$tc('aeon-dump-manager.list.progressTitle')"
variant="small"
class="aeon-dump-manager-list__progress-modal"
@modal-close="onCloseProgressModal"
>
<div class="aeon-dump-manager-list__progress-wrapper">
<template v-if="pendingJob.status === 'done'">
<sw-alert variant="success">
{{ $tc('aeon-dump-manager.list.createSuccess') }}
</sw-alert>
</template>
<template v-else-if="pendingJob.status === 'failed'">
<sw-alert variant="error">
{{ $tc('aeon-dump-manager.list.createFailed', 0, { error: pendingJob.errorMessage || '' }) }}
</sw-alert>
</template>
<template v-else>
<sw-progress-bar
:value="pendingJob.percent || 0"
:max-value="100"
/>
<span class="aeon-dump-manager-list__progress-text">
{{ $tc('aeon-dump-manager.list.progressText') }}
</span>
</template>
</div>
</sw-modal>
{% endblock %}
<sw-confirm-modal
v-if="deleteFilenames !== null"
:title="$tc('aeon-dump-manager.list.confirmDeleteTitle')"
:text="deleteFilenames.length > 1
? $tc('aeon-dump-manager.list.confirmDeleteTextMultiple', 0, { count: deleteFilenames.length })
: $tc('aeon-dump-manager.list.confirmDeleteText', 0, { filename: deleteFilenames[0] })"
type="delete"
@confirm="onConfirmDelete"
@cancel="onCancelDelete"
@close="onCancelDelete"
/>
</sw-page>
{% endblock %}
@@ -0,0 +1,289 @@
import template from './aeon-dump-manager-list.html.twig';
import type DumpApiService, { DumpFile, DumpJob } from '../../../../service/dump-api.service';
const { Component, Mixin } = Shopware;
interface PendingJob {
status: string;
percent: number | null;
errorMessage?: string | null;
}
const CREATE_MODAL_AUTO_CLOSE_MS = 1500;
interface DateRangeCriteria {
type: string;
field: string;
parameters?: { gte?: string; lte?: string };
}
interface ComponentData {
dumps: DumpFile[];
isLoading: boolean;
pendingJob: PendingJob | null;
deleteFilenames: string[] | null;
selection: Record<string, DumpFile>;
pollTimer: number | null;
dateFrom: string | null;
dateTo: string | null;
sortBy: string;
sortDirection: string;
storeKey: string;
defaultFilters: string[];
}
interface ComponentInstance extends ComponentData {
aeonDumpManagerApiService: DumpApiService;
$tc: (key: string, count?: number, values?: Record<string, unknown>) => string;
createNotificationError: (options: { message: string }) => void;
createNotificationSuccess: (options: { message: string }) => void;
getList: () => Promise<void>;
stopPolling: () => void;
pollJobStatus: (jobId: string) => void;
selectionCount: number;
sortedDumps: DumpFile[];
listFilters: Record<string, unknown>[];
}
Component.register('aeon-dump-manager-list', {
template,
mixins: [
// Provides createNotificationSuccess/createNotificationError, used below.
Mixin.getByName('notification'),
// Provides sortBy/sortDirection state, onSortColumn(), and route-query
// persistence for them (same mixin sw-product-list etc. use) — our own
// data() below overrides the defaults to keep "newest first".
Mixin.getByName('listing'),
],
inject: ['aeonDumpManagerApiService', 'acl'],
data(): ComponentData {
return {
dumps: [],
isLoading: false,
pendingJob: null,
deleteFilenames: null,
selection: {},
pollTimer: null,
dateFrom: null,
dateTo: null,
sortBy: 'datetime',
sortDirection: 'DESC',
storeKey: 'grid.filter.aeon-dump-manager',
defaultFilters: ['datetime'],
};
},
computed: {
listFilters(this: ComponentInstance) {
return [
{
name: 'datetime',
type: 'date-filter',
property: 'datetime',
label: this.$tc('aeon-dump-manager.list.columnDatetime'),
dateType: 'date',
fromFieldLabel: this.$tc('aeon-dump-manager.list.filterFromLabel'),
toFieldLabel: this.$tc('aeon-dump-manager.list.filterToLabel'),
fromPlaceholder: this.$tc('aeon-dump-manager.list.filterFromPlaceholder'),
toPlaceholder: this.$tc('aeon-dump-manager.list.filterToPlaceholder'),
showTimeframe: false,
},
];
},
columns() {
return [
{
property: 'datetime',
dataIndex: 'datetime',
label: this.$tc('aeon-dump-manager.list.columnDatetime'),
allowResize: true,
sortable: true,
},
{
property: 'filename',
dataIndex: 'filename',
label: this.$tc('aeon-dump-manager.list.columnFilename'),
allowResize: true,
sortable: true,
},
{
property: 'sizeBytes',
dataIndex: 'sizeBytes',
label: this.$tc('aeon-dump-manager.list.columnSize'),
align: 'right',
allowResize: true,
sortable: true,
},
];
},
selectionCount(this: ComponentInstance): number {
return Object.keys(this.selection).length;
},
sortedDumps(this: ComponentInstance): DumpFile[] {
const direction = this.sortDirection === 'ASC' ? 1 : -1;
return [...this.dumps].sort((a, b) => {
let compareVal: number;
switch (this.sortBy) {
case 'sizeBytes':
compareVal = a.sizeBytes - b.sizeBytes;
break;
case 'datetime':
compareVal = new Date(a.datetime).getTime() - new Date(b.datetime).getTime();
break;
default:
compareVal = a.filename.localeCompare(b.filename, undefined, { numeric: true });
}
return compareVal * direction;
});
},
},
beforeDestroy(this: ComponentInstance) {
this.stopPolling();
},
methods: {
getList(this: ComponentInstance): Promise<void> {
this.isLoading = true;
return this.aeonDumpManagerApiService.getList({ from: this.dateFrom, to: this.dateTo })
.then((response) => {
this.dumps = response.dumps;
})
.finally(() => {
this.isLoading = false;
});
},
formatDatetime(value: string): string {
return Shopware.Utils.format.date(value);
},
onCriteriaChanged(this: ComponentInstance, criteria: DateRangeCriteria[]) {
const range = criteria.find((filter) => filter.type === 'range' && filter.field === 'datetime');
this.dateFrom = range?.parameters?.gte ?? null;
this.dateTo = range?.parameters?.lte ?? null;
this.getList();
},
formatSize(bytes: number): string {
return Shopware.Utils.format.fileSize(bytes);
},
onSelectionChange(this: ComponentInstance, selection: Record<string, DumpFile>) {
this.selection = selection;
},
onCreate(this: ComponentInstance) {
this.pendingJob = { percent: 0, status: 'pending' };
this.aeonDumpManagerApiService.create()
.then((response) => {
this.pollJobStatus(response.jobId);
})
.catch((error: Error) => {
// Shown in the progress modal itself, not a notification —
// stays open so the user can actually read what went wrong.
this.pendingJob = { status: 'failed', percent: null, errorMessage: error.message };
});
},
pollJobStatus(this: ComponentInstance, jobId: string) {
this.stopPolling();
this.pollTimer = window.setInterval(() => {
this.aeonDumpManagerApiService.getJobStatus(jobId).then((job: DumpJob) => {
this.pendingJob = job;
if (job.status === 'done') {
this.stopPolling();
this.getList();
window.setTimeout(() => {
this.pendingJob = null;
}, CREATE_MODAL_AUTO_CLOSE_MS);
return;
}
if (job.status === 'failed') {
this.stopPolling();
}
});
}, 2000);
},
stopPolling(this: ComponentInstance) {
if (this.pollTimer !== null) {
window.clearInterval(this.pollTimer);
this.pollTimer = null;
}
},
onCloseProgressModal(this: ComponentInstance) {
this.stopPolling();
this.pendingJob = null;
},
onDownload(this: ComponentInstance, filename: string) {
this.aeonDumpManagerApiService.download(filename)
.then((blob) => {
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
})
.catch((error: Error) => {
this.createNotificationError({
message: this.$tc('aeon-dump-manager.list.downloadFailed', 0, { error: error.message }),
});
});
},
onRequestDelete(this: ComponentInstance, filename: string) {
this.deleteFilenames = [filename];
},
onRequestBulkDelete(this: ComponentInstance) {
this.deleteFilenames = Object.keys(this.selection);
},
onCancelDelete(this: ComponentInstance) {
this.deleteFilenames = null;
},
onConfirmDelete(this: ComponentInstance): Promise<void> {
const filenames = this.deleteFilenames as string[];
this.deleteFilenames = null;
// Optimistic UI update: pull the rows out immediately rather than
// waiting on a full reload, so the grid never looks stale even if
// getList() is slow or a later delete in the batch fails.
this.dumps = this.dumps.filter((dumpFile) => !filenames.includes(dumpFile.filename));
this.selection = {};
return Promise.all(filenames.map((filename) => this.aeonDumpManagerApiService.remove(filename)))
.then(() => this.getList())
.catch((error: Error) => {
this.createNotificationError({
message: this.$tc('aeon-dump-manager.list.deleteFailed', 0, { error: error.message }),
});
// A delete failed after the optimistic removal — reload to
// show the real state rather than leave a wrong guess on screen.
return this.getList();
});
},
},
});
@@ -0,0 +1,31 @@
{
"aeon-dump-manager": {
"general": {
"mainMenuItemGeneral": "Dump-Verwaltung",
"descriptionTextModule": "SQL-Datenbank-Dumps erstellen, auflisten und löschen"
},
"list": {
"columnFilename": "Name",
"columnDatetime": "Erstellt am",
"columnSize": "Größe",
"filterFromLabel": "Von",
"filterFromPlaceholder": "Startdatum auswählen...",
"filterToLabel": "Bis",
"filterToPlaceholder": "Enddatum auswählen...",
"buttonCreate": "Dump erstellen",
"buttonDownload": "Herunterladen",
"buttonDelete": "Löschen",
"bulkDeleteButton": "Auswahl löschen ({count})",
"confirmDeleteTitle": "Dump löschen?",
"confirmDeleteText": "Möchten Sie \"{filename}\" wirklich löschen? Dies kann nicht rückgängig gemacht werden.",
"confirmDeleteTextMultiple": "Möchten Sie {count} Dumps wirklich löschen? Dies kann nicht rückgängig gemacht werden.",
"empty": "Keine Dumps gefunden.",
"progressTitle": "Dump wird erstellt",
"progressText": "Dump wird erstellt…",
"createFailed": "Dump konnte nicht erstellt werden: {error}",
"createSuccess": "Dump erstellt.",
"deleteFailed": "Dump konnte nicht gelöscht werden: {error}",
"downloadFailed": "Dump konnte nicht heruntergeladen werden: {error}"
}
}
}
@@ -0,0 +1,31 @@
{
"aeon-dump-manager": {
"general": {
"mainMenuItemGeneral": "Dump manager",
"descriptionTextModule": "Create, list and delete SQL database dumps"
},
"list": {
"columnFilename": "Name",
"columnDatetime": "Created at",
"columnSize": "Size",
"filterFromLabel": "From",
"filterFromPlaceholder": "Select start date...",
"filterToLabel": "To",
"filterToPlaceholder": "Select end date...",
"buttonCreate": "Create dump",
"buttonDownload": "Download",
"buttonDelete": "Delete",
"bulkDeleteButton": "Delete selected ({count})",
"confirmDeleteTitle": "Delete dump?",
"confirmDeleteText": "Are you sure you want to delete \"{filename}\"? This cannot be undone.",
"confirmDeleteTextMultiple": "Are you sure you want to delete {count} dumps? This cannot be undone.",
"empty": "No dumps found.",
"progressTitle": "Creating dump",
"progressText": "Creating dump…",
"createFailed": "Could not create dump: {error}",
"createSuccess": "Dump created.",
"deleteFailed": "Could not delete dump: {error}",
"downloadFailed": "Could not download dump: {error}"
}
}
}
@@ -1,49 +0,0 @@
// <plugin root>/src/Resources/app/administration/src/module/swag-example/index.js
import './page/swag-example-list';
import './page/swag-example-detail';
import './page/swag-example-create';
import deDE from './snippet/de-DE';
import enGB from './snippet/en-GB';
Shopware.Module.register('swag-example', {
type: 'plugin',
name: 'Example',
title: 'swag-example.general.mainMenuItemGeneral',
description: 'sw-property.general.descriptionTextModule',
color: '#ff3d58',
icon: 'default-shopping-paper-bag-product',
snippets: {
'de-DE': deDE,
'en-GB': enGB
},
routes: {
list: {
component: 'swag-example-list',
path: 'list'
},
detail: {
component: 'swag-example-detail',
path: 'detail/:id',
meta: {
parentPath: 'swag.example.list'
}
},
create: {
component: 'swag-example-create',
path: 'create',
meta: {
parentPath: 'swag.example.list'
}
}
},
navigation: [{
label: 'swag-example.general.mainMenuItemGeneral',
color: '#ff3d58',
path: 'swag.example.list',
icon: 'default-shopping-paper-bag-product',
position: 100
}]
});
@@ -0,0 +1,81 @@
export interface DumpFile {
filename: string;
datetime: string;
sizeBytes: number;
}
export interface DumpList {
dumps: DumpFile[];
}
export interface CreateDumpResponse {
jobId: string;
}
export type DumpJobStatus = 'pending' | 'running' | 'done' | 'failed';
export interface DumpJob {
id: string;
status: DumpJobStatus;
percent: number | null;
filename: string | null;
errorMessage: string | null;
}
// Shopware.Classes.ApiService has no official type package for plugin authors
// (per docs/research/admin-dump-manager-ui.md §4) — redeclaring the inherited
// member this class actually uses keeps everything below typed without one.
// `declare` is required here: a normal field declaration compiles to a real
// `this.httpClient = void 0` in the constructor, which runs *after* `super()`
// and silently clobbers the value the base class just set.
const { ApiService } = Shopware.Classes;
export default class DumpApiService extends ApiService {
protected declare httpClient: {
get: (url: string, config?: unknown) => Promise<unknown>;
post: (url: string, data: unknown, config?: unknown) => Promise<unknown>;
delete: (url: string, config?: unknown) => Promise<unknown>;
};
protected declare getBasicHeaders: (additionalHeaders?: Record<string, string>) => Record<string, string>;
constructor(httpClient: unknown, loginService: unknown, apiEndpoint = 'aeon-dump-manager') {
super(httpClient, loginService, apiEndpoint);
}
getList(filter: { from?: string | null; to?: string | null } = {}): Promise<DumpList> {
return this.httpClient
.get('/_action/aeon-dump-manager/dumps', {
headers: this.getBasicHeaders(),
params: { from: filter.from ?? undefined, to: filter.to ?? undefined },
})
.then((response: unknown) => ApiService.handleResponse(response));
}
create(): Promise<CreateDumpResponse> {
return this.httpClient
.post('/_action/aeon-dump-manager/dumps', {}, { headers: this.getBasicHeaders() })
.then((response: unknown) => ApiService.handleResponse(response));
}
remove(filename: string): Promise<void> {
return this.httpClient
.delete(`/_action/aeon-dump-manager/dumps/${encodeURIComponent(filename)}`, { headers: this.getBasicHeaders() })
.then((response: unknown) => ApiService.handleResponse(response));
}
getJobStatus(jobId: string): Promise<DumpJob> {
return this.httpClient
.get(`/_action/aeon-dump-manager/dumps/jobs/${encodeURIComponent(jobId)}`, { headers: this.getBasicHeaders() })
.then((response: unknown) => ApiService.handleResponse(response));
}
download(filename: string): Promise<Blob> {
return this.httpClient
.get(`/_action/aeon-dump-manager/dumps/${encodeURIComponent(filename)}/download`, {
headers: this.getBasicHeaders(),
responseType: 'blob',
})
.then((response: unknown) => ApiService.handleResponse(response) as Blob);
}
}
@@ -1,8 +0,0 @@
{
"swag-example": {
"general": {
"mainMenuItemGeneral": "My custom module",
"descriptionTextModule": "Manage this custom module here"
}
}
}
@@ -1,8 +0,0 @@
{
"swag-example": {
"general": {
"mainMenuItemGeneral": "My custom module",
"descriptionTextModule": "Manage this custom module here"
}
}
}
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"strict": false,
"noEmit": true,
"skipLibCheck": true,
"allowJs": true,
"esModuleInterop": true
},
"include": ["**/*.ts", "global.d.ts"]
}
Regular → Executable
+6 -2
View File
@@ -6,16 +6,20 @@
<card> <card>
<title>Minimal configuration</title> <title>Minimal configuration</title>
<input-field type="number"> <input-field type="int">
<name>maxDumps</name> <name>maxDumps</name>
<label>Maximum allowed dumps to exist</label> <label>Maximum allowed dumps to exist</label>
<defaultValue>6</defaultValue> <defaultValue>6</defaultValue>
</input-field> </input-field>
<input-field type="number"> <input-field type="int">
<name>retantionDays</name> <name>retantionDays</name>
<label>How many Days the dumps kept in the Storage. 0 Means unlimited</label> <label>How many Days the dumps kept in the Storage. 0 Means unlimited</label>
<defaultValue>0</defaultValue> <defaultValue>0</defaultValue>
</input-field> </input-field>
<input-field type="text">
<name>dumpBinaryName</name>
<label>Name of the mysqldump/mariadb-dump binary to look up on PATH (e.g. if your distro renamed it). Leave empty to auto-detect.</label>
</input-field>
</card> </card>
</config> </config>
@@ -0,0 +1,2 @@
monolog:
channels: ['aeon_dump_manager']
Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+3
View File
@@ -0,0 +1,3 @@
aeon_dump_manager_controllers:
resource: ../../Controller/*Controller.php
type: attribute
-18
View File
@@ -1,18 +0,0 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="AeonDumpManager\Command\ExampleCommand">
<tag name="console.command"/>
</service>
<service id="AeonDumpManager\ScheduledTask\ExampleTask">
<tag name="shopware.scheduled.task"/>
</service>
</services>
</container>
+92
View File
@@ -0,0 +1,92 @@
services:
Symfony\Component\Process\ExecutableFinder: ~
aeon_dump_manager.dump_filename_parser:
class: AeonDumpManager\Service\DumpFilenameParser
aeon_dump_manager.dump_binary_locator:
class: AeonDumpManager\Service\DumpBinaryLocator
arguments:
- '@Doctrine\DBAL\Connection'
- '@Shopware\Core\System\SystemConfig\SystemConfigService'
- '@Symfony\Component\Process\ExecutableFinder'
aeon_dump_manager.dump_job_status_service:
class: AeonDumpManager\Service\DumpJobStatusService
arguments:
- '@Doctrine\DBAL\Connection'
aeon_dump_manager.dump_lister:
class: AeonDumpManager\Service\DumpLister
arguments:
- '@aeon_dump_manager.filesystem.private'
- '@aeon_dump_manager.dump_filename_parser'
aeon_dump_manager.dump_service:
class: AeonDumpManager\Service\DumpService
arguments:
- '@aeon_dump_manager.dump_lister'
- '@aeon_dump_manager.filesystem.private'
- '@aeon_dump_manager.dump_binary_locator'
- '@Doctrine\DBAL\Connection'
- '@Shopware\Core\System\SystemConfig\SystemConfigService'
- '@aeon_dump_manager.dump_filename_parser'
- '@monolog.logger.aeon_dump_manager'
# Async create job
aeon_dump_manager.message_queue.create_dump_handler:
class: AeonDumpManager\MessageQueue\Handler\CreateDumpHandler
arguments:
- '@aeon_dump_manager.dump_service'
- '@aeon_dump_manager.dump_job_status_service'
- '@monolog.logger.aeon_dump_manager'
tags:
- { name: messenger.message_handler }
# Retention
aeon_dump_manager.scheduled_task.purge_dumps_task:
class: AeonDumpManager\ScheduledTask\PurgeDumpsTask
tags:
- { name: shopware.scheduled.task }
aeon_dump_manager.scheduled_task.purge_dumps_task_handler:
class: AeonDumpManager\ScheduledTask\PurgeDumpsTaskHandler
arguments:
- '@scheduled_task.repository'
- '@monolog.logger.aeon_dump_manager'
- '@aeon_dump_manager.dump_service'
- '@aeon_dump_manager.dump_job_status_service'
- '@Shopware\Core\System\SystemConfig\SystemConfigService'
tags:
- { name: messenger.message_handler, handles: AeonDumpManager\ScheduledTask\PurgeDumpsTask }
# Console commands
aeon_dump_manager.command.dump_list:
class: AeonDumpManager\Command\DumpListCommand
arguments:
- '@aeon_dump_manager.dump_lister'
tags:
- { name: console.command }
aeon_dump_manager.command.dump_create:
class: AeonDumpManager\Command\DumpCreateCommand
arguments:
- '@aeon_dump_manager.dump_service'
tags:
- { name: console.command }
aeon_dump_manager.command.dump_remove:
class: AeonDumpManager\Command\DumpRemoveCommand
arguments:
- '@aeon_dump_manager.dump_service'
tags:
- { name: console.command }
# Admin API controller
AeonDumpManager\Controller\DumpController:
public: true
arguments:
- '@aeon_dump_manager.dump_lister'
- '@aeon_dump_manager.dump_service'
- '@aeon_dump_manager.dump_job_status_service'
- '@messenger.default_bus'
@@ -4,15 +4,15 @@ namespace AeonDumpManager\ScheduledTask;
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTask; use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTask;
class ExampleTask extends ScheduledTask class PurgeDumpsTask extends ScheduledTask
{ {
public static function getTaskName(): string public static function getTaskName(): string
{ {
return 'swag.example_task'; return 'aeon_dump_manager.purge_dumps_task';
} }
public static function getDefaultInterval(): int public static function getDefaultInterval(): int
{ {
return 300; // 5 minutes return 3600; // hourly
} }
} }
@@ -0,0 +1,38 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\ScheduledTask;
use AeonDumpManager\Service\DumpJobStatusService;
use AeonDumpManager\Service\DumpService;
use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskHandler;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler(handles: PurgeDumpsTask::class)]
class PurgeDumpsTaskHandler extends ScheduledTaskHandler
{
public function __construct(
EntityRepository $scheduledTaskRepository,
LoggerInterface $logger,
private readonly DumpService $dumpService,
private readonly DumpJobStatusService $jobStatus,
private readonly SystemConfigService $systemConfigService,
) {
parent::__construct($scheduledTaskRepository, $logger);
}
public function run(): void
{
$retantionDays = $this->systemConfigService->getInt('AeonDumpManager.config.retantionDays');
if ($retantionDays <= 0) {
return; // 0 means unlimited — nothing to purge
}
$threshold = (new \DateTimeImmutable())->modify("-{$retantionDays} days");
$this->dumpService->purgeOlderThan($threshold);
$this->jobStatus->purgeOlderThan($threshold);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service;
use AeonDumpManager\Service\Exception\DumpBinaryNotFoundException;
use Doctrine\DBAL\Connection;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
/**
* Picks mariadb-dump/mysqldump depending on what the configured DB connection
* actually is, mirroring Doctrine DBAL's own stripos($version, 'mariadb')
* version-string check (no shared platform base class to rely on instead).
*/
class DumpBinaryLocator
{
public function __construct(
private readonly Connection $connection,
private readonly SystemConfigService $systemConfigService,
private readonly ExecutableFinder $executableFinder,
) {
}
public function locate(): string
{
$configuredName = $this->systemConfigService->getString('AeonDumpManager.config.dumpBinaryName');
$binaryNames = $configuredName !== ''
? [$configuredName]
: ($this->isMariaDb() ? ['mariadb-dump', 'mysqldump'] : ['mysqldump']);
foreach ($binaryNames as $binaryName) {
$path = $this->executableFinder->find($binaryName);
if ($path !== null) {
return $path;
}
}
throw DumpBinaryNotFoundException::create($binaryNames);
}
/**
* @return list<string> client-specific flags for the located binary
*/
public function extraArguments(string $binary): array
{
$version = new Process([$binary, '--version']);
$version->run();
return MySqlVariant::needsColumnStatisticsOff($version->getOutput(), $this->isMariaDb())
? ['--column-statistics=0']
: [];
}
private function isMariaDb(): bool
{
// Connection::getServerVersion() is private in the DBAL version this
// repo pins against — SELECT VERSION() is the stable public way to get
// the same string.
return MySqlVariant::isMariaDb((string) $this->connection->fetchOne('SELECT VERSION()'));
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service;
/**
* Dumps are named dump_YYYY-MM-DD_HH-mm-ss.sql.gz — lexicographically sortable,
* and the filename is the single source of truth for a dump's datetime (not
* filesystem mtime, which can drift across copies/touches).
*/
class DumpFilenameParser
{
private const PATTERN = '/^dump_(\d{4}-\d{2}-\d{2})_(\d{2}-\d{2}-\d{2})\.sql\.gz$/';
public function format(\DateTimeImmutable $dateTime): string
{
return 'dump_' . $dateTime->format('Y-m-d_H-i-s') . '.sql.gz';
}
public function parse(string $filename): ?\DateTimeImmutable
{
if (preg_match(self::PATTERN, $filename, $matches) !== 1) {
return null;
}
$dateTime = \DateTimeImmutable::createFromFormat(
'Y-m-d_H-i-s',
$matches[1] . '_' . $matches[2]
);
return $dateTime ?: null;
}
public function isValid(string $filename): bool
{
return $this->parse($filename) !== null;
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Uuid\Uuid;
/**
* Owns the aeon_dump_manager_job table. Shopware core has no generic
* async-job-status framework to hook into (confirmed against core's own
* Import/Export source) — this mirrors that pattern with a small dedicated table.
*/
class DumpJobStatusService
{
public function __construct(private readonly Connection $connection)
{
}
public function createPending(): string
{
$id = Uuid::randomBytes();
$this->connection->insert('aeon_dump_manager_job', [
'id' => $id,
'status' => 'pending',
'created_at' => (new \DateTimeImmutable())->format('Y-m-d H:i:s.v'),
]);
return Uuid::fromBytesToHex($id);
}
public function markRunning(string $jobId): void
{
$this->update($jobId, ['status' => 'running']);
}
public function updateProgress(string $jobId, int $percent): void
{
$this->update($jobId, ['percent' => min(99, max(0, $percent))]);
}
public function markDone(string $jobId, string $filename): void
{
$this->update($jobId, ['status' => 'done', 'percent' => 100, 'filename' => $filename]);
}
public function markFailed(string $jobId, string $errorMessage): void
{
$this->update($jobId, ['status' => 'failed', 'error_message' => $errorMessage]);
}
/**
* @return array{id: string, status: string, percent: ?int, filename: ?string, errorMessage: ?string}|null
*/
public function find(string $jobId): ?array
{
$row = $this->connection->fetchAssociative(
'SELECT LOWER(HEX(id)) AS id, status, percent, filename, error_message FROM aeon_dump_manager_job WHERE id = :id',
['id' => Uuid::fromHexToBytes($jobId)]
);
if ($row === false) {
return null;
}
return [
'id' => $row['id'],
'status' => $row['status'],
'percent' => $row['percent'] !== null ? (int) $row['percent'] : null,
'filename' => $row['filename'],
'errorMessage' => $row['error_message'],
];
}
public function purgeOlderThan(\DateTimeImmutable $threshold): void
{
$this->connection->executeStatement(
'DELETE FROM aeon_dump_manager_job WHERE created_at < :threshold',
['threshold' => $threshold->format('Y-m-d H:i:s.v')]
);
}
private function update(string $jobId, array $data): void
{
$data['updated_at'] = (new \DateTimeImmutable())->format('Y-m-d H:i:s.v');
$this->connection->update('aeon_dump_manager_job', $data, ['id' => Uuid::fromHexToBytes($jobId)]);
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service;
use AeonDumpManager\Struct\DumpFile;
use League\Flysystem\FilesystemOperator;
class DumpLister
{
private const DUMP_DIRECTORY = 'dumps';
public function __construct(
private readonly FilesystemOperator $aeonDumpManagerFilesystemPrivate,
private readonly DumpFilenameParser $filenameParser,
) {
}
/**
* @return DumpFile[] newest first
*/
public function list(?\DateTimeImmutable $from = null, ?\DateTimeImmutable $to = null): array
{
$dumps = [];
foreach ($this->aeonDumpManagerFilesystemPrivate->listContents(self::DUMP_DIRECTORY) as $item) {
if (!$item->isFile()) {
continue;
}
$filename = basename($item->path());
$datetime = $this->filenameParser->parse($filename);
if ($datetime === null) {
continue;
}
if ($from !== null && $datetime < $from) {
continue;
}
if ($to !== null && $datetime > $to) {
continue;
}
$dumps[] = new DumpFile($filename, $datetime, $item->fileSize());
}
usort($dumps, static fn (DumpFile $a, DumpFile $b) => $b->datetime <=> $a->datetime ?: $b->filename <=> $a->filename);
return $dumps;
}
public static function path(string $filename): string
{
return self::DUMP_DIRECTORY . '/' . $filename;
}
}
+197
View File
@@ -0,0 +1,197 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service;
use AeonDumpManager\Service\Exception\DumpNotFoundException;
use AeonDumpManager\Struct\DumpFile;
use Doctrine\DBAL\Connection;
use League\Flysystem\FilesystemOperator;
use Psr\Log\LoggerInterface;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
/**
* Orchestrates dump create/delete — the single entry point every caller
* (console commands, the async Messenger handler, the retention task) goes
* through, so maxDumps/retantionDays enforcement only lives in one place.
*/
class DumpService
{
public function __construct(
private readonly DumpLister $dumpLister,
private readonly FilesystemOperator $aeonDumpManagerFilesystemPrivate,
private readonly DumpBinaryLocator $dumpBinaryLocator,
private readonly Connection $connection,
private readonly SystemConfigService $systemConfigService,
private readonly DumpFilenameParser $filenameParser,
private readonly LoggerInterface $logger,
) {
}
public function createSync(): DumpFile
{
$dumpFile = $this->create();
$this->enforceMaxDumps();
return $dumpFile;
}
public function createAsync(string $jobId, DumpJobStatusService $jobStatus): void
{
$estimatedTotalBytes = $this->estimateTotalBytes();
$lastUpdate = 0.0;
$dumpFile = $this->create(function (int $bytesWritten) use ($jobStatus, $jobId, $estimatedTotalBytes, &$lastUpdate): void {
$now = microtime(true);
if ($now - $lastUpdate < 1.0) {
return;
}
$lastUpdate = $now;
$percent = $estimatedTotalBytes > 0
? (int) min(99, ($bytesWritten / $estimatedTotalBytes) * 100)
: 0;
$jobStatus->updateProgress($jobId, $percent);
});
$jobStatus->markDone($jobId, $dumpFile->filename);
$this->enforceMaxDumps();
}
public function delete(string $filename): void
{
if (!$this->filenameParser->isValid($filename)) {
throw DumpNotFoundException::create($filename);
}
$path = DumpLister::path($filename);
if (!$this->aeonDumpManagerFilesystemPrivate->fileExists($path)) {
throw DumpNotFoundException::create($filename);
}
$this->aeonDumpManagerFilesystemPrivate->delete($path);
$this->logger->info('Dump deleted.', ['filename' => $filename]);
}
/**
* @return resource
*/
public function readStream(string $filename)
{
if (!$this->filenameParser->isValid($filename)) {
throw DumpNotFoundException::create($filename);
}
$path = DumpLister::path($filename);
if (!$this->aeonDumpManagerFilesystemPrivate->fileExists($path)) {
throw DumpNotFoundException::create($filename);
}
return $this->aeonDumpManagerFilesystemPrivate->readStream($path);
}
public function enforceMaxDumps(): void
{
$maxDumps = $this->systemConfigService->getInt('AeonDumpManager.config.maxDumps');
if ($maxDumps <= 0) {
return;
}
$dumps = $this->dumpLister->list(); // newest first
$excess = \array_slice($dumps, $maxDumps);
foreach ($excess as $dumpFile) {
$this->aeonDumpManagerFilesystemPrivate->delete(DumpLister::path($dumpFile->filename));
$this->logger->info('Dump removed: maxDumps exceeded.', ['filename' => $dumpFile->filename]);
}
}
public function purgeOlderThan(\DateTimeImmutable $threshold): void
{
foreach ($this->dumpLister->list() as $dumpFile) {
if ($dumpFile->datetime < $threshold) {
$this->aeonDumpManagerFilesystemPrivate->delete(DumpLister::path($dumpFile->filename));
$this->logger->info('Dump removed: older than retention.', ['filename' => $dumpFile->filename]);
}
}
}
/**
* @param (callable(int $bytesWritten): void)|null $onProgress
*/
private function create(?callable $onProgress = null): DumpFile
{
$dateTime = new \DateTimeImmutable();
$filename = $this->filenameParser->format($dateTime);
$tempPath = sys_get_temp_dir() . '/' . uniqid('aeon_dump_', true) . '.sql.gz';
$process = $this->buildProcess();
$gzHandle = gzopen($tempPath, 'wb6');
try {
$process->run(function (string $type, string $buffer) use ($gzHandle, $onProgress, $tempPath): void {
if ($type !== Process::OUT) {
return;
}
gzwrite($gzHandle, $buffer);
if ($onProgress !== null) {
clearstatcache(true, $tempPath);
$onProgress((int) filesize($tempPath));
}
});
} finally {
gzclose($gzHandle);
}
if (!$process->isSuccessful()) {
@unlink($tempPath);
$this->logger->error('Dump process failed.', ['exitCode' => $process->getExitCode()]);
throw new ProcessFailedException($process);
}
$sizeBytes = (int) filesize($tempPath);
$stream = fopen($tempPath, 'rb');
$this->aeonDumpManagerFilesystemPrivate->writeStream(DumpLister::path($filename), $stream);
fclose($stream);
@unlink($tempPath);
$this->logger->info('Dump created.', ['filename' => $filename, 'sizeBytes' => $sizeBytes]);
return new DumpFile($filename, $dateTime, $sizeBytes);
}
private function buildProcess(): Process
{
$binary = $this->dumpBinaryLocator->locate();
$params = $this->connection->getParams();
$command = [
$binary,
'--single-transaction',
'--quick',
...$this->dumpBinaryLocator->extraArguments($binary),
'-h', (string) ($params['host'] ?? '127.0.0.1'),
'-P', (string) ($params['port'] ?? 3306),
'-u', (string) ($params['user'] ?? 'root'),
(string) ($params['dbname'] ?? ''),
];
$process = new Process($command, null, ['MYSQL_PWD' => (string) ($params['password'] ?? '')]);
$process->setTimeout(null);
return $process;
}
private function estimateTotalBytes(): int
{
$bytes = $this->connection->fetchOne(
'SELECT SUM(data_length) FROM information_schema.tables WHERE table_schema = DATABASE()'
);
return (int) ($bytes ?? 0);
}
}
@@ -0,0 +1,16 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service\Exception;
use RuntimeException;
class DumpBinaryNotFoundException extends RuntimeException
{
public static function create(array $searched): self
{
return new self(sprintf(
'Could not find a dump binary. Searched for: %s. Configure "dumpBinaryPath" in the plugin settings to point at one explicitly.',
implode(', ', $searched)
));
}
}
@@ -0,0 +1,13 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service\Exception;
use RuntimeException;
class DumpNotFoundException extends RuntimeException
{
public static function create(string $filename): self
{
return new self(sprintf('Dump "%s" does not exist.', $filename));
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Service;
/**
* Pure version-string check, split out of DumpBinaryLocator so it's
* unit-testable without a live Shopware kernel/DB connection. Mirrors
* Doctrine DBAL's own AbstractMySQLDriver::createDatabasePlatformForVersion()
* check — the stable, version-portable way to tell MariaDB from MySQL.
*/
class MySqlVariant
{
public static function isMariaDb(string $serverVersion): bool
{
return stripos($serverVersion, 'mariadb') !== false;
}
/**
* MySQL 8+ mysqldump queries information_schema.COLUMN_STATISTICS, which
* MariaDB lacks (error 1109); --column-statistics=0 skips it. MariaDB's own
* client (version string contains "MariaDB") and MySQL < 8 don't know the flag.
*/
public static function needsColumnStatisticsOff(string $clientVersion, bool $serverIsMariaDb): bool
{
return $serverIsMariaDb
&& !self::isMariaDb($clientVersion)
// MySQL < 8 prints "Ver 10.13 Distrib 5.7.x": the Distrib number is the real version.
&& (preg_match('/Distrib (\d+)\./', $clientVersion, $m) === 1 || preg_match('/\bVer (\d+)\./', $clientVersion, $m) === 1)
&& (int) $m[1] >= 8;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Struct;
/**
* A dump on disk. Not a DAL entity — dumps are plain files in the plugin's
* private Flysystem mount, identified by their filename.
*/
final class DumpFile
{
public function __construct(
public readonly string $filename,
public readonly \DateTimeImmutable $datetime,
public readonly int $sizeBytes,
) {
}
/**
* @return array{filename: string, datetime: string, sizeBytes: int}
*/
public function jsonSerialize(): array
{
return [
'filename' => $this->filename,
'datetime' => $this->datetime->format(DATE_ATOM),
'sizeBytes' => $this->sizeBytes,
];
}
}
@@ -0,0 +1,46 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Tests\MessageQueue\Handler;
use AeonDumpManager\MessageQueue\Handler\CreateDumpHandler;
use AeonDumpManager\MessageQueue\Message\CreateDumpMessage;
use AeonDumpManager\Service\DumpJobStatusService;
use AeonDumpManager\Service\DumpService;
use AeonDumpManager\Tests\Support\RecordingLogger;
use PHPUnit\Framework\TestCase;
class CreateDumpHandlerTest extends TestCase
{
public function testLogsStartOnSuccess(): void
{
$status = $this->createMock(DumpJobStatusService::class);
$status->expects(self::once())->method('markRunning')->with('job-1');
$status->expects(self::never())->method('markFailed');
$logger = new RecordingLogger();
(new CreateDumpHandler($this->createMock(DumpService::class), $status, $logger))(new CreateDumpMessage('job-1'));
self::assertCount(1, $logger->records);
self::assertSame('info', $logger->records[0]['level']);
self::assertSame('Dump job started.', $logger->records[0]['message']);
self::assertSame(['jobId' => 'job-1'], $logger->records[0]['context']);
}
public function testLogsErrorAndMarksFailedWhenCreateThrows(): void
{
$exception = new \RuntimeException('boom');
$service = $this->createMock(DumpService::class);
$service->method('createAsync')->willThrowException($exception);
$status = $this->createMock(DumpJobStatusService::class);
$status->expects(self::once())->method('markFailed')->with('job-2', 'boom');
$logger = new RecordingLogger();
(new CreateDumpHandler($service, $status, $logger))(new CreateDumpMessage('job-2'));
self::assertCount(2, $logger->records);
self::assertSame('error', $logger->records[1]['level']);
self::assertSame('Dump job failed.', $logger->records[1]['message']);
self::assertSame('job-2', $logger->records[1]['context']['jobId']);
self::assertSame($exception, $logger->records[1]['context']['exception']);
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Tests\Service;
use AeonDumpManager\Service\DumpFilenameParser;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class DumpFilenameParserTest extends TestCase
{
private DumpFilenameParser $parser;
protected function setUp(): void
{
$this->parser = new DumpFilenameParser();
}
public function testFormatProducesExpectedPattern(): void
{
$dateTime = new \DateTimeImmutable('2026-09-14 15:04:05');
self::assertSame('dump_2026-09-14_15-04-05.sql.gz', $this->parser->format($dateTime));
}
public function testParseRoundTripsWithFormat(): void
{
$dateTime = new \DateTimeImmutable('2026-09-14 15:04:05');
$filename = $this->parser->format($dateTime);
self::assertEquals($dateTime, $this->parser->parse($filename));
}
#[DataProvider('invalidFilenameProvider')]
public function testParseRejectsInvalidFilenames(string $filename): void
{
self::assertNull($this->parser->parse($filename));
}
public static function invalidFilenameProvider(): iterable
{
yield 'wrong extension' => ['dump_2026-09-14_15-04-05.sql'];
yield 'no prefix' => ['2026-09-14_15-04-05.sql.gz'];
yield 'path traversal' => ['../dump_2026-09-14_15-04-05.sql.gz'];
yield 'garbage' => ['not-a-dump.sql.gz'];
yield 'empty' => [''];
}
public function testIsValid(): void
{
self::assertTrue($this->parser->isValid('dump_2026-09-14_15-04-05.sql.gz'));
self::assertFalse($this->parser->isValid('../etc/passwd'));
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Tests\Service;
use AeonDumpManager\Service\DumpBinaryLocator;
use AeonDumpManager\Service\DumpFilenameParser;
use AeonDumpManager\Service\DumpLister;
use AeonDumpManager\Service\DumpService;
use AeonDumpManager\Service\Exception\DumpNotFoundException;
use AeonDumpManager\Tests\Support\RecordingLogger;
use Doctrine\DBAL\Connection;
use League\Flysystem\FilesystemOperator;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Shopware\Core\System\SystemConfig\SystemConfigService;
class DumpServiceLoggingTest extends TestCase
{
private const FILENAME = 'dump_2026-09-14_15-04-05.sql.gz';
private FilesystemOperator&MockObject $filesystem;
private RecordingLogger $logger;
private DumpService $service;
protected function setUp(): void
{
$this->filesystem = $this->createMock(FilesystemOperator::class);
$this->logger = new RecordingLogger();
$this->service = new DumpService(
$this->createMock(DumpLister::class),
$this->filesystem,
$this->createMock(DumpBinaryLocator::class),
$this->createMock(Connection::class),
$this->createMock(SystemConfigService::class),
new DumpFilenameParser(),
$this->logger,
);
}
public function testDeleteLogsInfo(): void
{
$this->filesystem->method('fileExists')->willReturn(true);
$this->filesystem->expects(self::once())->method('delete')->with(DumpLister::path(self::FILENAME));
$this->service->delete(self::FILENAME);
self::assertSame(
[['level' => 'info', 'message' => 'Dump deleted.', 'context' => ['filename' => self::FILENAME]]],
$this->logger->records
);
}
public function testDeleteMissingDumpDoesNotLog(): void
{
$this->filesystem->method('fileExists')->willReturn(false);
try {
$this->service->delete(self::FILENAME);
self::fail('Expected DumpNotFoundException.');
} catch (DumpNotFoundException) {
self::assertSame([], $this->logger->records);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Tests\Service;
use AeonDumpManager\Service\MySqlVariant;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class MySqlVariantTest extends TestCase
{
#[DataProvider('versionProvider')]
public function testIsMariaDb(string $version, bool $expected): void
{
self::assertSame($expected, MySqlVariant::isMariaDb($version));
}
public static function versionProvider(): iterable
{
yield 'plain mysql' => ['8.0.36', false];
yield 'mariadb with legacy prefix' => ['5.5.5-10.11.2-MariaDB', true];
yield 'mariadb without legacy prefix' => ['10.11.2-MariaDB', true];
yield 'mariadb lowercase' => ['10.11.2-mariadb', true];
}
#[DataProvider('columnStatisticsProvider')]
public function testNeedsColumnStatisticsOff(string $clientVersion, bool $serverIsMariaDb, bool $expected): void
{
self::assertSame($expected, MySqlVariant::needsColumnStatisticsOff($clientVersion, $serverIsMariaDb));
}
public static function columnStatisticsProvider(): iterable
{
$mysql8 = 'mysqldump Ver 8.0.46-0ubuntu0.24.04.4 for Linux on x86_64 ((Ubuntu))';
yield 'mysql 8 client, mariadb server' => [$mysql8, true, true];
yield 'mysql 8 client, mysql server' => [$mysql8, false, false];
yield 'mysql 5.7 client, mariadb server' => ['mysqldump Ver 10.13 Distrib 5.7.44, for Linux (x86_64)', true, false];
yield 'mariadb client, mariadb server' => ['mariadb-dump from 11.4.2-MariaDB, client 10.19 for debian-linux-gnu (x86_64)', true, false];
yield 'mariadb legacy mysqldump name' => ['mysqldump Ver 10.19 Distrib 10.11.6-MariaDB, for debian-linux-gnu (x86_64)', true, false];
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php declare(strict_types=1);
namespace AeonDumpManager\Tests\Support;
use Psr\Log\AbstractLogger;
class RecordingLogger extends AbstractLogger
{
/** @var list<array{level: string, message: string, context: array<mixed>}> */
public array $records = [];
public function log($level, string|\Stringable $message, array $context = []): void
{
$this->records[] = ['level' => (string) $level, 'message' => (string) $message, 'context' => $context];
}
}
Regular → Executable
View File
File mode changed.