Compare commits
39
Commits
f5ff279b7b
..
v0.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec5c40c9f2 | ||
|
|
56ada0cedc | ||
|
|
f50154b96b | ||
|
|
7aa11b0396 | ||
|
|
161c35dc8a | ||
|
|
a1f0160ab9 | ||
|
|
1ee83aad37 | ||
|
|
b2c2a8d80b | ||
|
|
31b9e61adb | ||
|
|
5a482b49bb | ||
|
|
6094b6f49c | ||
|
|
e5c3a5b28f | ||
|
|
f967ef7544 | ||
|
|
20492e8c80 | ||
|
|
2c7a105332 | ||
|
|
0401859227 | ||
|
|
2683792fee | ||
|
|
29abb1cd59 | ||
|
|
05e1d0eeb9 | ||
|
|
59e48c8f21 | ||
|
|
b89a878b92 | ||
|
|
9713f9f780 | ||
|
|
3a7bcee096 | ||
|
|
0b71a62d40 | ||
|
|
92f8605dd0 | ||
|
|
1d8d2de118 | ||
|
|
b66bc550cd | ||
|
|
a21b5aa73e | ||
|
|
86069a51a3 | ||
|
|
0188a24278 | ||
|
|
309cdf3f09 | ||
|
|
f982c3c3da | ||
|
|
44e7648e06 | ||
|
|
d0e8ea582f | ||
|
|
957588d0b1 | ||
|
|
b4e84d0570 | ||
|
|
0dc19897a4 | ||
|
|
e8121c701f | ||
|
|
21d1f9f465 |
@@ -0,0 +1,40 @@
|
||||
name: version-changelog
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
version-changelog:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check version bump and changelog entry
|
||||
run: |
|
||||
set -e
|
||||
PR_VERSION=$(grep -m1 '"version"' composer.json | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
|
||||
MAIN_VERSION=$(git show origin/main:composer.json | grep -m1 '"version"' | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
|
||||
|
||||
echo "main version: $MAIN_VERSION"
|
||||
echo "PR version: $PR_VERSION"
|
||||
|
||||
if [ "$MAIN_VERSION" = "$PR_VERSION" ]; then
|
||||
echo "::error::composer.json version ($PR_VERSION) was not bumped from main ($MAIN_VERSION)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
HIGHEST=$(printf '%s\n%s\n' "$MAIN_VERSION" "$PR_VERSION" | sort -V | tail -n1)
|
||||
if [ "$HIGHEST" != "$PR_VERSION" ]; then
|
||||
echo "::error::composer.json version ($PR_VERSION) is not greater than main's ($MAIN_VERSION)"
|
||||
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: version bumped to $PR_VERSION and documented in CHANGELOG.md"
|
||||
@@ -0,0 +1,100 @@
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
SERVER_URL: https://git.arthurerlich.de
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.RELEASE_TOKEN }}
|
||||
|
||||
- name: Determine version and guard against re-release
|
||||
id: version
|
||||
run: |
|
||||
set -e
|
||||
VERSION=$(grep -m1 '"version"' composer.json | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
|
||||
TAG="v${VERSION}"
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||
if git ls-remote --tags origin "refs/tags/${TAG}" | grep -q "${TAG}"; then
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
echo "Tag ${TAG} already exists, nothing to release."
|
||||
else
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Extract changelog section
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
run: |
|
||||
awk -v ver="${{ steps.version.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 and push tag
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
run: |
|
||||
git config user.name "gitea-actions"
|
||||
git config user.email "actions@git.arthurerlich.de"
|
||||
git tag "${{ steps.version.outputs.tag }}"
|
||||
git push origin "${{ steps.version.outputs.tag }}"
|
||||
|
||||
- name: Install shopware-cli
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
run: |
|
||||
curl -sL -o /tmp/shopware-cli.tar.gz \
|
||||
https://github.com/shopware/shopware-cli/releases/latest/download/shopware-cli_Linux_x86_64.tar.gz
|
||||
mkdir -p /tmp/swcli-extract
|
||||
tar -xzf /tmp/shopware-cli.tar.gz -C /tmp/swcli-extract
|
||||
cp /tmp/swcli-extract/shopware-cli /usr/local/bin/shopware-cli
|
||||
|
||||
- name: Validate extension (informational only, does not gate the release)
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
run: shopware-cli extension validate . || true
|
||||
|
||||
- name: Package Store-style zip for the Gitea Release asset
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
run: |
|
||||
shopware-cli extension package . --output-directory .build \
|
||||
--filename "AeonDumpManager-${{ steps.version.outputs.tag }}.zip"
|
||||
|
||||
- name: Build root-level zip for the Composer registry
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
run: git archive --format=zip -o "composer-package-${{ steps.version.outputs.tag }}.zip" "${{ steps.version.outputs.tag }}"
|
||||
|
||||
- name: Create Gitea Release
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
uses: akkuman/gitea-release-action@v1
|
||||
with:
|
||||
server_url: ${{ env.SERVER_URL }}
|
||||
token: ${{ secrets.RELEASE_TOKEN }}
|
||||
tag_name: ${{ steps.version.outputs.tag }}
|
||||
name: ${{ steps.version.outputs.tag }}
|
||||
body_path: release-notes.md
|
||||
files: .build/AeonDumpManager-${{ steps.version.outputs.tag }}.zip
|
||||
|
||||
- name: Publish to Composer registry
|
||||
if: steps.version.outputs.skip == 'false'
|
||||
run: |
|
||||
STATUS=$(curl -s -o /tmp/composer-publish.log -w "%{http_code}" \
|
||||
-u "haylan:${{ secrets.RELEASE_TOKEN }}" \
|
||||
-T "composer-package-${{ steps.version.outputs.tag }}.zip" \
|
||||
"https://git.arthurerlich.de/api/packages/haylan/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
|
||||
Regular → Executable
+6
@@ -12,6 +12,11 @@ composer.phar
|
||||
/custom/
|
||||
/src/Shopware/Platform
|
||||
|
||||
# Frontend
|
||||
*.vite/
|
||||
**/public/administration/js/
|
||||
**/public/static/js/
|
||||
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
@@ -22,6 +27,7 @@ composer.phar
|
||||
/.claude/
|
||||
/.qwen/
|
||||
/.opencode/
|
||||
/.scratch/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# 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.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.
|
||||
@@ -0,0 +1,72 @@
|
||||
# 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.xml` (Symfony DI, XML 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), currently just the `swag-example` scaffold module.
|
||||
|
||||
## 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.
|
||||
|
||||
```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.1`, `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/`.
|
||||
|
||||
## Adding functionality
|
||||
|
||||
- New console commands go in `src/Command/`, new scheduled tasks in `src/ScheduledTask/` — both must
|
||||
be registered in `src/Resources/config/services.xml` 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.
|
||||
Regular → Executable
+1
-1
@@ -3,7 +3,7 @@
|
||||
"description": "Export database dumps for Shopware 6 environments.",
|
||||
"type": "shopware-platform-plugin",
|
||||
"license": "MIT",
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.3",
|
||||
"keywords": [
|
||||
"shopware",
|
||||
"shopware6",
|
||||
|
||||
Executable
+31
@@ -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:
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
Regular → Executable
Regular → Executable
Regular → Executable
+4
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace AeonDumpManager;
|
||||
|
||||
use Doctrine\DBAL\Connection;
|
||||
use Shopware\Core\Framework\Plugin;
|
||||
use Shopware\Core\Framework\Plugin\Context\ActivateContext;
|
||||
use Shopware\Core\Framework\Plugin\Context\DeactivateContext;
|
||||
@@ -24,7 +25,9 @@ class AeonDumpManager extends Plugin
|
||||
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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,30 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace AeonDumpManager\MessageQueue\Handler;
|
||||
|
||||
use AeonDumpManager\MessageQueue\Message\CreateDumpMessage;
|
||||
use AeonDumpManager\Service\DumpJobStatusService;
|
||||
use AeonDumpManager\Service\DumpService;
|
||||
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
|
||||
|
||||
#[AsMessageHandler]
|
||||
class CreateDumpHandler
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DumpService $dumpService,
|
||||
private readonly DumpJobStatusService $jobStatus,
|
||||
) {
|
||||
}
|
||||
|
||||
public function __invoke(CreateDumpMessage $message): void
|
||||
{
|
||||
$jobId = $message->getJobId();
|
||||
$this->jobStatus->markRunning($jobId);
|
||||
|
||||
try {
|
||||
$this->dumpService->createAsync($jobId, $this->jobStatus);
|
||||
} catch (\Throwable $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
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
Executable
+8
@@ -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',
|
||||
},
|
||||
});
|
||||
+124
@@ -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 %}
|
||||
+289
@@ -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
@@ -6,16 +6,20 @@
|
||||
<card>
|
||||
<title>Minimal configuration</title>
|
||||
|
||||
<input-field type="number">
|
||||
<input-field type="int">
|
||||
<name>maxDumps</name>
|
||||
<label>Maximum allowed dumps to exist</label>
|
||||
<defaultValue>6</defaultValue>
|
||||
</input-field>
|
||||
<input-field type="number">
|
||||
<input-field type="int">
|
||||
<name>retantionDays</name>
|
||||
<label>How many Days the dumps kept in the Storage. 0 Means unlimited</label>
|
||||
<defaultValue>0</defaultValue>
|
||||
</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>
|
||||
|
||||
</config>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
|
||||
|
||||
return function (RoutingConfigurator $routes): void {
|
||||
$routes->import(__DIR__ . '/../../Controller/*Controller.php', 'attribute');
|
||||
};
|
||||
Regular → Executable
+73
-3
@@ -5,13 +5,83 @@
|
||||
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
|
||||
|
||||
<services>
|
||||
<!-- Services -->
|
||||
|
||||
<service id="AeonDumpManager\Command\ExampleCommand">
|
||||
<service id="Symfony\Component\Process\ExecutableFinder"/>
|
||||
|
||||
<service id="aeon_dump_manager.dump_filename_parser" class="AeonDumpManager\Service\DumpFilenameParser"/>
|
||||
|
||||
<service id="aeon_dump_manager.dump_binary_locator" class="AeonDumpManager\Service\DumpBinaryLocator">
|
||||
<argument type="service" id="Doctrine\DBAL\Connection"/>
|
||||
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
|
||||
<argument type="service" id="Symfony\Component\Process\ExecutableFinder"/>
|
||||
</service>
|
||||
|
||||
<service id="aeon_dump_manager.dump_job_status_service" class="AeonDumpManager\Service\DumpJobStatusService">
|
||||
<argument type="service" id="Doctrine\DBAL\Connection"/>
|
||||
</service>
|
||||
|
||||
<service id="aeon_dump_manager.dump_lister" class="AeonDumpManager\Service\DumpLister">
|
||||
<argument type="service" id="aeon_dump_manager.filesystem.private"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_filename_parser"/>
|
||||
</service>
|
||||
|
||||
<service id="aeon_dump_manager.dump_service" class="AeonDumpManager\Service\DumpService">
|
||||
<argument type="service" id="aeon_dump_manager.dump_lister"/>
|
||||
<argument type="service" id="aeon_dump_manager.filesystem.private"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_binary_locator"/>
|
||||
<argument type="service" id="Doctrine\DBAL\Connection"/>
|
||||
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_filename_parser"/>
|
||||
</service>
|
||||
|
||||
<!-- Async create job -->
|
||||
|
||||
<service id="aeon_dump_manager.message_queue.create_dump_handler" class="AeonDumpManager\MessageQueue\Handler\CreateDumpHandler">
|
||||
<argument type="service" id="aeon_dump_manager.dump_service"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_job_status_service"/>
|
||||
<tag name="messenger.message_handler"/>
|
||||
</service>
|
||||
|
||||
<!-- Retention -->
|
||||
|
||||
<service id="aeon_dump_manager.scheduled_task.purge_dumps_task" class="AeonDumpManager\ScheduledTask\PurgeDumpsTask">
|
||||
<tag name="shopware.scheduled.task"/>
|
||||
</service>
|
||||
|
||||
<service id="aeon_dump_manager.scheduled_task.purge_dumps_task_handler" class="AeonDumpManager\ScheduledTask\PurgeDumpsTaskHandler">
|
||||
<argument type="service" id="scheduled_task.repository"/>
|
||||
<argument type="service" id="logger"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_service"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_job_status_service"/>
|
||||
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
|
||||
<tag name="messenger.message_handler" handles="AeonDumpManager\ScheduledTask\PurgeDumpsTask"/>
|
||||
</service>
|
||||
|
||||
<!-- Console commands -->
|
||||
|
||||
<service id="aeon_dump_manager.command.dump_list" class="AeonDumpManager\Command\DumpListCommand">
|
||||
<argument type="service" id="aeon_dump_manager.dump_lister"/>
|
||||
<tag name="console.command"/>
|
||||
</service>
|
||||
|
||||
<service id="AeonDumpManager\ScheduledTask\ExampleTask">
|
||||
<tag name="shopware.scheduled.task"/>
|
||||
<service id="aeon_dump_manager.command.dump_create" class="AeonDumpManager\Command\DumpCreateCommand">
|
||||
<argument type="service" id="aeon_dump_manager.dump_service"/>
|
||||
<tag name="console.command"/>
|
||||
</service>
|
||||
|
||||
<service id="aeon_dump_manager.command.dump_remove" class="AeonDumpManager\Command\DumpRemoveCommand">
|
||||
<argument type="service" id="aeon_dump_manager.dump_service"/>
|
||||
<tag name="console.command"/>
|
||||
</service>
|
||||
|
||||
<!-- Admin API controller -->
|
||||
|
||||
<service id="AeonDumpManager\Controller\DumpController" public="true">
|
||||
<argument type="service" id="aeon_dump_manager.dump_lister"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_service"/>
|
||||
<argument type="service" id="aeon_dump_manager.dump_job_status_service"/>
|
||||
<argument type="service" id="messenger.default_bus"/>
|
||||
</service>
|
||||
|
||||
</services>
|
||||
|
||||
@@ -4,15 +4,15 @@ namespace AeonDumpManager\ScheduledTask;
|
||||
|
||||
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTask;
|
||||
|
||||
class ExampleTask extends ScheduledTask
|
||||
class PurgeDumpsTask extends ScheduledTask
|
||||
{
|
||||
public static function getTaskName(): string
|
||||
{
|
||||
return 'swag.example_task';
|
||||
return 'aeon_dump_manager.purge_dumps_task';
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
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()'));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?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 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,
|
||||
) {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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));
|
||||
}
|
||||
}
|
||||
|
||||
public function purgeOlderThan(\DateTimeImmutable $threshold): void
|
||||
{
|
||||
foreach ($this->dumpLister->list() as $dumpFile) {
|
||||
if ($dumpFile->datetime < $threshold) {
|
||||
$this->aeonDumpManagerFilesystemPrivate->delete(DumpLister::path($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);
|
||||
|
||||
throw new ProcessFailedException($process);
|
||||
}
|
||||
|
||||
$sizeBytes = (int) filesize($tempPath);
|
||||
$stream = fopen($tempPath, 'rb');
|
||||
$this->aeonDumpManagerFilesystemPrivate->writeStream(DumpLister::path($filename), $stream);
|
||||
fclose($stream);
|
||||
@unlink($tempPath);
|
||||
|
||||
return new DumpFile($filename, $dateTime, $sizeBytes);
|
||||
}
|
||||
|
||||
private function buildProcess(): Process
|
||||
{
|
||||
$binary = $this->dumpBinaryLocator->locate();
|
||||
$params = $this->connection->getParams();
|
||||
|
||||
$command = [
|
||||
$binary,
|
||||
'--single-transaction',
|
||||
'--quick',
|
||||
'-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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -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,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'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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];
|
||||
}
|
||||
}
|
||||
Regular → Executable
Reference in New Issue
Block a user