From 5744e7dc6c64aa4324b496303ea5ba64e735b346 Mon Sep 17 00:00:00 2001 From: GitHub Actions Bot <> Date: Fri, 8 Nov 2024 06:25:48 +0000 Subject: [PATCH] Build release --- .github/chainguard/prepare_release.sts.yaml | 7 - .github/chainguard/translations.sts.yaml | 7 - .github/workflows/admin.yml | 30 -- .github/workflows/build.yml | 12 - .github/workflows/php.yml | 34 -- .github/workflows/prepare_release.yml | 57 --- .github/workflows/store-release.yml | 16 - .github/workflows/translations.yml | 54 --- .gitignore | 22 -- CHANGELOG_en-GB.md | 3 + Makefile | 60 ---- phpunit.xml.dist | 27 -- psalm.xml | 50 --- .../administration/css/swag-language-pack.css | 3 + .../administration/js/swag-language-pack.js | 3 + .../SalesChannelDomainValidatorTest.php | 88 ----- .../SalesChannelLanguageValidatorTest.php | 54 --- .../Validation/SalesChannelValidatorTest.php | 91 ----- .../Write/Validation/UserValidatorTest.php | 83 ----- .../Command/SalesChannelCreateCommandTest.php | 153 --------- tests/Extension/LanguageExtensionTest.php | 54 --- tests/Helper/ServicesTrait.php | 84 ----- ...alesChannelCreateStorefrontCommandTest.php | 195 ----------- tests/SwagLanguagePackTest.php | 103 ------ tests/TestBootstrap.php | 25 -- .../Exception/LanguagePackExceptionTest.php | 44 --- tests/Util/Lifecycle/LifecycleTest.php | 83 ----- tests/Util/Migration/MigrationHelperTest.php | 325 ------------------ 28 files changed, 9 insertions(+), 1758 deletions(-) delete mode 100644 .github/chainguard/prepare_release.sts.yaml delete mode 100644 .github/chainguard/translations.sts.yaml delete mode 100644 .github/workflows/admin.yml delete mode 100644 .github/workflows/build.yml delete mode 100644 .github/workflows/php.yml delete mode 100644 .github/workflows/prepare_release.yml delete mode 100644 .github/workflows/store-release.yml delete mode 100644 .github/workflows/translations.yml delete mode 100644 .gitignore create mode 100755 CHANGELOG_en-GB.md delete mode 100644 Makefile delete mode 100644 phpunit.xml.dist delete mode 100644 psalm.xml create mode 100644 src/Resources/public/administration/css/swag-language-pack.css create mode 100644 src/Resources/public/administration/js/swag-language-pack.js delete mode 100644 tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelDomainValidatorTest.php delete mode 100644 tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelLanguageValidatorTest.php delete mode 100644 tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelValidatorTest.php delete mode 100644 tests/Core/Framework/DataAbstractionLayer/Write/Validation/UserValidatorTest.php delete mode 100644 tests/Core/System/SalesChannel/Command/SalesChannelCreateCommandTest.php delete mode 100644 tests/Extension/LanguageExtensionTest.php delete mode 100644 tests/Helper/ServicesTrait.php delete mode 100644 tests/Storefront/Framework/Command/SalesChannelCreateStorefrontCommandTest.php delete mode 100644 tests/SwagLanguagePackTest.php delete mode 100644 tests/TestBootstrap.php delete mode 100644 tests/Util/Exception/LanguagePackExceptionTest.php delete mode 100644 tests/Util/Lifecycle/LifecycleTest.php delete mode 100644 tests/Util/Migration/MigrationHelperTest.php diff --git a/.github/chainguard/prepare_release.sts.yaml b/.github/chainguard/prepare_release.sts.yaml deleted file mode 100644 index 754e7a4f..00000000 --- a/.github/chainguard/prepare_release.sts.yaml +++ /dev/null @@ -1,7 +0,0 @@ -issuer: https://token.actions.githubusercontent.com -subject_pattern: repo:shopware/SwagLanguagePack:.* -claim_pattern: - workflow_ref: shopware/SwagLanguagePack/.github/workflows/prepare_release.yml@.* - -permissions: - contents: write diff --git a/.github/chainguard/translations.sts.yaml b/.github/chainguard/translations.sts.yaml deleted file mode 100644 index 03051b39..00000000 --- a/.github/chainguard/translations.sts.yaml +++ /dev/null @@ -1,7 +0,0 @@ -issuer: https://token.actions.githubusercontent.com -subject_pattern: repo:shopware/SwagLanguagePack:.* -claim_pattern: - workflow_ref: shopware/SwagLanguagePack/.github/workflows/translations.yml@.* - -permissions: - contents: write diff --git a/.github/workflows/admin.yml b/.github/workflows/admin.yml deleted file mode 100644 index 63b50481..00000000 --- a/.github/workflows/admin.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Administration -on: - pull_request: - paths: - - '**/*.js' - - '**/*.ts' - - '**/*.html' - - '**/*.html.twig' - - .github/workflows/admin.yml - push: - paths: - - '**/*.js' - - '**/*.ts' - - '**/*.html' - - '**/*.html.twig' - branches: - - master - workflow_dispatch: - schedule: - - cron: '0 3 * * *' - -jobs: - unit: - uses: shopware/github-actions/.github/workflows/admin-jest.yml@main - with: - extensionName: ${{ github.event.repository.name }} - shopwareVersion: trunk - uploadCoverage: true - secrets: - codecovToken: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index 0e157fcd..00000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: Build -on: - pull_request: - push: - branches: - - master - -jobs: - build: - uses: shopware/github-actions/.github/workflows/build-zip.yml@main - with: - extensionName: ${{ github.event.repository.name }} diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml deleted file mode 100644 index 29b2d29a..00000000 --- a/.github/workflows/php.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: PHP -on: - pull_request: - paths: - - '**/*.php' - - .github/workflows/php.yml - push: - paths: - - '**/*.php' - branches: - - master - workflow_dispatch: - schedule: - - cron: '0 3 * * *' - -jobs: - cs: - if: github.event_name != 'schedule' - uses: shopware/github-actions/.github/workflows/cs-fixer.yml@main - - phpstan: - uses: shopware/github-actions/.github/workflows/phpstan.yml@main - with: - extensionName: ${{ github.event.repository.name }} - shopwareVersion: trunk - - phpunit: - uses: shopware/github-actions/.github/workflows/phpunit.yml@main - with: - extensionName: ${{ github.event.repository.name }} - shopwareVersion: trunk - uploadCoverage: true - secrets: - codecovToken: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/prepare_release.yml b/.github/workflows/prepare_release.yml deleted file mode 100644 index e27331dc..00000000 --- a/.github/workflows/prepare_release.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Prepare Release -on: - workflow_dispatch: - schedule: - # Every Friday at 06:15 AM UTC - - cron: "15 6 * * 5" - -permissions: - contents: read - id-token: write - -jobs: - prepare_release: - runs-on: ubuntu-latest - steps: - - uses: octo-sts/action@main - id: octo-sts - with: - scope: shopware/SwagLanguagePack - identity: prepare_release - - uses: actions/checkout@v4 - with: - token: ${{ steps.octo-sts.outputs.token }} - fetch-depth: 0 - - name: Check for changes - shell: bash - id: check-changes - run: | - if [[ -z $(git diff HEAD $(git describe --tags $(git rev-list --tags --max-count=1)) src/) ]]; then - echo "No changes detected" - echo "no_changes=1" >> "$GITHUB_OUTPUT" - fi - - name: Increase version - shell: bash - if: ${{ ! steps.check-changes.outputs.no_changes }} - run: | - version=$(jq -r '.version' composer.json) - regex="([0-9]+).([0-9]+).([0-9]+)" - if [[ $version =~ $regex ]]; then - major="${BASH_REMATCH[1]}" - minor="${BASH_REMATCH[2]}" - fi - new_version="${major}.$((minor+1)).0" - jq --arg version "$new_version" --indent 4 '.version = $version' composer.json > composer.json.tmp - mv composer.json.tmp composer.json - composer validate - echo "Old version: ${version}" - echo "New version: $(jq -r '.version' composer.json)" - - name: Push new version - if: ${{ ! steps.check-changes.outputs.no_changes }} - shell: bash - run: | - git config user.name shopwareBot - git config user.email development@shopware.com - git add . - git commit -m "Prepare release $(jq -r '.version' composer.json)" - git push diff --git a/.github/workflows/store-release.yml b/.github/workflows/store-release.yml deleted file mode 100644 index 5b08cc8b..00000000 --- a/.github/workflows/store-release.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Release to Store -on: - workflow_dispatch: - workflow_run: - workflows: ["Prepare Release"] - types: - - completed -jobs: - build: - uses: shopware/github-actions/.github/workflows/store-release.yml@main - with: - extensionName: ${{ github.event.repository.name }} - secrets: - accountUser: ${{ secrets.SHOPWARE_ACCOUNT_USER }} - accountPassword: ${{ secrets.SHOPWARE_ACCOUNT_PASSWORD }} - ghToken: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/translations.yml b/.github/workflows/translations.yml deleted file mode 100644 index e81b7b81..00000000 --- a/.github/workflows/translations.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: Translations -on: - push: - branches: - - master - workflow_dispatch: - schedule: - - cron: "0 3 * * *" - -permissions: - contents: read - id-token: write - -jobs: - update_translations: - runs-on: ubuntu-latest - - steps: - - name: Setup Shopware - uses: shopware/setup-shopware@main - with: - shopware-version: trunk - - - uses: octo-sts/action@main - id: octo-sts - with: - scope: shopware/SwagLanguagePack - identity: translations - - - name: Clone Extension - uses: actions/checkout@v4 - with: - path: custom/plugins/${{ github.event.repository.name }} - token: ${{ steps.octo-sts.outputs.token }} - - - name: Install extension with Composer - run: composer require $(composer -d custom/plugins/${{ github.event.repository.name }} config name) - - - name: Download translations - working-directory: custom/plugins/${{ github.event.repository.name }} - run: ./bin/download-translations.sh - - - name: Push translations - working-directory: custom/plugins/${{ github.event.repository.name }} - run: | - if [[ -z $(git status -s) ]]; then - echo "No changes detected" - exit 0 - fi - git config user.name shopwareBot - git config user.email development@shopware.com - git add ./src - git commit -m "Update translations $(date +%Y-%m-%d)" - git push diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 1877d363..00000000 --- a/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -.idea/ -coverage/ -.phpunit.result.cache -vendor/ -var/ -phpstan.neon -phpstan-report.json -composer.lock - -node_modules -/src/Resources/app/storefront/test/e2e/cypress/results/ -/src/Resources/app/storefront/test/app/ - -/src/Resources/app/administration/test/e2e/cypress/results/ -/src/Resources/app/administration/test/app/ - -/src/Resources/public/* -!/src/Resources/public/static -/src/Resources/public/static/* -!/src/Resources/public/static/flags/* - -/.php-cs-fixer.cache \ No newline at end of file diff --git a/CHANGELOG_en-GB.md b/CHANGELOG_en-GB.md new file mode 100755 index 00000000..68f4bf98 --- /dev/null +++ b/CHANGELOG_en-GB.md @@ -0,0 +1,3 @@ +# 4.14.0 +- [Update translations 2024-11-08](https://issues.shopware.com/issues/) +- [Update translations 2024-11-05](https://issues.shopware.com/issues/) \ No newline at end of file diff --git a/Makefile b/Makefile deleted file mode 100644 index 68b4f7a6..00000000 --- a/Makefile +++ /dev/null @@ -1,60 +0,0 @@ -.DEFAULT_GOAL := help - -help: - @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' -.PHONY: help - -init: ## Initialize shopware, install language pack, dump the test database - cd src/Resources/app/administration \ - && npm i \ - && cd ../../../../../../../ \ - && ./psh.phar init\ - && php bin/console plugin:install --activate -c SwagLanguagePack\ - && ./psh.phar init-test-databases\ - && ./psh.phar storefront:init\ - && ./psh.phar administration:init -.PHONY: init - -administration-fix: ## Run eslint on the administration files - ../../../vendor/shopware/platform/src/Administration/Resources/app/administration/node_modules/.bin/eslint --ignore-path .eslintignore --config ../../../vendor/shopware/platform/src/Administration/Resources/app/administration/.eslintrc.js --ext .js,.vue --fix src/Resources/app/administration -.PHONY: administration-fix - -administration-lint: ## Run eslint on the administration files - ../../../vendor/shopware/platform/src/Administration/Resources/app/administration/node_modules/.bin/eslint --ignore-path .eslintignore --config ../../../vendor/shopware/platform/src/Administration/Resources/app/administration/.eslintrc.js --ext .js,.vue src/Resources/app/administration -.PHONY: administration-lint - -eslint: administration-lint ## Synonym to 'administration-lint' -.PHONY: eslint - -eslint-fix: administration-fix ## Synonym to 'administration-fix' -.PHONY: eslint-fix - -ecs-fix: ## Run easy coding style in fix mode - php ../../../dev-ops/analyze/vendor/bin/ecs check --fix --config=../../../vendor/shopware/platform/easy-coding-standard.php src tests\ - && php ../../../dev-ops/analyze/vendor/bin/ecs check --fix --config=easy-coding-standard.php src tests -.PHONY: ecs-fix - -ecs-dry: ## Run easy coding style in dry mode - php ../../../dev-ops/analyze/vendor/bin/ecs check --config=../../../vendor/shopware/platform/easy-coding-standard.php src tests\ - && php ../../../dev-ops/analyze/vendor/bin/ecs check --config=easy-coding-standard.php src tests -.PHONY: ecs-dry - -phpstan: ## Run phpstan - php bin/phpstan-config-generator.php \ - && composer dump-autoload \ - && php ../../../dev-ops/analyze/vendor/bin/phpstan analyze --configuration phpstan.neon --autoload-file=../../../vendor/autoload.php src tests -.PHONY: phpstan - -psalm: ## Run vimeo psalm - php ../../../dev-ops/analyze/vendor/bin/psalm --config=psalm.xml --threads=2 --diff --show-info=false -.PHONY: psalm - -phpunit: ## Run phpunit; Accepts an additional argument "FILTER='search term'" - composer dump-autoload \ - && ./../../../vendor/bin/phpunit --filter "$(FILTER)" -.PHONY: phpunit - -phpunit-coverage: ## Run phpunit with coverage report; Accepts an additional argument "FILTER='search term'" - composer dump-autoload \ - && php -d pcov.enabled=1 -d pcov.directory=./.. ./../../../vendor/bin/phpunit --configuration phpunit.xml.dist --log-junit ./../../../build/artifacts/phpunit-language-pack.junit.xml --coverage-clover ./../../../build/artifacts/phpunit-language-pack.clover.xml --coverage-html ./../../../build/artifacts/coverage-language-pack --coverage-text --filter "$(FILTER)" -.PHONY: phpunit-coverage diff --git a/phpunit.xml.dist b/phpunit.xml.dist deleted file mode 100644 index 211b7a8a..00000000 --- a/phpunit.xml.dist +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - tests - - - - - - - ./src/ - - - diff --git a/psalm.xml b/psalm.xml deleted file mode 100644 index 8dfc41f7..00000000 --- a/psalm.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Resources/public/administration/css/swag-language-pack.css b/src/Resources/public/administration/css/swag-language-pack.css new file mode 100644 index 00000000..80221ebf --- /dev/null +++ b/src/Resources/public/administration/css/swag-language-pack.css @@ -0,0 +1,3 @@ +.swag-language-pack-entry__flag{display:inline-block;width:34px;height:24px}.swag-language-pack-entry__flag>svg{border:1px solid #b3bfcc;border-radius:4px} +.swag-language-pack-entry{display:grid;grid-template-columns:auto 1fr auto;align-items:center;column-gap:16px;padding:16px;margin:16px 0;border:1px solid #d1d9e0;border-radius:4px}.swag-language-pack-entry__name{font-weight:600}.swag-language-pack-entry__description{font-size:12px;color:#b3bfcc}.swag-language-pack-entry .sw-field--switch{margin:0}.swag-language-pack-entry .sw-field--switch .sw-field--switch__input{padding:8px 0}.swag-language-pack-entry .sw-field--switch .sw-field__switch-state{top:0;left:0} +.swag-language-pack-settings-base a,.swag-language-pack-settings-base a:active,.swag-language-pack-settings-base a:visited{color:#189eff;text-decoration:none} diff --git a/src/Resources/public/administration/js/swag-language-pack.js b/src/Resources/public/administration/js/swag-language-pack.js new file mode 100644 index 00000000..119b91bd --- /dev/null +++ b/src/Resources/public/administration/js/swag-language-pack.js @@ -0,0 +1,3 @@ +(function(){var e={280:function(){},737:function(){},708:function(){},590:function(){let{Component:e,Defaults:a}=Shopware,{Criteria:n}=Shopware.Data;e.override("sw-language-switch",{computed:{languageCriteria(){return this.$super("languageCriteria").addFilter(n.multi("OR",[n.equals("extensions.swagLanguagePackLanguage.id",null),n.equals("extensions.swagLanguagePackLanguage.salesChannelActive",!0),n.equals("id",a.systemLanguageId)]))}}})},175:function(){let e;let{Criteria:a}=Shopware.Data,{warn:n}=Shopware.Utils.debug,t=Shopware.Service("repositoryFactory").create("swag_language_pack_language"),s=new a().addFilter(a.equals("administrationActive",!0)).addAggregation(a.terms("locales","language.locale.code",null,null,null)),i=Shopware.Plugin.addBootPromise();t.search(s).then(a=>{a.aggregations.locales.buckets.forEach(({key:a})=>{!1===Shopware.Locale.getByName(a)&&(e=a,Shopware.Locale.register(a,{}))}),i()}).catch(()=>{let a='Unable to register "packLanguages".';void 0!==e&&(a+=` Problems occurred while installing language: ${e}`),n("SwagLanguagePack",a),i()})},12:function(){let{Component:e,Defaults:a}=Shopware,{Criteria:n}=Shopware.Data;e.override("sw-first-run-wizard-welcome",{methods:{getLanguageCriteria(){return this.$super("getLanguageCriteria").addAssociation("swagLanguagePackLanguage").addSorting(n.sort("name","ASC")).addFilter(n.multi("OR",[n.equals("extensions.swagLanguagePackLanguage.id",null),n.equals("extensions.swagLanguagePackLanguage.administrationActive",!0),n.equals("id",a.systemLanguageId)])).setLimit(null)}}})},620:function(){let{Component:e}=Shopware,{Criteria:a}=Shopware.Data;e.override("sw-sales-channel-detail-domains",{computed:{snippetSetCriteria(){let e=this.salesChannel.languages.map(e=>e.locale?.code).filter(Boolean);return 0===e.length?this.$super("snippetSetCriteria"):this.$super("snippetSetCriteria").addFilter(a.equalsAny("iso",e))}}})},983:function(){let{Component:e}=Shopware;e.override("sw-sales-channel-detail",{methods:{getLoadSalesChannelCriteria(){return this.$super("getLoadSalesChannelCriteria").addAssociation("languages.locale")}}})},637:function(){let{Component:e}=Shopware,{Criteria:a}=Shopware.Data;e.override("sw-users-permissions-user-create",{computed:{languageCriteria(){return this.$super("languageCriteria").addFilter(a.multi("OR",[a.equals("extensions.swagLanguagePackLanguage.id",null),a.equals("extensions.swagLanguagePackLanguage.administrationActive",!0),a.equals("id",Shopware.Defaults.systemLanguageId)]))}},methods:{onSave(){this.$super("onSave")}}})},988:function(){let{Component:e}=Shopware,{Criteria:a}=Shopware.Data;e.override("sw-users-permissions-user-detail",{computed:{languageCriteria(){let e=this.$super("languageCriteria");return e.addFilter(a.multi("OR",[a.equals("extensions.swagLanguagePackLanguage.id",null),a.equals("extensions.swagLanguagePackLanguage.administrationActive",!0),a.equals("id",Shopware.Defaults.systemLanguageId)])),e}}})},366:function(){Shopware.Service("privileges").addPrivilegeMappingEntry({category:"permissions",parent:"settings",key:"language",roles:{viewer:{privileges:["sales_channel:read","sales_channel_domain:read"]},editor:{privileges:["swag_language_pack_language:update","user:read","user:update"]}}})},210:function(e,a,n){var t=n(280);t.__esModule&&(t=t.default),"string"==typeof t&&(t=[[e.id,t,""]]),t.locals&&(e.exports=t.locals),n(346).Z("38f45fdc",t,!0,{})},431:function(e,a,n){var t=n(737);t.__esModule&&(t=t.default),"string"==typeof t&&(t=[[e.id,t,""]]),t.locals&&(e.exports=t.locals),n(346).Z("4d501ae2",t,!0,{})},596:function(e,a,n){var t=n(708);t.__esModule&&(t=t.default),"string"==typeof t&&(t=[[e.id,t,""]]),t.locals&&(e.exports=t.locals),n(346).Z("a696210e",t,!0,{})},346:function(e,a,n){"use strict";function t(e,a){for(var n=[],t={},s=0;sn.parts.length&&(t.parts.length=n.parts.length)}else{for(var g=[],s=0;s(function(e,a){return{template:`
`,name:e,mounted(){console.warn(`DEPRECATED: Replace '<${e} />' with ''`)},computed:{assetFilter(){return Shopware.Filter.getByName("asset")}}}})(a,e))}n(12),n(620),n(983);let{Component:e,Defaults:a}=Shopware,{Criteria:t}=Shopware.Data;e.override("sw-sales-channel-detail-base",{template:'{% block sw_sales_channel_detail_base_general_input_languages %}\n \n{% endblock %}\n',computed:{languageCriteria(){return new t().addAssociation("swagLanguagePackLanguage").addAssociation("locale").addSorting(t.sort("name","ASC")).addFilter(t.multi("OR",[t.equals("extensions.swagLanguagePackLanguage.id",null),t.equals("extensions.swagLanguagePackLanguage.salesChannelActive",!0),t.equals("id",a.systemLanguageId)]))}}});let{Component:s}=Shopware,{Criteria:i}=Shopware.Data;s.override("sw-settings-language-list",{template:'{% block sw_settings_language_list_content_list_delete_action %}\n \n{% endblock %}\n',data(){return{packLanguageLanguageIds:[]}},computed:{packLanguageCriteria(){return new i(1,50).addFilter(i.not("and",[i.equals("swagLanguagePackLanguage.id",null)]))}},created(){this.createdComponent()},methods:{createdComponent(){this.getPackLanguageLanguageIds()},getPackLanguageLanguageIds(){this.languageRepository.searchIds(this.packLanguageCriteria).then(e=>{this.packLanguageLanguageIds=e.data})},isPackLanguage(e){return this.packLanguageLanguageIds.includes(e)}}}),n(366),n(210);let{Component:g}=Shopware;g.register("swag-language-pack-flag",{template:'{% block swag_language_pack_flag %}\n
\n \n
\n{% endblock %}\n',props:{locale:{type:String,required:!1,default:""}},computed:{assetFilter(){return Shopware.Filter.getByName("asset")},countryCode(){return this.locale.split("-")[1].toLowerCase()}}}),n(431);let{Component:l}=Shopware;l.register("swag-pack-language-entry",{template:'{% block swag_pack_language_entry %}\n
\n\n {% block swag_pack_language_entry_flag %}\n \n {% endblock %}\n\n {% block swag_pack_language_entry_content %}\n
\n\n {% block swag_pack_language_entry_content_name %}\n
\n {{ label }}\n
\n {% endblock %}\n\n {% block swag_pack_language_entry_content_description %}\n
\n {{ description }}\n
\n {% endblock %}\n\n
\n {% endblock %}\n\n {% block swag_pack_language_entry_switch %}\n \n {% endblock %}\n
\n{% endblock %}\n',inject:["acl"],props:{value:{type:Object,required:!0},field:{type:String,required:!0},label:{type:String,required:!0},disabled:{type:Boolean,required:!0,default:!1},description:{type:String,required:!1,default:""},flagLocale:{type:String,required:!1,default:""}}});let{Component:r}=Shopware;r.register("swag-language-pack-settings-icon",{template:'{% block swag_language_pack_settings_icon %}\n \n{% endblock %}\n'});let{Component:o,Defaults:c}=Shopware,{Criteria:u}=Shopware.Data;o.register("swag-language-pack-settings",{template:'{% block swag_language_pack_settings %}\n\n\n {% block swag_language_pack_settings_header %}\n \n {% endblock %}\n\n {% block swag_language_pack_settings_actions %}\n \n {% endblock %}\n\n {% block swag_language_pack_settings_content %}\n \n {% endblock %}\n\n\n{% endblock %}\n',inject:["repositoryFactory","userService","acl"],mixins:["notification"],data(){return{isLoading:!1,isSaveSuccessful:!1,hasChanges:!1,packLanguages:[],fallbackLocaleId:null,confirmPasswordModal:!1}},metaInfo(){return{title:this.$createTitle()}},computed:{packLanguageRepository(){return this.repositoryFactory.create("swag_language_pack_language")},languageRepository(){return this.repositoryFactory.create("language")},userRepository(){return this.repositoryFactory.create("user")},packLanguageCriteria(){return new u().addSorting(u.sort("language.name","ASC")).addAssociation("language.salesChannels.domains").addAssociation("language.locale")}},created(){this.createdComponent()},beforeRouteLeave(e,a,n){n(),this.hasChanges&&window.location.reload()},methods:{createdComponent(){this.loadPackLanguages()},loadPackLanguages(){return this.isLoading=!0,this.packLanguageRepository.search(this.packLanguageCriteria).then(e=>{this.packLanguages=e}).finally(()=>{this.isLoading=!1})},onSave(){this.confirmPasswordModal=!0},onSaveFinish(){this.isSaveSuccessful=!1},onCloseConfirmPasswordModal(){this.confirmPasswordModal=!1},savePackLanguages(){return this.isLoading=!0,this.validateStates(this.packLanguages).then(()=>this.packLanguageRepository.saveAll(this.packLanguages).then(()=>(this.hasChanges=!0,this.resetInvalidUserLanguages())).catch(()=>{this.createNotificationError({message:this.$tc("swag-language-pack.settings.card.messageSaveError")})})).catch(e=>{let a=e.map(e=>e.language.name),n=`${a.join(", ")}`;this.createNotificationError({message:this.$tc("swag-language-pack.settings.card.messageSalesChannelActiveError",0,{languages:n}),autoClose:!1})}).finally(()=>{this.isLoading=!1,this.isSaveSuccessful=!0,this.loadPackLanguages()})},validateStates(e){return new Promise((a,n)=>{let t=e.filter(e=>!(e.salesChannelActive||e.language.salesChannels.length<=0));t.length>0&&n(t),a()})},async resetInvalidUserLanguages(){let e=await this.fetchInvalidLocaleIds();if(!e||e.length<=0)return Promise.resolve();let a=await this.userService.getUser(),n=new u().addFilter(u.equalsAny("localeId",e)),t=await this.userRepository.search(n);return t=t.reduce((e,n)=>(n.localeId=this.fallbackLocaleId,a.data.id===n.id&&Shopware.Service("localeHelper").setLocaleWithId(n.localeId),e.push(n),e),[]),this.userRepository.saveAll(t)},async fetchInvalidLocaleIds(){let e=new u().addFilter(u.equals("extensions.swagLanguagePackLanguage.administrationActive",!1)),a=await this.languageRepository.search(e),n=new u().setIds([c.systemLanguageId]),t=await this.languageRepository.search(n);return this.fallbackLocaleId=t.first().localeId,a.map(e=>e.localeId)}}}),n(596);let{Component:d}=Shopware;d.register("swag-language-pack-settings-base",{template:'{% block swag_language_pack_settings_base %}\n{% block swag_language_pack_settings_base_card_view_language_selection %}\n \n\n {% block swag_language_pack_settings_base_card_view_card_loader %}\n \n {% endblock %}\n\n {% block swag_language_pack_settings_base_card_view_description%}\n \n {% endblock %}\n\n {% block swag_language_pack_settings_base_card_view_language_selection_languages %}\n \n {% block swag_language_pack_settings_base_card_view_language_selection_language %}\n \n {% endblock %}\n \n {% endblock %}\n\n \n{% endblock %}\n{% endblock %}\n',inject:["acl"],props:{isLoading:{type:Boolean,required:!0},packLanguages:{type:Array,required:!0},settingsType:{type:String,required:!0,validator(e){return["administration","salesChannel"].includes(e)}}},computed:{description(){let e=` + ${this.$tc("swag-language-pack.settings.card.administration.descriptionTargetLinkText")} + `;return this.$tc(`swag-language-pack.settings.card.${this.settingsType}.description`,0,{userInterfaceLanguageLink:e})}}});let{Component:p}=Shopware;p.register("swag-language-pack-settings-administration",{template:'{% block swag_language_pack_settings_administration %}\n \n \n{% endblock %}',props:{isLoading:{type:Boolean,required:!0},packLanguages:{type:Array,required:!0}}});let{Component:w}=Shopware;w.register("swag-language-pack-settings-sales-channel",{template:'{% block swag_language_pack_settings_sales_channel %}\n \n \n{% endblock %}\n',props:{isLoading:{type:Boolean,required:!0},packLanguages:{type:Array,required:!0}}});let{Module:k}=Shopware;k.register("swag-language-pack",{type:"plugin",name:"SwagLanguagePack",title:"swag-language-pack.general.mainMenuItemGeneral",description:"swag-language-pack.general.descriptionTextModule",version:"1.0.0",targetVersion:"1.0.0",color:"#9AA8B5",icon:"regular-cog",routes:{index:{component:"swag-language-pack-settings",path:"index",redirect:{name:"swag.language.pack.index.administration"},meta:{parentPath:"sw.settings.index",privilege:"language.viewer"},children:{administration:{component:"swag-language-pack-settings-administration",path:"administration",meta:{parentPath:"sw.settings.index",privilege:"language.viewer"}},salesChannel:{component:"swag-language-pack-settings-sales-channel",path:"sales-channel",meta:{parentPath:"sw.settings.index",privilege:"language.viewer"}}}}},settingsItem:{group:"plugins",to:"swag.language.pack.index",icon:"regular-language",backgroundEnabled:!0,privilege:"language.viewer"}}),n(988),n(637)}()})(); \ No newline at end of file diff --git a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelDomainValidatorTest.php b/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelDomainValidatorTest.php deleted file mode 100644 index ed4d6092..00000000 --- a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelDomainValidatorTest.php +++ /dev/null @@ -1,88 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Core\Framework\DataAbstractionLayer\Write\Validation; - -use PHPUnit\Framework\TestCase; -use Shopware\Core\Defaults; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\Uuid\Uuid; -use Shopware\Core\System\SalesChannel\Aggregate\SalesChannelDomain\SalesChannelDomainDefinition; -use Shopware\Core\System\SalesChannel\Aggregate\SalesChannelDomain\SalesChannelDomainEntity; -use Shopware\Core\System\SalesChannel\SalesChannelCollection; -use Shopware\Core\Test\TestDefaults; -use Swag\LanguagePack\Test\Helper\ServicesTrait; - -class SalesChannelDomainValidatorTest extends TestCase -{ - use ServicesTrait; - - /** - * @var EntityRepository - */ - private EntityRepository $salesChannelDomainRepository; - - protected function setUp(): void - { - $container = $this->getContainer(); - - /** @var EntityRepository $salesChannelDomainRepository */ - $salesChannelDomainRepository = $container->get(\sprintf('%s.repository', SalesChannelDomainDefinition::ENTITY_NAME)); - $this->salesChannelDomainRepository = $salesChannelDomainRepository; - } - - public function testCreatingASalesChannelDomainWithADeactivatedLanguageFails(): void - { - $context = Context::createDefaultContext(); - $languageId = $this->setSalesChannelActiveForLanguageByName('Dansk', false, $context); - - $this->expectExceptionMessage(\sprintf('The language with the id "%s" is disabled for all Sales Channels.', $languageId)); - $this->createSalesChannelDomain(Uuid::randomHex(), $languageId, $context); - } - - public function testUpdatingASalesChannelDomainToADisabledLanguageFails(): void - { - $context = Context::createDefaultContext(); - $enabledLanguageId = $this->setSalesChannelActiveForLanguageByName('Dansk', true, $context); - $disabledLanguageId = $this->setSalesChannelActiveForLanguageByName('Français', false, $context); - - $domainId = Uuid::randomHex(); - $this->createSalesChannelDomain($domainId, $enabledLanguageId, $context); - - $criteria = new Criteria([$domainId]); - - /** @var SalesChannelDomainEntity|null $domain */ - $domain = $this->salesChannelDomainRepository->search($criteria, $context)->first(); - static::assertNotNull($domain); - - $this->expectExceptionMessage(\sprintf('The language with the id "%s" is disabled for all Sales Channels.', $disabledLanguageId)); - $this->salesChannelDomainRepository->update([ - [ - 'id' => $domainId, - 'languageId' => $disabledLanguageId, - ], - ], $context); - } - - private function createSalesChannelDomain(string $domainId, string $languageId, Context $context): void - { - $this->salesChannelDomainRepository->create([ - [ - 'id' => $domainId, - 'url' => 'http://example.com', - 'salesChannelId' => TestDefaults::SALES_CHANNEL, - 'languageId' => $languageId, - 'currencyId' => Defaults::CURRENCY, - 'snippetSetId' => $this->getSnippetSetIdForLocale('en-GB'), - ], - ], $context); - } -} diff --git a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelLanguageValidatorTest.php b/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelLanguageValidatorTest.php deleted file mode 100644 index 409f8200..00000000 --- a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelLanguageValidatorTest.php +++ /dev/null @@ -1,54 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Core\Framework\DataAbstractionLayer\Write\Validation; - -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\System\SalesChannel\Aggregate\SalesChannelLanguage\SalesChannelLanguageDefinition; -use Shopware\Core\System\SalesChannel\SalesChannelCollection; -use Shopware\Core\Test\TestDefaults; -use Swag\LanguagePack\Test\Helper\ServicesTrait; - -class SalesChannelLanguageValidatorTest extends TestCase -{ - use ServicesTrait; - - /** - * @var EntityRepository - */ - private EntityRepository $salesChannelLanguageRepository; - - protected function setUp(): void - { - $container = $this->getContainer(); - - /** @var EntityRepository $salesChannelLanguageRepository */ - $salesChannelLanguageRepository = $container->get(\sprintf('%s.repository', SalesChannelLanguageDefinition::ENTITY_NAME)); - $this->salesChannelLanguageRepository = $salesChannelLanguageRepository; - } - - public function testCreatingASalesChannelLanguageWithADeactivatedLanguageFails(): void - { - $context = Context::createDefaultContext(); - $languageId = $this->setSalesChannelActiveForLanguageByName('Dansk', false, $context); - - $this->expectExceptionMessage(\sprintf('The language with the id "%s" is disabled for all Sales Channels.', $languageId)); - $this->createSalesChannelLanguage($languageId, $context); - } - - private function createSalesChannelLanguage(string $languageId, Context $context): void - { - $this->salesChannelLanguageRepository->create([[ - 'salesChannelId' => TestDefaults::SALES_CHANNEL, - 'languageId' => $languageId, - ]], $context); - } -} diff --git a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelValidatorTest.php b/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelValidatorTest.php deleted file mode 100644 index 87071114..00000000 --- a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/SalesChannelValidatorTest.php +++ /dev/null @@ -1,91 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Core\Framework\DataAbstractionLayer\Write\Validation; - -use PHPUnit\Framework\TestCase; -use Shopware\Core\Defaults; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\Uuid\Uuid; -use Shopware\Core\System\SalesChannel\SalesChannelCollection; -use Shopware\Core\System\SalesChannel\SalesChannelDefinition; -use Shopware\Core\System\SalesChannel\SalesChannelEntity; -use Shopware\Core\Test\TestDefaults; -use Swag\LanguagePack\Test\Helper\ServicesTrait; - -class SalesChannelValidatorTest extends TestCase -{ - use ServicesTrait; - - /** - * @var EntityRepository - */ - private EntityRepository $salesChannelRepository; - - protected function setUp(): void - { - $container = $this->getContainer(); - - /** @var EntityRepository $salesChannelRepository */ - $salesChannelRepository = $container->get(\sprintf('%s.repository', SalesChannelDefinition::ENTITY_NAME)); - $this->salesChannelRepository = $salesChannelRepository; - } - - public function testCreatingASalesChannelWithADeactivatedDefaultLanguageFails(): void - { - $context = Context::createDefaultContext(); - $languageId = $this->setSalesChannelActiveForLanguageByName('Dansk', false, $context); - - $this->expectExceptionMessage(\sprintf('The language with the id "%s" is disabled for all Sales Channels.', $languageId)); - $this->createSalesChannelWithLanguage(Uuid::randomHex(), $languageId, $context); - } - - public function testThatUpdatingASalesChannelToADisabledSalesChannelFails(): void - { - $context = Context::createDefaultContext(); - $enabledLanguageId = $this->setSalesChannelActiveForLanguageByName('Dansk', true, $context); - $disabledLanguageId = $this->setSalesChannelActiveForLanguageByName('Français', false, $context); - - $salesChannelId = Uuid::randomHex(); - $this->createSalesChannelWithLanguage($salesChannelId, $enabledLanguageId, $context); - - $criteria = new Criteria([$salesChannelId]); - - /** @var SalesChannelEntity|null $salesChannel */ - $salesChannel = $this->salesChannelRepository->search($criteria, $context)->first(); - static::assertNotNull($salesChannel); - - $this->expectExceptionMessage(\sprintf('The language with the id "%s" is disabled for all Sales Channels.', $disabledLanguageId)); - $this->salesChannelRepository->update([[ - 'id' => $salesChannelId, - 'languageId' => $disabledLanguageId, - 'languages' => [['id' => $disabledLanguageId]], - ]], $context); - } - - private function createSalesChannelWithLanguage(string $salesChannelId, string $languageId, Context $context): void - { - $this->salesChannelRepository->create([[ - 'id' => $salesChannelId, - 'languageId' => $languageId, - 'languages' => [['id' => $languageId]], - 'typeId' => Defaults::SALES_CHANNEL_TYPE_STOREFRONT, - 'customerGroupId' => TestDefaults::FALLBACK_CUSTOMER_GROUP, - 'currencyId' => Defaults::CURRENCY, - 'paymentMethodId' => $this->getValidPaymentMethodId(), - 'shippingMethodId' => $this->getValidShippingMethodId(), - 'countryId' => $this->getValidCountryId(), - 'navigationCategoryId' => $this->getValidCategoryId(), - 'accessKey' => 'S3cr3tfor3st', - 'name' => 'Test SalesChannel', - ]], $context); - } -} diff --git a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/UserValidatorTest.php b/tests/Core/Framework/DataAbstractionLayer/Write/Validation/UserValidatorTest.php deleted file mode 100644 index eb534a30..00000000 --- a/tests/Core/Framework/DataAbstractionLayer/Write/Validation/UserValidatorTest.php +++ /dev/null @@ -1,83 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Core\Framework\DataAbstractionLayer\Write\Validation; - -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\Uuid\Uuid; -use Shopware\Core\System\User\UserCollection; -use Shopware\Core\System\User\UserDefinition; -use Shopware\Core\System\User\UserEntity; -use Swag\LanguagePack\Test\Helper\ServicesTrait; - -class UserValidatorTest extends TestCase -{ - use ServicesTrait; - - /** - * @var EntityRepository - */ - private EntityRepository $userRepository; - - protected function setUp(): void - { - $container = $this->getContainer(); - - /** @var EntityRepository $userRepository */ - $userRepository = $container->get(\sprintf('%s.repository', UserDefinition::ENTITY_NAME)); - $this->userRepository = $userRepository; - } - - public function testCreateUserWithADeactivatedLanguageFails(): void - { - $context = Context::createDefaultContext(); - $localeId = $this->setAdministrationActiveForLanguageByLocale('da-DK', false, $context); - - $this->expectExceptionMessage(\sprintf('The language bound to the locale with the id "%s" is disabled for the Administration.', $localeId)); - $this->createUser(Uuid::randomHex(), $localeId, $context); - } - - public function testUpdateUserToDisabledLanguageFails(): void - { - $context = Context::createDefaultContext(); - $enabledLocaleId = $this->setAdministrationActiveForLanguageByLocale('da-DK', true, $context); - $disabledLocaleId = $this->setAdministrationActiveForLanguageByLocale('fr-FR', false, $context); - - $userId = Uuid::randomHex(); - $this->createUser($userId, $enabledLocaleId, $context); - - $criteria = new Criteria([$userId]); - - /** @var UserEntity|null $user */ - $user = $this->userRepository->search($criteria, $context)->first(); - static::assertNotNull($user); - - $this->expectExceptionMessage(\sprintf('The language bound to the locale with the id "%s" is disabled for the Administration.', $disabledLocaleId)); - $this->userRepository->update([[ - 'id' => $userId, - 'localeId' => $disabledLocaleId, - ]], $context); - } - - private function createUser(string $userId, string $localeId, Context $context): void - { - $this->userRepository->create([[ - 'id' => $userId, - 'localeId' => $localeId, - 'username' => 'foo', - 'password' => 'foobarbatz', - 'firstName' => 'Olaf', - 'lastName' => 'Olafson', - 'email' => 'test@example.com', - ]], $context); - } -} diff --git a/tests/Core/System/SalesChannel/Command/SalesChannelCreateCommandTest.php b/tests/Core/System/SalesChannel/Command/SalesChannelCreateCommandTest.php deleted file mode 100644 index 8daf5638..00000000 --- a/tests/Core/System/SalesChannel/Command/SalesChannelCreateCommandTest.php +++ /dev/null @@ -1,153 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Core\System\SalesChannel\Command; - -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\DefinitionInstanceRegistry; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour; -use Shopware\Core\Maintenance\SalesChannel\Service\SalesChannelCreator; -use Shopware\Core\System\Language\LanguageCollection; -use Shopware\Core\System\Language\LanguageDefinition; -use Shopware\Core\System\Language\LanguageEntity; -use Shopware\Core\System\SalesChannel\SalesChannelCollection; -use Shopware\Core\System\SalesChannel\SalesChannelDefinition; -use Shopware\Core\System\SalesChannel\SalesChannelEntity; -use Swag\LanguagePack\Core\System\SalesChannel\Command\SalesChannelCreateCommand; -use Swag\LanguagePack\PackLanguage\PackLanguageCollection; -use Swag\LanguagePack\PackLanguage\PackLanguageDefinition; -use Swag\LanguagePack\SwagLanguagePack; -use Symfony\Component\Console\Tester\CommandTester; - -class SalesChannelCreateCommandTest extends TestCase -{ - use IntegrationTestBehaviour; - - protected SalesChannelCreateCommand $salesChannelCreateCommand; - - protected SalesChannelCreateCommand $overrideSalesChannelCreateCommand; - - /** - * @var EntityRepository $salesChannelRepository - */ - protected EntityRepository $salesChannelRepository; - - /** - * @var EntityRepository $languageRepository - */ - protected EntityRepository $languageRepository; - - /** - * @var EntityRepository $languagePackRepository - */ - protected EntityRepository $languagePackRepository; - - private Context $context; - - protected function setUp(): void - { - /** @var EntityRepository $salesChannelRepository */ - $salesChannelRepository = $this->getContainer()->get(\sprintf('%s.repository', SalesChannelDefinition::ENTITY_NAME)); - $this->salesChannelRepository = $salesChannelRepository; - - /** @var EntityRepository $languageRepository */ - $languageRepository = $this->getContainer()->get(\sprintf('%s.repository', LanguageDefinition::ENTITY_NAME)); - $this->languageRepository = $languageRepository; - - /** @var EntityRepository $languagePackRepository */ - $languagePackRepository = $this->getContainer()->get(\sprintf('%s.repository', PackLanguageDefinition::ENTITY_NAME)); - $this->languagePackRepository = $languagePackRepository; - - $this->context = Context::createDefaultContext(); - - /** @var DefinitionInstanceRegistry $definitionRegistry */ - $definitionRegistry = $this->getContainer()->get(DefinitionInstanceRegistry::class); - - /** @var SalesChannelCreator $salesChannelCreator */ - $salesChannelCreator = $this->getContainer()->get(SalesChannelCreator::class); - - $this->salesChannelCreateCommand = new SalesChannelCreateCommand( - $definitionRegistry, - $languageRepository, - $salesChannelCreator, - ); - } - - public function testIfCommandSucceeds(): void - { - $salesChannelId = 'ad1028c2a8ed46d2a24f189812b1a23c'; - $navigationCategoryId = $this->getValidCategoryId(); - $tester = new CommandTester($this->salesChannelCreateCommand); - $result = $tester->execute([ - '--id' => $salesChannelId, - '--navigationCategoryId' => $navigationCategoryId, - ]); - static::assertSame(0, $result); - - $outputString = $tester->getDisplay(); - - static::assertStringNotContainsString('[ERROR]', $outputString); - - // check the associated languages of the created sales channel - $associatedLanguages = $this->getAssociatedLanguageLocalesOfSalesChannel($salesChannelId); - - static::assertStringContainsString('[OK] Sales channel has been created successfully.', $outputString); - static::assertContains('en-GB', $associatedLanguages); - static::assertContains('de-DE', $associatedLanguages); - } - - public function testIfCommandConsidersActivatedLanguages(): void - { - $salesChannelId = 'ad1028c2a8ed46d2a24f189812b1a23b'; - - $navigationCategoryId = $this->getValidCategoryId(); - - $tester = new CommandTester($this->salesChannelCreateCommand); - $result = $tester->execute([ - '--id' => $salesChannelId, - '--navigationCategoryId' => $navigationCategoryId, - ]); - static::assertSame(0, $result); - - $outputString = $tester->getDisplay(); - - static::assertStringContainsString('[OK] Sales channel has been created successfully.', $outputString); - static::assertStringNotContainsString('[ERROR]', $outputString); - - // check the associated languages of the created sales channel - $associatedLanguages = $this->getAssociatedLanguageLocalesOfSalesChannel($salesChannelId); - static::assertCount(0, \array_diff(SwagLanguagePack::BASE_SNIPPET_SET_LOCALES, $associatedLanguages)); - } - - /** - * @return string[] - */ - protected function getAssociatedLanguageLocalesOfSalesChannel(string $salesChannelId): array - { - // fetch the language with the locale - $criteria = new Criteria([$salesChannelId]); - $criteria->addAssociation('languages.locale'); - - /** @var SalesChannelEntity|null $result */ - $result = $this->salesChannelRepository->search($criteria, $this->context)->first(); - static::assertNotNull($result); - $languages = $result->getLanguages(); - static::assertNotNull($languages); - - return \array_map(static function (LanguageEntity $lang): string { - $locale = $lang->getLocale(); - static::assertNotNull($locale); - - return $locale->getCode(); - }, \array_values($languages->getElements())); - } -} diff --git a/tests/Extension/LanguageExtensionTest.php b/tests/Extension/LanguageExtensionTest.php deleted file mode 100644 index d55055ef..00000000 --- a/tests/Extension/LanguageExtensionTest.php +++ /dev/null @@ -1,54 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Extension; - -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\SetNullOnDelete; -use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToOneAssociationField; -use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection; -use Shopware\Core\System\Language\LanguageDefinition; -use Swag\LanguagePack\Extension\LanguageExtension; -use Swag\LanguagePack\PackLanguage\PackLanguageDefinition; - -class LanguageExtensionTest extends TestCase -{ - public function testExtendFieldsAddsOneToOneAssociationField(): void - { - /** @var MockObject|FieldCollection $collection */ - $collection = $this->getMockBuilder(FieldCollection::class) - ->disableOriginalConstructor() - ->onlyMethods(['add']) - ->getMock(); - - $collection - ->expects(static::atLeastOnce()) - ->method('add') - ->with( - (new OneToOneAssociationField( - LanguageExtension::PACK_LANGUAGE_ASSOCIATION_PROPERTY_NAME, - 'id', - 'language_id', - PackLanguageDefinition::class, - false, - ))->addFlags(new SetNullOnDelete()), - ); - - (new LanguageExtension())->extendFields($collection); - } - - public function testGetDefinitionClassReturnsCmsSectionDefinitionClass(): void - { - static::assertSame( - LanguageDefinition::class, - (new LanguageExtension())->getDefinitionClass(), - ); - } -} diff --git a/tests/Helper/ServicesTrait.php b/tests/Helper/ServicesTrait.php deleted file mode 100644 index 80a1e973..00000000 --- a/tests/Helper/ServicesTrait.php +++ /dev/null @@ -1,84 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Helper; - -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; -use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour; -use Swag\LanguagePack\PackLanguage\PackLanguageCollection; -use Swag\LanguagePack\PackLanguage\PackLanguageDefinition; -use Swag\LanguagePack\PackLanguage\PackLanguageEntity; - -trait ServicesTrait -{ - use IntegrationTestBehaviour; - - private function setSalesChannelActiveForLanguageByName(string $name, bool $salesChannelActive, Context $context): string - { - /** @var EntityRepository $packLanguageRepository */ - $packLanguageRepository = $this->getContainer()->get(\sprintf('%s.repository', PackLanguageDefinition::ENTITY_NAME)); - - $criteria = new Criteria(); - $criteria->addFilter(new EqualsFilter('language.name', $name)); - - /** @var PackLanguageEntity|null $first */ - $first = $packLanguageRepository->search($criteria, $context)->first(); - static::assertNotNull($first); - - $packLanguageRepository->update([[ - 'id' => $first->getId(), - 'salesChannelActive' => $salesChannelActive, - ]], $context); - - return $first->getLanguageId(); - } - - private function setSalesChannelActiveForLanguageByLocale(string $locale, bool $salesChannelActive, Context $context): string - { - /** @var EntityRepository $packLanguageRepository */ - $packLanguageRepository = $this->getContainer()->get(\sprintf('%s.repository', PackLanguageDefinition::ENTITY_NAME)); - - $criteria = new Criteria(); - $criteria->addFilter(new EqualsFilter('language.locale.code', $locale)); - - /** @var PackLanguageEntity|null $first */ - $first = $packLanguageRepository->search($criteria, $context)->first(); - static::assertNotNull($first); - - $packLanguageRepository->update([[ - 'id' => $first->getId(), - 'salesChannelActive' => $salesChannelActive, - ]], $context); - - return $first->getLanguage()->getLocaleId(); - } - - private function setAdministrationActiveForLanguageByLocale(string $locale, bool $administrationActive, Context $context): string - { - /** @var EntityRepository $packLanguageRepository */ - $packLanguageRepository = $this->getContainer()->get(\sprintf('%s.repository', PackLanguageDefinition::ENTITY_NAME)); - - $criteria = new Criteria(); - $criteria->addFilter(new EqualsFilter('language.locale.code', $locale)); - - /** @var PackLanguageEntity|null $first */ - $first = $packLanguageRepository->search($criteria, $context)->first(); - static::assertNotNull($first); - - $packLanguageRepository->update([[ - 'id' => $first->getId(), - 'administrationActive' => $administrationActive, - ]], $context); - - return $first->getLanguage()->getLocaleId(); - } -} diff --git a/tests/Storefront/Framework/Command/SalesChannelCreateStorefrontCommandTest.php b/tests/Storefront/Framework/Command/SalesChannelCreateStorefrontCommandTest.php deleted file mode 100644 index 97f6594d..00000000 --- a/tests/Storefront/Framework/Command/SalesChannelCreateStorefrontCommandTest.php +++ /dev/null @@ -1,195 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Storefront\Framework\Command; - -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\DefinitionInstanceRegistry; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; -use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour; -use Shopware\Core\Framework\Uuid\Uuid; -use Shopware\Core\Maintenance\SalesChannel\Service\SalesChannelCreator; -use Shopware\Core\System\Language\LanguageCollection; -use Shopware\Core\System\SalesChannel\SalesChannelCollection; -use Shopware\Core\System\SalesChannel\SalesChannelEntity; -use Shopware\Core\System\Snippet\Aggregate\SnippetSet\SnippetSetCollection; -use Shopware\Storefront\Storefront; -use Swag\LanguagePack\Extension\LanguageExtension; -use Swag\LanguagePack\PackLanguage\PackLanguageCollection; -use Swag\LanguagePack\Storefront\Framework\Command\SalesChannelCreateStorefrontCommand; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Tester\CommandTester; - -class SalesChannelCreateStorefrontCommandTest extends TestCase -{ - use IntegrationTestBehaviour; - - /** - * @var EntityRepository $salesChannelRepository - */ - private EntityRepository $salesChannelRepository; - - /** - * @var EntityRepository $languagePackLanguageRepository - */ - private EntityRepository $languagePackLanguageRepository; - - /** - * @var EntityRepository $languageRepository - */ - private EntityRepository $languageRepository; - - private Context $context; - - private Command $command; - - /** - * @psalm-suppress PropertyTypeCoercion - */ - public function setUp(): void - { - if (!\class_exists(Storefront::class)) { - static::markTestSkipped('Skip test: Storefront bundle is not installed'); - } - - /** @var DefinitionInstanceRegistry $definitionRegistry */ - $definitionRegistry = $this->getContainer()->get(DefinitionInstanceRegistry::class); - - /** @var SalesChannelCreator $salesChannelCreator */ - $salesChannelCreator = $this->getContainer()->get(SalesChannelCreator::class); - - /** @var EntityRepository $snippetSetRepository */ - $snippetSetRepository = $this->getContainer()->get('snippet_set.repository'); - - $this->salesChannelRepository = $this->getContainer()->get('sales_channel.repository'); - - /** @var EntityRepository $languageRepository */ - $languageRepository = $this->getContainer()->get('language.repository'); - $this->languageRepository = $languageRepository; - - /** @var EntityRepository $languagePackLanguageRepository */ - $languagePackLanguageRepository = $this->getContainer()->get('swag_language_pack_language.repository'); - $this->languagePackLanguageRepository = $languagePackLanguageRepository; - - $this->command = new SalesChannelCreateStorefrontCommand( - $definitionRegistry, - $this->languageRepository, - $salesChannelCreator, - $snippetSetRepository, - ); - - $this->context = Context::createDefaultContext(); - } - - public function testServiceIsDecoratedCorrectly(): void - { - static::assertInstanceOf(SalesChannelCreateStorefrontCommand::class, $this->command); - } - - public function testItCreatesStorefrontWithDefaultLanguagesIfAllLanguagesAreDisabled(): void - { - $this->setLanguagesActive(false); - $navigationCategoryId = $this->getValidCategoryId(); - - $storefrontId = 'f37e50e6e2c8461dab552bdbc50e4566'; - - $tester = new CommandTester($this->command); - - $tester->execute([ - '--id' => $storefrontId, - '--url' => '"http://test.shop"', - '--navigationCategoryId' => $navigationCategoryId, - ]); - - /** @var ?SalesChannelEntity $storefront */ - $storefront = $this->salesChannelRepository->search($this->getStorefrontCriteria($storefrontId), $this->context) - ->getEntities()->first(); - - static::assertNotNull($storefront); - - $criteria = new Criteria(); - $criteria->addFilter( - new EqualsFilter( - \sprintf('%s.id', LanguageExtension::PACK_LANGUAGE_ASSOCIATION_PROPERTY_NAME), - null, - ), - ); - - $activeLanguageIds = $this->languageRepository->searchIds($criteria, $this->context)->getIds(); - - /** @var LanguageCollection $associatedLanguages */ - $associatedLanguages = $storefront->getLanguages(); - $associatedLanguageIds = \array_values($associatedLanguages->getIds()); - - static::assertCount(2, $activeLanguageIds); - - static::assertEquals( - \sort($activeLanguageIds), - \sort($associatedLanguageIds), - ); - } - - public function testItCreatesStorefrontWithEnabledLanguages(): void - { - $this->setLanguagesActive(true); - $navigationCategoryId = $this->getValidCategoryId(); - - $storefrontId = Uuid::randomHex(); - - $tester = new CommandTester($this->command); - - $tester->execute([ - '--id' => $storefrontId, - '--url' => '"http://test.shop"', - '--navigationCategoryId' => $navigationCategoryId, - ]); - - /** @var SalesChannelEntity $storefront */ - $storefront = $this->salesChannelRepository->search($this->getStorefrontCriteria($storefrontId), $this->context) - ->getEntities()->first(); - - $activeLanguageIds = $this->languageRepository->searchIds(new Criteria(), $this->context)->getIds(); - - /** @var LanguageCollection $associatedLanguages */ - $associatedLanguages = $storefront->getLanguages(); - $associatedLanguageIds = \array_values($associatedLanguages->getIds()); - - static::assertEquals( - \sort($activeLanguageIds), - \sort($associatedLanguageIds), - ); - } - - public function setLanguagesActive(bool $active): void - { - /** @var string[] $ids */ - $ids = $this->languagePackLanguageRepository->searchIds(new Criteria(), $this->context)->getIds(); - - $updateCommands = \array_map(static function (string $id) use ($active): array { - return [ - 'id' => $id, - 'salesChannelActive' => $active, - ]; - }, $ids); - - $this->languagePackLanguageRepository->update($updateCommands, $this->context); - } - - private function getStorefrontCriteria(string $id): Criteria - { - $criteria = new Criteria([$id]); - $criteria->addAssociation('domains'); - $criteria->addAssociation('languages'); - - return $criteria; - } -} diff --git a/tests/SwagLanguagePackTest.php b/tests/SwagLanguagePackTest.php deleted file mode 100644 index 6fe1b41f..00000000 --- a/tests/SwagLanguagePackTest.php +++ /dev/null @@ -1,103 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test; - -use Doctrine\DBAL\Connection; -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; -use Shopware\Core\Framework\Plugin\PluginCollection; -use Shopware\Core\Framework\Plugin\PluginDefinition; -use Shopware\Core\Framework\Plugin\PluginEntity; -use Shopware\Core\Framework\Plugin\PluginLifecycleService; -use Shopware\Core\Framework\Test\TestCaseBase\DatabaseTransactionBehaviour; -use Shopware\Core\Framework\Test\TestCaseBase\KernelTestBehaviour; -use Swag\LanguagePack\SwagLanguagePack; - -class SwagLanguagePackTest extends TestCase -{ - use KernelTestBehaviour; - use DatabaseTransactionBehaviour; - - /** - * @var EntityRepository - */ - private EntityRepository $pluginRepository; - - protected function setUp(): void - { - /** @var EntityRepository $pluginRepository */ - $pluginRepository = $this->getContainer()->get(\sprintf('%s.repository', PluginDefinition::ENTITY_NAME)); - $this->pluginRepository = $pluginRepository; - } - - public function testThatPluginIsInstalled(): void - { - $criteria = new Criteria(); - $criteria->addFilter( - new EqualsFilter('baseClass', SwagLanguagePack::class), - ); - - /** @var PluginEntity|null $plugin */ - $plugin = $this->pluginRepository->search($criteria, Context::createDefaultContext())->first(); - - static::assertNotNull($plugin, 'Plugin needs to be installed to run testsuite'); - } - - public function testUpdateSnippetsAndLanguagesOnUpdate(): void - { - $connection = $this->getContainer()->get(Connection::class); - - $lastLocale = SwagLanguagePack::SUPPORTED_LANGUAGES; - $lastLocale = \end($lastLocale); - - $languageCountBefore = $connection->fetchOne('SELECT COUNT(*) FROM `language`'); - $swagLanguageCountBefore = $connection->fetchOne('SELECT COUNT(*) FROM `swag_language_pack_language`'); - - $languageId = $connection->fetchOne( - <<<'SQL' - SELECT `language`.`id` FROM `locale` - LEFT JOIN `language` ON `language`.`locale_id` = `locale`.`id` - WHERE `locale`.`code` = :code - SQL, - ['code' => $lastLocale], - ); - - $connection->executeStatement( - 'DELETE FROM `swag_language_pack_language` WHERE `language_id` = :languageId', - ['languageId' => $languageId], - ); - - $connection->executeStatement( - 'DELETE FROM `language` WHERE `id` = :languageId', - ['languageId' => $languageId], - ); - - static::assertNotEquals($languageCountBefore, $connection->fetchOne('SELECT COUNT(*) FROM `language`')); - static::assertNotEquals($swagLanguageCountBefore, $connection->fetchOne('SELECT COUNT(*) FROM `swag_language_pack_language`')); - - $pluginLifeCycleService = $this->getContainer()->get(PluginLifecycleService::class); - - $criteria = new Criteria(); - $criteria->addFilter(new EqualsFilter('baseClass', SwagLanguagePack::class)); - - $context = Context::createDefaultContext(); - - $plugin = $this->pluginRepository->search($criteria, $context)->first(); - static::assertInstanceOf(PluginEntity::class, $plugin); - - $pluginLifeCycleService->updatePlugin($plugin, $context); - - static::assertEquals($languageCountBefore, $connection->fetchOne('SELECT COUNT(*) FROM `language`')); - static::assertEquals($swagLanguageCountBefore, $connection->fetchOne('SELECT COUNT(*) FROM `swag_language_pack_language`')); - } -} diff --git a/tests/TestBootstrap.php b/tests/TestBootstrap.php deleted file mode 100644 index f4179d94..00000000 --- a/tests/TestBootstrap.php +++ /dev/null @@ -1,25 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -use Shopware\Core\TestBootstrapper; - -$platformRoot = dirname(__DIR__, 4); - -if (is_readable($platformRoot . '/src/Core/TestBootstrapper.php')) { - require $platformRoot . '/src/Core/TestBootstrapper.php'; -} else { - require __DIR__ . '/../vendor/shopware/core/TestBootstrapper.php'; -} - -return (new TestBootstrapper()) - ->setProjectDir($_SERVER['PROJECT_ROOT'] ?? $platformRoot) - ->setForceInstallPlugins(true) - ->addCallingPlugin() - ->bootstrap() - ->getClassLoader(); diff --git a/tests/Util/Exception/LanguagePackExceptionTest.php b/tests/Util/Exception/LanguagePackExceptionTest.php deleted file mode 100644 index 663419ea..00000000 --- a/tests/Util/Exception/LanguagePackExceptionTest.php +++ /dev/null @@ -1,44 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Util\Exception; - -use PHPUnit\Framework\TestCase; -use Shopware\Core\System\Language\LanguageCollection; -use Shopware\Core\System\Language\LanguageEntity; -use Swag\LanguagePack\Util\Exception\LanguagePackException; - -class LanguagePackExceptionTest extends TestCase -{ - public function testInstallWithoutLocalesException(): void - { - $exception = LanguagePackException::installWithoutLocales(['doesnt-EXIST', 'thatis-NOLOCALE']); - - static::assertSame( - 'No LocaleEntities associated to the following locale codes: doesnt-EXIST, thatis-NOLOCALE', - $exception->getMessage(), - ); - static::assertSame('SWAG_LANGUAGE_PACK__PACK_LANGUAGES_WITHOUT_LOCALES', $exception->getErrorCode()); - } - - public function testPackLanguagesStillInUseException(): void - { - $language = new LanguageEntity(); - $language->setUniqueIdentifier('NobodyDoesCareAboutThisAtAll'); - $language->setName('CoolDutch'); - - $exception = LanguagePackException::packLanguagesStillInUse(new LanguageCollection([$language])); - - static::assertSame( - "The following languages provided by Shopware's LanguagePack are still used by Sales Channels: CoolDutch", - $exception->getMessage(), - ); - static::assertSame('SWAG_LANGUAGE_PACK_LANGUAGE__STILL_IN_USE_IN_SALES_CHANNEL', $exception->getErrorCode()); - } -} diff --git a/tests/Util/Lifecycle/LifecycleTest.php b/tests/Util/Lifecycle/LifecycleTest.php deleted file mode 100644 index ec308309..00000000 --- a/tests/Util/Lifecycle/LifecycleTest.php +++ /dev/null @@ -1,83 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Util\Lifecycle; - -use Doctrine\DBAL\Connection; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\Migration\MigrationCollection; -use Shopware\Core\Framework\Plugin\Context\UninstallContext; -use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour; -use Shopware\Core\System\Language\LanguageCollection; -use Swag\LanguagePack\SwagLanguagePack; -use Swag\LanguagePack\Util\Lifecycle\Lifecycle; - -class LifecycleTest extends TestCase -{ - use IntegrationTestBehaviour; - - public function testUninstallWithoutKeepingUserData(): void - { - $connection = $this->getConnectionMock(); - - $connection->expects(static::atLeast(4)) - ->method('executeStatement') - ->willReturn(true); - - $connection->expects(static::atLeast(2)) - ->method('executeQuery'); - - /** @var EntityRepository $languageRepository */ - $languageRepository = $this->getContainer()->get('language.repository'); - - $lifecycle = new Lifecycle($connection, $languageRepository); - $lifecycle->uninstall($this->getUninstallContext()); - } - - public function testUninstallKeepsUserData(): void - { - $connection = $this->getConnectionMock(); - $uninstallContext = $this->getUninstallContext(true); - - $connection->expects(static::never()) - ->method('executeStatement'); - - /** @var EntityRepository $languageRepository */ - $languageRepository = $this->getContainer()->get('language.repository'); - - $lifecycle = new Lifecycle($connection, $languageRepository); - $lifecycle->uninstall($uninstallContext); - } - - private function getUninstallContext(bool $keepUserData = false): UninstallContext - { - return new UninstallContext( - new SwagLanguagePack(true, ''), - Context::createDefaultContext(), - '', - '', - $this->createMock(MigrationCollection::class), - $keepUserData, - ); - } - - /** - * @return Connection|MockObject - */ - private function getConnectionMock() - { - return $this->getMockBuilder(Connection::class) - ->disableOriginalConstructor() - ->onlyMethods(['executeStatement', 'executeQuery']) - ->getMock(); - } -} diff --git a/tests/Util/Migration/MigrationHelperTest.php b/tests/Util/Migration/MigrationHelperTest.php deleted file mode 100644 index 61985b16..00000000 --- a/tests/Util/Migration/MigrationHelperTest.php +++ /dev/null @@ -1,325 +0,0 @@ - - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Swag\LanguagePack\Test\Util\Migration; - -use Doctrine\DBAL\Connection; -use Doctrine\DBAL\Result; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\Plugin\Context\UninstallContext; -use Shopware\Core\Framework\Test\TestCaseBase\BasicTestDataBehaviour; -use Shopware\Core\Framework\Test\TestCaseBase\CacheTestBehaviour; -use Shopware\Core\Framework\Test\TestCaseBase\DatabaseTransactionBehaviour; -use Shopware\Core\Framework\Test\TestCaseBase\FilesystemBehaviour; -use Shopware\Core\Framework\Test\TestCaseBase\KernelTestBehaviour; -use Shopware\Core\Framework\Test\TestCaseBase\RequestStackTestBehaviour; -use Shopware\Core\Framework\Test\TestCaseBase\SessionTestBehaviour; -use Shopware\Core\Framework\Uuid\Uuid; -use Shopware\Core\System\Language\LanguageCollection; -use Shopware\Core\System\Language\LanguageDefinition; -use Swag\LanguagePack\PackLanguage\PackLanguageDefinition; -use Swag\LanguagePack\SwagLanguagePack; -use Swag\LanguagePack\Util\Lifecycle\Lifecycle; -use Swag\LanguagePack\Util\Migration\MigrationHelper; - -class MigrationHelperTest extends TestCase -{ - use KernelTestBehaviour; - use DatabaseTransactionBehaviour; - use FilesystemBehaviour; - use CacheTestBehaviour; - use BasicTestDataBehaviour; - use SessionTestBehaviour; - use RequestStackTestBehaviour; - - private MigrationHelper $migrationHelper; - - private Connection $connection; - - protected function setUp(): void - { - /** @var Connection $connection */ - $connection = $this->getContainer()->get(Connection::class); - $this->connection = $connection; - - $this->connection->rollback(); - - $this->migrationHelper = new MigrationHelper($this->connection); - $this->uninstallPluginAndDeleteLanguages(); - } - - protected function tearDown(): void - { - $this->migrationHelper->createPackLanguageTable(); - $this->migrationHelper->alterLanguageAddPackLanguageColumn(); - $this->migrationHelper->createPackLanguages(); - $this->migrationHelper->createSnippetSets(); - - $this->connection->beginTransaction(); - } - - public function testCreateLanguageTableCorrectly(): void - { - static::assertFalse($this->databaseHasPackLanguageTable()); - - $this->migrationHelper->createPackLanguageTable(); - static::assertTrue($this->databaseHasPackLanguageTable()); - } - - public function testDontAlterLanguageTableBecauseColumnExists(): void - { - $this->migrationHelper->createPackLanguageTable(); - static::assertFalse($this->doesLanguageColumnExist()); - - $this->migrationHelper->alterLanguageAddPackLanguageColumn(); - static::assertTrue($this->doesLanguageColumnExist()); - - // Check again if working correctly, even if column exists - $this->migrationHelper->alterLanguageAddPackLanguageColumn(); - static::assertTrue($this->doesLanguageColumnExist()); - } - - public function testCreatePackLanguagesCorrectly(): void - { - $tables = [PackLanguageDefinition::ENTITY_NAME, LanguageDefinition::ENTITY_NAME]; - $this->migrationHelper->createPackLanguageTable(); - $this->migrationHelper->alterLanguageAddPackLanguageColumn(); - - $counts = $this->getTableCounts($tables); - static::assertEquals(2, $counts[LanguageDefinition::ENTITY_NAME]); - static::assertEquals(0, $counts[PackLanguageDefinition::ENTITY_NAME]); - - $this->migrationHelper->createPackLanguages(); - - $counts = $this->getTableCounts($tables); - static::assertEquals(\count(SwagLanguagePack::SUPPORTED_LANGUAGES) + 2, $counts[LanguageDefinition::ENTITY_NAME]); - static::assertEquals(\count(SwagLanguagePack::SUPPORTED_LANGUAGES), $counts[PackLanguageDefinition::ENTITY_NAME]); - } - - public function testCreatePackLanguagesCorrectlyEvenWithAlreadyInstalledPackLanguages(): void - { - $tables = [PackLanguageDefinition::ENTITY_NAME, LanguageDefinition::ENTITY_NAME]; - $this->migrationHelper->createPackLanguageTable(); - $this->migrationHelper->alterLanguageAddPackLanguageColumn(); - - $counts = $this->getTableCounts($tables); - static::assertEquals(2, $counts[LanguageDefinition::ENTITY_NAME]); - static::assertEquals(0, $counts[PackLanguageDefinition::ENTITY_NAME]); - - // Simulate already having one language installed - $this->createMockPackLanguage(); - $counts = $this->getTableCounts($tables); - static::assertEquals(3, $counts[LanguageDefinition::ENTITY_NAME]); - static::assertEquals(1, $counts[PackLanguageDefinition::ENTITY_NAME]); - - $this->migrationHelper->createPackLanguages(); - - $counts = $this->getTableCounts($tables); - static::assertEquals(\count(SwagLanguagePack::SUPPORTED_LANGUAGES) + 2, $counts[LanguageDefinition::ENTITY_NAME]); - static::assertEquals(\count(SwagLanguagePack::SUPPORTED_LANGUAGES), $counts[PackLanguageDefinition::ENTITY_NAME]); - } - - public function testMissingLocaleWhileCreating(): void - { - $locales = SwagLanguagePack::SUPPORTED_LANGUAGES; - $locales['nonsense'] = 'non-sense'; - $locales['doesntExist'] = 'doesnt-exist'; - - $connectionMock = $this->prepareLocaleConnectionMock($locales); - - $this->migrationHelper->createPackLanguageTable(); - $this->migrationHelper->alterLanguageAddPackLanguageColumn(); - - $this->expectExceptionMessage('No LocaleEntities associated to the following locale codes: bg-BG, bs-BA, cs-CZ, da-DK, el-GR, en-US, es-ES, fi-FI, fr-FR, hi-IN, hr-HR, hu-HU, id-ID, it-IT, ko-KR, lv-LV, nl-NL, nn-NO, pl-PL, pt-PT, ro-RO, ru-RU, sk-SK, sl-SI, sr-RS, sv-SE, tr-TR, uk-UA, vi-VN'); - - $mockedMigrationHelper = new MigrationHelper($connectionMock); - $mockedMigrationHelper->createPackLanguages(); - } - - public function testCreateSnippetSetsCorrectly(): void - { - static::assertFalse($this->databaseHasBaseSnippetSetsForPackLanguages()); - - $this->migrationHelper->createSnippetSets(); - static::assertTrue($this->databaseHasBaseSnippetSetsForPackLanguages()); - - // test again for duplicates, for example when plugin update is triggered - $this->migrationHelper->createSnippetSets(); - static::assertTrue($this->databaseHasBaseSnippetSetsForPackLanguages()); - } - - private function uninstallPluginAndDeleteLanguages(): void - { - /** @var MockObject|UninstallContext $uninstallContext */ - $uninstallContext = $this->getMockBuilder(UninstallContext::class) - ->disableOriginalConstructor() - ->onlyMethods(['keepUserData']) - ->getMock(); - - $uninstallContext - ->expects(static::once()) - ->method('keepUserData') - ->willReturn(false); - - /** @var EntityRepository $languageRepository */ - $languageRepository = $this->getContainer()->get('language.repository'); - - (new Lifecycle($this->connection, $languageRepository)) - ->uninstall($uninstallContext); - - $sql = \str_replace( - ['#table#'], - [LanguageDefinition::ENTITY_NAME], - <<<'SQL' - DELETE FROM `#table#` - WHERE `name` NOT IN ("Deutsch", "English"); - SQL, - ); - - $this->connection->executeStatement($sql); - - $deleteSnippetSetsSql = <<<'SQL' - DELETE FROM `snippet_set` - WHERE `name` NOT IN ("BASE de-DE", "BASE en-GB"); - SQL; - $this->connection->executeStatement($deleteSnippetSetsSql); - } - - private function databaseHasPackLanguageTable(): bool - { - $sql = \str_replace( - ['#table#'], - [PackLanguageDefinition::ENTITY_NAME], - <<<'SQL' - SELECT * - FROM `information_schema`.`TABLES` - WHERE `TABLE_NAME` = "#table#" - AND `TABLE_SCHEMA` = DATABASE(); - SQL, - ); - - return (bool) $this->connection->executeQuery($sql)->fetchOne(); - } - - private function doesLanguageColumnExist(): bool - { - $sql = \str_replace( - ['#table#', '#column#'], - [LanguageDefinition::ENTITY_NAME, PackLanguageDefinition::PACK_LANGUAGE_FOREIGN_KEY_STORAGE_NAME], - <<<'SQL' - SHOW COLUMNS FROM `#table#` - LIKE "#column#"; - SQL, - ); - - return (bool) $this->connection->executeQuery($sql)->fetchOne(); - } - - /** - * @param array $tables - * @return array - */ - private function getTableCounts(array $tables): array - { - $results = []; - foreach ($tables as $table) { - $sql = \str_replace( - ['#table#'], - [$table], - <<<'SQL' - SELECT COUNT(*) as `count` - FROM `#table#`; - SQL, - ); - - $results[$table] = (int) $this->connection->executeQuery($sql)->fetchOne(); - } - - return $results; - } - - /** - * @param array $locales - */ - private function prepareLocaleConnectionMock(array $locales): Connection&MockObject - { - $connectionMock = $this->getMockBuilder(Connection::class) - ->disableOriginalConstructor() - ->getMock(); - - $resultStatementMock = $this->getMockBuilder(Result::class) - ->disableOriginalConstructor() - ->getMock(); - - $resultStatementMock - ->expects(static::once()) - ->method('fetchAllAssociative') - ->willReturn($locales); - - $connectionMock - ->expects(static::once()) - ->method('executeQuery') - ->willReturn($resultStatementMock); - - return $connectionMock; - } - - private function databaseHasBaseSnippetSetsForPackLanguages(): bool - { - $sql = <<<'SQL' - SELECT COUNT(DISTINCT `id`) - FROM `snippet_set`; - SQL; - $snippetSetCount = (int) $this->connection->executeQuery($sql)->fetchOne(); - - // de-DE & en-GB are system default languages so we have to add 2 - return $snippetSetCount === (\count(SwagLanguagePack::SUPPORTED_LANGUAGES) + 2); - } - - private function createMockPackLanguage(): void - { - $localeId = $this->connection->executeQuery(<<<'SQL' - SELECT `locale`.`id` AS `locale_id` - FROM `locale` - LEFT JOIN `language` ON `locale`.`id` = `language`.`locale_id` - WHERE `code` = 'fr-FR'; - SQL)->fetchOne(); - - $insertLanguagesSql = <<<'SQL' - INSERT INTO `language` (`id`, `name`, `locale_id`, `translation_code_id`, `created_at`) - VALUES (:id, :name, :localeId, :translationCodeId, NOW()); - SQL; - - $languageId = Uuid::randomBytes(); - $this->connection->executeStatement($insertLanguagesSql, [ - 'id' => $languageId, - 'name' => 'Français', - 'localeId' => $localeId, - 'translationCodeId' => $localeId, - ]); - - $insertPackLanguagesSql = <<<'SQL' - INSERT INTO `swag_language_pack_language` (`id`, `language_id`, `administration_active`, `sales_channel_active`, `created_at`) - VALUES (:id, :languageId, :administrationActive, :salesChannelActive, NOW()); - - UPDATE `language` - SET swag_language_pack_language_id = :id - WHERE `id` = :languageId; - SQL; - - $this->connection->executeStatement($insertPackLanguagesSql, [ - 'id' => Uuid::randomBytes(), - 'languageId' => $languageId, - 'administrationActive' => 1, - 'salesChannelActive' => 1, - ]); - } -}