From 3fde601c809d021d9306ee16d146a21b438c441d Mon Sep 17 00:00:00 2001 From: maxperei Date: Tue, 24 Dec 2024 15:49:06 +0100 Subject: [PATCH] feat(upgrade): bump codebase to match sylius v[1.12|1.13|1.14] --- .github/workflows/analysis.yaml | 7 +-- .github/workflows/sylius.yaml | 14 ++--- Makefile | 22 +++---- README.md | 58 +++++++++---------- composer.json | 47 +++++++-------- config/routes/attributes.yaml | 5 ++ config/services.yaml | 14 +++++ grumphp.yml | 20 ++++--- .../config/packages/maintenance.yaml | 2 - .../config/routes/maintenance.yaml | 2 +- ruleset/.php_md.xml | 2 +- ruleset/phpstan.neon | 22 +++---- ruleset/rector.php | 30 +++++++--- ruleset/ruleset.xml | 19 ++++++ src/Checker/AdminChecker.php | 13 ++--- src/Checker/BotChecker.php | 4 +- src/Checker/ChannelChecker.php | 10 ++-- src/Checker/EnabledChecker.php | 4 +- src/Checker/IpChecker.php | 4 +- src/Checker/IsMaintenanceCheckerInterface.php | 4 +- src/Checker/ProfilerChecker.php | 4 +- src/Checker/ScheduledChecker.php | 21 +++---- src/Checker/TokenChecker.php | 4 +- src/Command/DisableMaintenanceCommand.php | 19 +++--- src/Command/EnableMaintenanceCommand.php | 15 +++-- .../MaintenanceConfigurationController.php | 25 +++++--- src/Controller/TokenStorageController.php | 15 +++-- src/DependencyInjection/Configuration.php | 19 ------ .../SynoliaSyliusMaintenanceExtension.php | 5 +- .../MaintenanceEventsubscriber.php | 12 ++-- .../MaintenanceConfigurationExporter.php | 8 +-- .../MaintenanceConfigurationFactory.php | 13 ++++- src/FileManager/ConfigurationFileManager.php | 14 ++--- .../Type/MaintenanceConfigurationType.php | 3 +- src/Menu/AdminMenuListener.php | 2 + src/Model/MaintenanceConfiguration.php | 6 +- src/Resources/config/admin_routing.yaml | 15 ----- src/Resources/config/config.yaml | 2 - src/Resources/config/services.yaml | 36 ------------ src/Resources/config/shop_routing.yaml | 1 - src/Storage/TokenStorage.php | 13 +---- src/SynoliaSyliusMaintenancePlugin.php | 5 ++ src/Voter/IsMaintenanceVoter.php | 15 ++--- .../Admin/maintenanceConfiguration.html.twig | 6 +- .../views => templates}/maintenance.html.twig | 1 - tests/PHPUnit/AbstractWebTestCase.php | 2 +- tests/PHPUnit/AssertTrait.php | 6 +- tests/PHPUnit/MaintenanceByChannelTest.php | 2 +- tests/PHPUnit/MaintenanceByFileTest.php | 4 +- ...st.php => MultiChannelMaintenanceTest.php} | 18 +++++- tests/{datas => data}/sylius_fixtures.yaml | 0 .../messages.en.yml | 0 .../messages.fr.yml | 0 53 files changed, 313 insertions(+), 301 deletions(-) create mode 100644 config/routes/attributes.yaml create mode 100644 config/services.yaml delete mode 100644 install/Application/config/packages/maintenance.yaml create mode 100644 ruleset/ruleset.xml delete mode 100644 src/DependencyInjection/Configuration.php delete mode 100644 src/Resources/config/admin_routing.yaml delete mode 100644 src/Resources/config/config.yaml delete mode 100644 src/Resources/config/services.yaml delete mode 100644 src/Resources/config/shop_routing.yaml rename {src/Resources/views => templates}/Admin/maintenanceConfiguration.html.twig (93%) rename {src/Resources/views => templates}/maintenance.html.twig (98%) rename tests/PHPUnit/{MulitChannelMaintenanceTest.php => MultiChannelMaintenanceTest.php} (76%) rename tests/{datas => data}/sylius_fixtures.yaml (100%) rename {src/Resources/translations => translations}/messages.en.yml (100%) rename {src/Resources/translations => translations}/messages.fr.yml (100%) diff --git a/.github/workflows/analysis.yaml b/.github/workflows/analysis.yaml index ecd8d4c..4ca1616 100644 --- a/.github/workflows/analysis.yaml +++ b/.github/workflows/analysis.yaml @@ -2,7 +2,7 @@ name: Analysis 'on': push: branches: - - master + - main paths-ignore: - README.md pull_request: @@ -16,11 +16,10 @@ jobs: fail-fast: false matrix: php: - - 8.1 - 8.2 + - 8.3 symfony: - - '5.4.*' - - '6.3.*' + - '6.4.*' env: APP_ENV: test steps: diff --git a/.github/workflows/sylius.yaml b/.github/workflows/sylius.yaml index be0444a..33dc57f 100644 --- a/.github/workflows/sylius.yaml +++ b/.github/workflows/sylius.yaml @@ -2,7 +2,7 @@ name: Install & Test 'on': push: branches: - - master + - main paths-ignore: - README.md pull_request: @@ -16,20 +16,16 @@ jobs: fail-fast: false matrix: php: - - 8.1 - 8.2 + - 8.3 sylius: - - 1.10.0 - 1.12.0 + - 1.13.0 + - 1.14.0 symfony: - - 5.4 - - 6.3 + - 6.4 node: - 14.x - exclude: - - - sylius: 1.10.0 - symfony: 6.3 env: APP_ENV: test package-name: synolia/sylius-maintenance-plugin diff --git a/Makefile b/Makefile index fbd526e..52e22ea 100644 --- a/Makefile +++ b/Makefile @@ -2,13 +2,14 @@ SHELL=/bin/bash COMPOSER_ROOT=composer TEST_DIRECTORY=tests/Application -CONSOLE=cd tests/Application && php bin/console -e test -COMPOSER=cd tests/Application && composer -YARN=cd tests/Application && yarn +INSTALL_DIRECTORY=install/Application +CONSOLE=cd ${TEST_DIRECTORY} && php bin/console -e test +COMPOSER=cd ${TEST_DIRECTORY} && composer +YARN=cd ${TEST_DIRECTORY} && yarn -SYLIUS_VERSION=1.12.0 -SYMFONY_VERSION=6.1 -PHP_VERSION=8.1 +SYLIUS_VERSION=1.14.0 +SYMFONY_VERSION=6.4 +PHP_VERSION=8.2 PLUGIN_NAME=synolia/sylius-maintenance-plugin ### @@ -19,10 +20,10 @@ install: sylius ## Install Plugin on Sylius [SYLIUS_VERSION=1.12.0] [SYMFONY_VER .PHONY: install reset: ## Remove dependencies -ifneq ("$(wildcard tests/Application/bin/console)","") +ifneq ("$(wildcard ${TEST_DIRECTORY}/bin/console)","") ${CONSOLE} doctrine:database:drop --force --if-exists || true endif - rm -rf tests/Application + rm -rf ${TEST_DIRECTORY} .PHONY: reset phpunit: phpunit-configure phpunit-run ## Run PHPUnit @@ -59,7 +60,8 @@ install-plugin: ${COMPOSER} config minimum-stability "dev" ${COMPOSER} config prefer-stable true ${COMPOSER} req ${PLUGIN_NAME}:* --prefer-source --no-scripts - cp -r install/Application tests + cp -r ${INSTALL_DIRECTORY} tests + cp -r tests/data/* ${TEST_DIRECTORY}/ install-sylius: ${CONSOLE} sylius:install -n -s default @@ -77,7 +79,7 @@ grumphp: vendor/bin/grumphp run help: SHELL=/bin/bash -help: ## Dislay this help +help: ## Display this help @IFS=$$'\n'; for line in `grep -h -E '^[a-zA-Z_#-]+:?.*?##.*$$' $(MAKEFILE_LIST)`; do if [ "$${line:0:2}" = "##" ]; then \ echo $$line | awk 'BEGIN {FS = "## "}; {printf "\033[33m %s\033[0m\n", $$2}'; else \ echo $$line | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m%s\n", $$1, $$2}'; fi; \ diff --git a/README.md b/README.md index 6372582..2c7a7e8 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ | | Version | |:-------|:--------| -| PHP | ^8.0 | -| Sylius | ^1.10 | +| PHP | ^8.2 | +| Sylius | ^1.12 | ## Installation @@ -40,22 +40,15 @@ composer require synolia/sylius-maintenance-plugin ``` -2. Import required config in your `config/packages/_sylius.yaml` file: - - ``` yaml - imports: - - { resource: "@SynoliaSyliusMaintenancePlugin/Resources/config/config.yaml" } - ``` - -3. Import routing in your `config/routes.yaml` file: +2. Import routing in your `config/routes.yaml` file: ``` yaml synolia_maintenance: - resource: "@SynoliaSyliusMaintenancePlugin/Resources/config/admin_routing.yaml" + resource: "@SynoliaSyliusMaintenancePlugin/config/routes/attributes.yaml" prefix: '/%sylius_admin.path_name%' ``` -4. Clear cache +3. Clear cache ``` shell php bin/console cache:clear @@ -65,7 +58,7 @@ - To turn your website under maintenance, please create a file **maintenance.yaml** at the root of your project. - If you want to allow access for some Ips, please add these Ip into **maintenance.yaml** - For example : + For example : ``` yaml ips: [172.16.254.1, 255.255.255.255, 192.0.0.255] @@ -73,28 +66,28 @@ ### You can turn your website under maintenance by console commands : - 1. Enable the plugin +1. Enable the plugin - ``` shell - php bin/console maintenance:enable - ``` - 2. Enable the plugin and add one or multiple ips addresses separated with a space + ``` shell + php bin/console maintenance:enable + ``` +2. Enable the plugin and add one or multiple ips addresses separated with a space - ``` shell - php bin/console maintenance:enable 172.16.254.1 255.255.255.255 192.0.0.255 - ``` - 3. Disable the plugin + ``` shell + php bin/console maintenance:enable 172.16.254.1 255.255.255.255 192.0.0.255 + ``` +3. Disable the plugin - ``` shell - php bin/console maintenance:disable - ``` + ``` shell + php bin/console maintenance:disable + ``` - 4. Remove configuration file using CLI +4. Remove configuration file using CLI - By default, **maintenance.yaml** configuration file remains when running `maintenance:disable` or via admin panel using toggle disable - Nevertheless passing option `[-c|--clear]` to command line above will reset previous saved configuration +By default, **maintenance.yaml** configuration file remains when running `maintenance:disable` or via admin panel using toggle disable +Nevertheless passing option `[-c|--clear]` to command line above will reset previous saved configuration -### You can also turn your website under maintenance in Back Office : +### You can also turn your website under maintenance in Back Office : - Enable/disable the plugin - Allow access for one or multiple ips addresses (optional) @@ -103,11 +96,12 @@ - Grant access to search bots during maintenance (optional) ### If you want to put the **maintenance.yaml** in a directory, please add your directory in .env: + For example : ``` yaml SYNOLIA_MAINTENANCE_DIR=var/maintenance - ``` +``` ### If you want to add cache on the **maintenance.yaml**: @@ -115,7 +109,9 @@ For example : # .env SYNOLIA_MAINTENANCE_CACHE=30 # ttl in seconds ``` -And in project code (for exemple with redis) + +And in project code (for example with redis) + ``` yaml # config/packages/prod/cache.yaml framework: diff --git a/composer.json b/composer.json index efaf642..14aadc5 100644 --- a/composer.json +++ b/composer.json @@ -9,32 +9,32 @@ ], "license": "EUPL-1.2", "require": { - "php": "^8.0", + "php": "^8.2", "jaybizzle/crawler-detect": "^1.2", - "sylius/sylius": "^1.10", + "sylius/sylius": "^1.12", "webmozart/assert": "^1.11" }, "require-dev": { - "dbrekelmans/bdi": "1.0", - "friendsoftwig/twigcs": "6.1.0", - "phpmd/phpmd": "2.13.0", - "phpro/grumphp": "1.15.0", - "phpspec/phpspec": "7.3.0", - "phpstan/extension-installer": "1.2.0", - "phpstan/phpstan": "1.9.7", - "phpstan/phpstan-doctrine": "1.3.29", - "phpstan/phpstan-phpunit": "1.3.3", - "phpstan/phpstan-strict-rules": "1.4.4", - "phpstan/phpstan-webmozart-assert": "1.2.2", - "phpunit/phpunit": "9.5.27", - "rector/rector": "^0.15.2", - "sylius-labs/coding-standard": "4.3.0", - "symfony/browser-kit": "6.0.11", - "symfony/debug-bundle": "6.0.11", - "symfony/dotenv": "6.0.5", - "symfony/intl": "6.0.15", - "symfony/panther": "2.0.1", - "symfony/web-profiler-bundle": "6.0.17" + "dbrekelmans/bdi": "^1.0", + "friendsoftwig/twigcs": "^6.4.0", + "php-parallel-lint/php-parallel-lint": "^1.4", + "phpmd/phpmd": "^2.13", + "phpro/grumphp": "^2.0", + "phpstan/extension-installer": "^1.3", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpstan/phpstan-webmozart-assert": "^2.0", + "phpunit/phpunit": "^9.5", + "povils/phpmnd": "^3.0", + "rector/rector": "^2.0", + "squizlabs/php_codesniffer": "^3.11", + "sylius-labs/coding-standard": "^4.3", + "symfony/browser-kit": "^6.4", + "symfony/debug-bundle": "^6.4", + "symfony/dotenv": "^6.4", + "symfony/intl": "^6.4", + "symfony/panther": "^2.0", + "symfony/web-profiler-bundle": "^6.4" }, "config": { "sort-packages": true, @@ -42,7 +42,8 @@ "dealerdirect/phpcodesniffer-composer-installer": true, "symfony/thanks": true, "phpro/grumphp": true, - "phpstan/extension-installer": true + "phpstan/extension-installer": true, + "php-http/discovery": true } }, "autoload": { diff --git a/config/routes/attributes.yaml b/config/routes/attributes.yaml new file mode 100644 index 0000000..b9abc96 --- /dev/null +++ b/config/routes/attributes.yaml @@ -0,0 +1,5 @@ +controllers: + resource: + path: ../../src/Controller/ + namespace: Synolia\SyliusMaintenancePlugin\Controller + type: attribute \ No newline at end of file diff --git a/config/services.yaml b/config/services.yaml new file mode 100644 index 0000000..5364030 --- /dev/null +++ b/config/services.yaml @@ -0,0 +1,14 @@ +parameters: + env(SYNOLIA_MAINTENANCE_DIR): '' + synolia_maintenance_dir: '%env(resolve:SYNOLIA_MAINTENANCE_DIR)%' + env(SYNOLIA_MAINTENANCE_CACHE): 0 + synolia_maintenance_cache: '%env(resolve:int:SYNOLIA_MAINTENANCE_CACHE)%' + +services: + _defaults: + autowire: true + autoconfigure: true + + Synolia\SyliusMaintenancePlugin\: + resource: '../src/*' + exclude: '../src/{SynoliaSyliusMaintenancePlugin.php}' diff --git a/grumphp.yml b/grumphp.yml index c33d031..004ffba 100644 --- a/grumphp.yml +++ b/grumphp.yml @@ -5,25 +5,31 @@ grumphp: tasks: composer: no_check_all: true - git_blacklist: - keywords: - - 'var_dump' - - 'print_r' - - 'die\(' - - 'console\.' - triggered_by: [php, twig, js] jsonlint: detect_key_conflicts: true + phplint: + exclude: ['vendor', 'tests/Application/*'] + triggered_by: ['php'] phpmd: ruleset: ['ruleset/.php_md.xml'] phpstan: level: ~ configuration: 'ruleset/phpstan.neon' + use_grumphp_paths: false yamllint: parse_custom_tags: true ecs: config: 'ruleset/ecs.php' no-progress-bar: true + phpmnd: + directory: src twigcs: path: 'src/' severity: error + phpcs: + standard: "ruleset" + warning_severity: 0 + whitelist_patterns: + - 'src' + exclude: + - 'PSR12.Files.FileHeader' \ No newline at end of file diff --git a/install/Application/config/packages/maintenance.yaml b/install/Application/config/packages/maintenance.yaml deleted file mode 100644 index 63a3449..0000000 --- a/install/Application/config/packages/maintenance.yaml +++ /dev/null @@ -1,2 +0,0 @@ -imports: - - { resource: "@SynoliaSyliusMaintenancePlugin/Resources/config/config.yaml" } diff --git a/install/Application/config/routes/maintenance.yaml b/install/Application/config/routes/maintenance.yaml index 208a6fc..8986cdd 100644 --- a/install/Application/config/routes/maintenance.yaml +++ b/install/Application/config/routes/maintenance.yaml @@ -1,3 +1,3 @@ synolia_maintenance: - resource: "@SynoliaSyliusMaintenancePlugin/Resources/config/admin_routing.yaml" + resource: "@SynoliaSyliusMaintenancePlugin/config/routes/attributes.yaml" prefix: '/%sylius_admin.path_name%' diff --git a/ruleset/.php_md.xml b/ruleset/.php_md.xml index 1c5a25d..a3c20c9 100644 --- a/ruleset/.php_md.xml +++ b/ruleset/.php_md.xml @@ -26,7 +26,7 @@ - + diff --git a/ruleset/phpstan.neon b/ruleset/phpstan.neon index 2d176b4..97de969 100644 --- a/ruleset/phpstan.neon +++ b/ruleset/phpstan.neon @@ -1,24 +1,18 @@ parameters: level: max reportUnmatchedIgnoredErrors: false - checkMissingIterableValueType: false + treatPhpDocTypesAsCertain: false + paths: + - ../src bootstrapFiles: - ../vendor/autoload.php excludePaths: - # Makes PHPStan crash - - '../src/DependencyInjection/Configuration.php' - - '../ruleset/ecs.php' - - # Test dependencies - - '../tests/Application/' - - '../tests/PHPUnit' - - - '../bin/' - + - ../src/DependencyInjection/Configuration.php? + - ../tests/Application/? + - ../tests/PHPUnit ignoreErrors: + - identifier: missingType.iterableValue + - identifier: missingType.generics - '/Parameter #1 \$configuration of method Symfony\\Component\\DependencyInjection\\Extension\\Extension::processConfiguration\(\) expects Symfony\\Component\\Config\\Definition\\ConfigurationInterface, Symfony\\Component\\Config\\Definition\\ConfigurationInterface\|null given\./' - '#Call to an undefined method Sylius\\Component\\Channel\\Repository\\ChannelRepositoryInterface::count\(\)\.#' - # Error not rightely reported because of Symfony 4.4 - - "#^Call to function method_exists\\(\\) with Symfony\\\\Component\\\\HttpFoundation\\\\RequestStack and '.*' will always evaluate to true\\.$#" - "#^Call to an undefined method Symfony\\\\Component\\\\HttpFoundation\\\\Session\\\\SessionInterface\\:\\:getFlashBag\\(\\)\\.$#" - - "#^Call to an undefined method Symfony\\\\Component\\\\HttpFoundation\\\\RequestStack\\:\\:getMasterRequest\\(\\)\\.$#" diff --git a/ruleset/rector.php b/ruleset/rector.php index c771605..adfbe1e 100644 --- a/ruleset/rector.php +++ b/ruleset/rector.php @@ -3,16 +3,28 @@ declare(strict_types=1); use Rector\Config\RectorConfig; -use Rector\Set\ValueObject\LevelSetList; +use Rector\Set\ValueObject\SetList; +use Rector\Symfony\Set\SymfonySetList; -return static function (RectorConfig $rectorConfig): void { - $rectorConfig->paths([ +return RectorConfig::configure() + ->withPaths([ dirname(__DIR__) . '/src', dirname(__DIR__) . '/tests/PHPUnit', + ]) + ->withPHPStanConfigs([__DIR__ . '/phpstan.neon']) + ->withPhpSets(php82: true) + ->withAttributesSets(symfony: true, doctrine: true) + ->withPreparedSets( + deadCode: true, + codeQuality: true, + doctrineCodeQuality: true, + symfonyConfigs: true, + ) + ->withTypeCoverageLevel(0) + ->withSets([ + SymfonySetList::SYMFONY_60, + SymfonySetList::SYMFONY_61, + SymfonySetList::SYMFONY_62, + SymfonySetList::SYMFONY_63, + SymfonySetList::SYMFONY_64, ]); - - $rectorConfig->sets([ - LevelSetList::UP_TO_PHP_74, - LevelSetList::UP_TO_PHP_80, - ]); -}; diff --git a/ruleset/ruleset.xml b/ruleset/ruleset.xml new file mode 100644 index 0000000..3008a56 --- /dev/null +++ b/ruleset/ruleset.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/Checker/AdminChecker.php b/src/Checker/AdminChecker.php index a1a6738..3758295 100644 --- a/src/Checker/AdminChecker.php +++ b/src/Checker/AdminChecker.php @@ -15,6 +15,8 @@ class AdminChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 70; + public function __construct( protected ParameterBagInterface $params, protected RequestStack $requestStack, @@ -24,7 +26,7 @@ public function __construct( public static function getDefaultPriority(): int { - return 70; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool @@ -35,14 +37,7 @@ public function isMaintenance(MaintenanceConfiguration $configuration, Request $ $adminPrefix = \DIRECTORY_SEPARATOR . $adminPrefix; if (str_starts_with($getRequestUri, $adminPrefix)) { - if (method_exists($this->requestStack, 'getMainRequest')) { - $request = $this->requestStack->getMainRequest(); - } - - /** @TODO Drop after remove Symfony 4.4 compatibility */ - if (method_exists($this->requestStack, 'getMasterRequest')) { - $request = $this->requestStack->getMasterRequest(); - } + $request = $this->requestStack->getMainRequest(); Assert::isInstanceOf($request, Request::class); if ($request === $this->requestStack->getCurrentRequest()) { diff --git a/src/Checker/BotChecker.php b/src/Checker/BotChecker.php index 5b2a0eb..6ff9a1d 100644 --- a/src/Checker/BotChecker.php +++ b/src/Checker/BotChecker.php @@ -11,9 +11,11 @@ class BotChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 90; + public static function getDefaultPriority(): int { - return 90; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool diff --git a/src/Checker/ChannelChecker.php b/src/Checker/ChannelChecker.php index c2644eb..c113cbd 100644 --- a/src/Checker/ChannelChecker.php +++ b/src/Checker/ChannelChecker.php @@ -12,6 +12,8 @@ class ChannelChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 60; + public function __construct( protected ChannelRepositoryInterface $channelRepository, protected ChannelContextInterface $channelContext, @@ -20,15 +22,13 @@ public function __construct( public static function getDefaultPriority(): int { - return 60; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool { - if ($this->channelRepository->count([]) > 1) { - if (!\in_array($this->channelContext->getChannel()->getCode(), $configuration->getChannels(), true)) { - return IsMaintenanceVoterInterface::ACCESS_GRANTED; - } + if ($this->channelRepository->count([]) > 1 && !\in_array($this->channelContext->getChannel()->getCode(), $configuration->getChannels(), true)) { + return IsMaintenanceVoterInterface::ACCESS_GRANTED; } return IsMaintenanceVoterInterface::ACCESS_DENIED; diff --git a/src/Checker/EnabledChecker.php b/src/Checker/EnabledChecker.php index 5abacc1..73ac178 100644 --- a/src/Checker/EnabledChecker.php +++ b/src/Checker/EnabledChecker.php @@ -10,9 +10,11 @@ class EnabledChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 100; + public static function getDefaultPriority(): int { - return 100; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool diff --git a/src/Checker/IpChecker.php b/src/Checker/IpChecker.php index c9cc2a5..f570528 100644 --- a/src/Checker/IpChecker.php +++ b/src/Checker/IpChecker.php @@ -10,9 +10,11 @@ class IpChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 90; + public static function getDefaultPriority(): int { - return 90; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool diff --git a/src/Checker/IsMaintenanceCheckerInterface.php b/src/Checker/IsMaintenanceCheckerInterface.php index 1c415ca..620919b 100644 --- a/src/Checker/IsMaintenanceCheckerInterface.php +++ b/src/Checker/IsMaintenanceCheckerInterface.php @@ -4,13 +4,13 @@ namespace Synolia\SyliusMaintenancePlugin\Checker; +use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag; use Symfony\Component\HttpFoundation\Request; use Synolia\SyliusMaintenancePlugin\Model\MaintenanceConfiguration; +#[AutoconfigureTag] interface IsMaintenanceCheckerInterface { - public const TAG_ID = 'synolia_maintenance.checker.is_maintenance'; - public static function getDefaultPriority(): int; public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool; diff --git a/src/Checker/ProfilerChecker.php b/src/Checker/ProfilerChecker.php index 1e92a2d..a6376a7 100644 --- a/src/Checker/ProfilerChecker.php +++ b/src/Checker/ProfilerChecker.php @@ -10,9 +10,11 @@ class ProfilerChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 30; + public static function getDefaultPriority(): int { - return 30; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool diff --git a/src/Checker/ScheduledChecker.php b/src/Checker/ScheduledChecker.php index d023eb1..4159e59 100644 --- a/src/Checker/ScheduledChecker.php +++ b/src/Checker/ScheduledChecker.php @@ -10,16 +10,19 @@ class ScheduledChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 80; + public static function getDefaultPriority(): int { - return 80; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool { - if (false === $this->isActuallyScheduledMaintenance($configuration) && - (null !== $configuration->getStartDate() || - null !== $configuration->getEndDate()) + if ( + false === $this->isActuallyScheduledMaintenance($configuration) && + ($configuration->getStartDate() instanceof \DateTime || + $configuration->getEndDate() instanceof \DateTime) ) { return IsMaintenanceVoterInterface::ACCESS_GRANTED; } @@ -33,18 +36,16 @@ private function isActuallyScheduledMaintenance(MaintenanceConfiguration $mainte $startDate = $maintenanceConfiguration->getStartDate(); $endDate = $maintenanceConfiguration->getEndDate(); // Now is between startDate and endDate - if ($startDate !== null && $endDate !== null && ($now >= $startDate) && ($now <= $endDate)) { + if ($startDate instanceof \DateTime && $endDate instanceof \DateTime && ($now >= $startDate) && ($now <= $endDate)) { return true; } // No enddate provided, now is greater than startDate - if ($startDate !== null && $endDate === null && ($now >= $startDate)) { + if ($startDate instanceof \DateTime && !$endDate instanceof \DateTime && ($now >= $startDate)) { return true; } + // No startdate provided, now is before than enddate - if ($endDate !== null && $startDate === null && ($now <= $endDate)) { - return true; - } // No schedule date - return false; + return $endDate instanceof \DateTime && !$startDate instanceof \DateTime && $now <= $endDate; } } diff --git a/src/Checker/TokenChecker.php b/src/Checker/TokenChecker.php index 4e855f5..5a86f40 100644 --- a/src/Checker/TokenChecker.php +++ b/src/Checker/TokenChecker.php @@ -11,9 +11,11 @@ class TokenChecker implements IsMaintenanceCheckerInterface { + private const PRIORITY = 20; + public static function getDefaultPriority(): int { - return 20; + return self::PRIORITY; } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool diff --git a/src/Command/DisableMaintenanceCommand.php b/src/Command/DisableMaintenanceCommand.php index 7a786f3..529a20e 100644 --- a/src/Command/DisableMaintenanceCommand.php +++ b/src/Command/DisableMaintenanceCommand.php @@ -4,6 +4,7 @@ namespace Synolia\SyliusMaintenancePlugin\Command; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -14,16 +15,15 @@ use Synolia\SyliusMaintenancePlugin\Factory\MaintenanceConfigurationFactory; use Synolia\SyliusMaintenancePlugin\FileManager\ConfigurationFileManager; +#[AsCommand(name: 'maintenance:disable', description: 'Disable maintenance plugin')] final class DisableMaintenanceCommand extends Command { - protected static $defaultName = 'maintenance:disable'; - public function __construct( - private ConfigurationFileManager $configurationFileManager, - private TranslatorInterface $translator, - private CacheInterface $synoliaMaintenanceCache, - private MaintenanceConfigurationFactory $configurationFactory, - private MaintenanceConfigurationExporter $configurationExporter, + private readonly ConfigurationFileManager $configurationFileManager, + private readonly TranslatorInterface $translator, + private readonly CacheInterface $synoliaMaintenanceCache, + private readonly MaintenanceConfigurationFactory $configurationFactory, + private readonly MaintenanceConfigurationExporter $configurationExporter, ) { parent::__construct(); } @@ -31,7 +31,6 @@ public function __construct( protected function configure(): void { $this - ->setDescription('Disable maintenance plugin') ->addOption('clear', 'c', InputOption::VALUE_NONE, 'Reset maintenance mode') ->setHelp('This command allows you to disable or delete the maintenance.yaml') ; @@ -48,11 +47,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->configurationFileManager->deleteMaintenanceFile(); $output->writeln($this->translator->trans('maintenance.ui.message_reset')); - return 0; + return Command::SUCCESS; } $output->writeln($this->translator->trans('maintenance.ui.message_disabled')); - return 0; + return Command::SUCCESS; } } diff --git a/src/Command/EnableMaintenanceCommand.php b/src/Command/EnableMaintenanceCommand.php index 9a3b4ea..ebbb53b 100644 --- a/src/Command/EnableMaintenanceCommand.php +++ b/src/Command/EnableMaintenanceCommand.php @@ -6,6 +6,7 @@ use Sylius\Component\Channel\Repository\ChannelRepositoryInterface; use Sylius\Component\Core\Model\ChannelInterface; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -17,16 +18,15 @@ use Synolia\SyliusMaintenancePlugin\FileManager\ConfigurationFileManager; use Synolia\SyliusMaintenancePlugin\Model\MaintenanceConfiguration; +#[AsCommand(name: 'maintenance:enable', description: 'Turn your website under maintenance.')] final class EnableMaintenanceCommand extends Command { - protected static $defaultName = 'maintenance:enable'; - public function __construct( - private TranslatorInterface $translator, - private MaintenanceConfigurationExporter $maintenanceExporter, - private MaintenanceConfigurationFactory $configurationFactory, - private CacheInterface $synoliaMaintenanceCache, - private ChannelRepositoryInterface $channelRepository, + private readonly TranslatorInterface $translator, + private readonly MaintenanceConfigurationExporter $maintenanceExporter, + private readonly MaintenanceConfigurationFactory $configurationFactory, + private readonly CacheInterface $synoliaMaintenanceCache, + private readonly ChannelRepositoryInterface $channelRepository, ) { parent::__construct(); } @@ -34,7 +34,6 @@ public function __construct( protected function configure(): void { $this - ->setDescription('Turn your website under maintenance.') ->addArgument('ips_address', InputArgument::IS_ARRAY, 'Add ips addresses (separate multiple ips with a space)') ->setHelp('This command allows you to create the maintenance.yaml and also allows you to put the ips into this file.') ; diff --git a/src/Controller/MaintenanceConfigurationController.php b/src/Controller/MaintenanceConfigurationController.php index 0cd412c..fd53173 100644 --- a/src/Controller/MaintenanceConfigurationController.php +++ b/src/Controller/MaintenanceConfigurationController.php @@ -7,6 +7,9 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface; +use Symfony\Component\HttpKernel\Attribute\AsController; +use Symfony\Component\Routing\Attribute\Route; use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Translation\TranslatorInterface; use Synolia\SyliusMaintenancePlugin\Exporter\MaintenanceConfigurationExporter; @@ -14,27 +17,31 @@ use Synolia\SyliusMaintenancePlugin\FileManager\ConfigurationFileManager; use Synolia\SyliusMaintenancePlugin\Form\Type\MaintenanceConfigurationType; +#[AsController] final class MaintenanceConfigurationController extends AbstractController { public function __construct( - private TranslatorInterface $translator, - private MaintenanceConfigurationExporter $maintenanceExporter, - private MaintenanceConfigurationFactory $configurationFactory, - private CacheInterface $synoliaMaintenanceCache, + private readonly TranslatorInterface $translator, + private readonly MaintenanceConfigurationExporter $maintenanceExporter, + private readonly MaintenanceConfigurationFactory $configurationFactory, + private readonly CacheInterface $synoliaMaintenanceCache, ) { } + #[Route('/maintenance/configuration', name: 'sylius_admin_maintenance_configuration', defaults: ['_sylius' => ['permission' => true, 'section' => 'admin', 'alias' => 'plugin_synolia_maintenance']], methods: ['GET', 'POST'])] public function __invoke(Request $request): Response { $maintenanceConfiguration = $this->configurationFactory->get(); - $form = $this->createForm(MaintenanceConfigurationType::class, $maintenanceConfiguration); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { - if (null !== $maintenanceConfiguration->getEndDate() && $maintenanceConfiguration->getEndDate() < (new \DateTime())) { + /** @var FlashBagInterface $flashBag */ + $flashBag = $request->getSession()->getFlashBag(); + + if ($maintenanceConfiguration->getEndDate() instanceof \DateTime && $maintenanceConfiguration->getEndDate() < (new \DateTime())) { $maintenanceConfiguration->setEnabled(false); - $request->getSession()->getFlashBag()->add('error', $this->translator->trans('maintenance.ui.message_end_date_in_the_past')); + $flashBag->add('error', $this->translator->trans('maintenance.ui.message_end_date_in_the_past')); } $this->maintenanceExporter->export($maintenanceConfiguration); @@ -45,11 +52,11 @@ public function __invoke(Request $request): Response $this->synoliaMaintenanceCache->delete(ConfigurationFileManager::MAINTENANCE_CACHE_KEY); - $request->getSession()->getFlashBag()->add('success', $this->translator->trans($message)); + $flashBag->add('success', $this->translator->trans($message)); } return $this->render('@SynoliaSyliusMaintenancePlugin/Admin/maintenanceConfiguration.html.twig', [ - 'form' => $form->createView(), + 'form' => $form, ]); } } diff --git a/src/Controller/TokenStorageController.php b/src/Controller/TokenStorageController.php index 3fc89ce..7eee75f 100644 --- a/src/Controller/TokenStorageController.php +++ b/src/Controller/TokenStorageController.php @@ -7,26 +7,33 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface; +use Symfony\Component\HttpKernel\Attribute\AsController; +use Symfony\Component\Routing\Attribute\Route; use Symfony\Contracts\Translation\TranslatorInterface; use Synolia\SyliusMaintenancePlugin\Factory\MaintenanceConfigurationFactory; use Synolia\SyliusMaintenancePlugin\Storage\TokenStorage; +#[AsController] final class TokenStorageController extends AbstractController { public function __construct( - private MaintenanceConfigurationFactory $configurationFactory, - private TokenStorage $tokenStorage, - private TranslatorInterface $translator, + private readonly MaintenanceConfigurationFactory $configurationFactory, + private readonly TokenStorage $tokenStorage, + private readonly TranslatorInterface $translator, ) { } + #[Route('/maintenance/token-storage', name: 'sylius_admin_maintenance_token_storage', methods: ['GET', 'POST'])] public function __invoke(Request $request): Response { $maintenanceConfiguration = $this->configurationFactory->get(); if ($maintenanceConfiguration->isEnabled()) { $this->tokenStorage->set($maintenanceConfiguration->getToken()); - $request->getSession()->getFlashBag()->add('success', $this->translator->trans('maintenance.ui.form.token_storage.message')); + /** @var FlashBagInterface $flashBag */ + $flashBag = $request->getSession()->getFlashBag(); + $flashBag->add('success', $this->translator->trans('maintenance.ui.form.token_storage.message')); } return $this->redirectToRoute('sylius_admin_maintenance_configuration'); diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php deleted file mode 100644 index 8176637..0000000 --- a/src/DependencyInjection/Configuration.php +++ /dev/null @@ -1,19 +0,0 @@ -getRootNode(); - - return $treeBuilder; - } -} diff --git a/src/DependencyInjection/SynoliaSyliusMaintenanceExtension.php b/src/DependencyInjection/SynoliaSyliusMaintenanceExtension.php index 608b8b8..6b1ce3b 100644 --- a/src/DependencyInjection/SynoliaSyliusMaintenanceExtension.php +++ b/src/DependencyInjection/SynoliaSyliusMaintenanceExtension.php @@ -11,9 +11,12 @@ final class SynoliaSyliusMaintenanceExtension extends Extension { + /** + * @inheritdoc + */ public function load(array $configs, ContainerBuilder $container): void { - $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); + $loader = new YamlFileLoader($container, new FileLocator(\dirname(__DIR__, 2) . '/config')); $loader->load('services.yaml'); } diff --git a/src/EventSubscriber/MaintenanceEventsubscriber.php b/src/EventSubscriber/MaintenanceEventsubscriber.php index 2bff3aa..d41ce42 100644 --- a/src/EventSubscriber/MaintenanceEventsubscriber.php +++ b/src/EventSubscriber/MaintenanceEventsubscriber.php @@ -4,6 +4,7 @@ namespace Synolia\SyliusMaintenancePlugin\EventSubscriber; +use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; @@ -15,13 +16,14 @@ use Synolia\SyliusMaintenancePlugin\Voter\IsMaintenanceVoterInterface; use Twig\Environment; -final class MaintenanceEventsubscriber implements EventSubscriberInterface +final readonly class MaintenanceEventsubscriber implements EventSubscriberInterface { public function __construct( private Environment $twig, private MaintenanceConfigurationFactory $configurationFactory, private IsMaintenanceVoterInterface $isMaintenanceVoter, private CacheInterface $synoliaMaintenanceCache, + #[Autowire(param: 'synolia_maintenance_cache')] private int $maintenanceCache, ) { } @@ -37,13 +39,7 @@ public function handle(RequestEvent $event): void { $configuration = $this->getMaintenanceConfiguration(); - /** @phpstan-ignore-next-line */ /** Call to function method_exists() with RequestEvent and 'isMainRequest' will always evaluate to true. */ - if (method_exists($event, 'isMainRequest') && !$event->isMainRequest()) { - return; - } - - /** @TODO Drop after remove Symfony 4.4 compatibility */ - if (method_exists($event, 'isMasterRequest') && !$event->isMasterRequest()) { + if (!$event->isMainRequest()) { return; } diff --git a/src/Exporter/MaintenanceConfigurationExporter.php b/src/Exporter/MaintenanceConfigurationExporter.php index fcffd2e..c963caa 100644 --- a/src/Exporter/MaintenanceConfigurationExporter.php +++ b/src/Exporter/MaintenanceConfigurationExporter.php @@ -7,7 +7,7 @@ use Synolia\SyliusMaintenancePlugin\FileManager\ConfigurationFileManager; use Synolia\SyliusMaintenancePlugin\Model\MaintenanceConfiguration; -final class MaintenanceConfigurationExporter +final readonly class MaintenanceConfigurationExporter { public function __construct(private ConfigurationFileManager $configurationFileManager) { @@ -26,7 +26,7 @@ public function export(MaintenanceConfiguration $configuration): void $dataToExport['custom_message'] = $customMessage; } $channels = $configuration->getChannels(); - if (0 !== count($channels)) { + if ([] !== $channels) { $dataToExport['channels'] = $channels; } $token = $configuration->getToken(); @@ -49,10 +49,10 @@ private function getSchedulerArray(?\DateTimeInterface $startDate, ?\DateTimeInt { $scheduler = ['scheduler' => []]; - if (null !== $startDate) { + if ($startDate instanceof \DateTimeInterface) { $scheduler['scheduler']['start_date'] = $startDate->format('Y-m-d H:i:s'); } - if (null !== $endDate) { + if ($endDate instanceof \DateTimeInterface) { $scheduler['scheduler']['end_date'] = $endDate->format('Y-m-d H:i:s'); } if ([] === $scheduler['scheduler']) { diff --git a/src/Factory/MaintenanceConfigurationFactory.php b/src/Factory/MaintenanceConfigurationFactory.php index 6c5901d..a15661d 100644 --- a/src/Factory/MaintenanceConfigurationFactory.php +++ b/src/Factory/MaintenanceConfigurationFactory.php @@ -8,7 +8,7 @@ use Synolia\SyliusMaintenancePlugin\FileManager\ConfigurationFileManager; use Synolia\SyliusMaintenancePlugin\Model\MaintenanceConfiguration; -final class MaintenanceConfigurationFactory +final readonly class MaintenanceConfigurationFactory { public function __construct(private ConfigurationFileManager $configurationFileManager) { @@ -48,6 +48,17 @@ public static function map(MaintenanceConfiguration $maintenanceConfiguration, ? 'allow_bots' => false, 'enabled' => true, ]); + /** + * @var array{ + * 'ips': array, + * 'channels': array, + * 'scheduler': array{'start_date': string, 'end_date': string}, + * 'custom_message': string, + * 'token': string, + * 'allow_bots': bool, + * 'enabled': bool, + * } $options + */ $options = $resolver->resolve($options); $ips = implode(',', $options['ips']); diff --git a/src/FileManager/ConfigurationFileManager.php b/src/FileManager/ConfigurationFileManager.php index 15a9b90..b48f80d 100644 --- a/src/FileManager/ConfigurationFileManager.php +++ b/src/FileManager/ConfigurationFileManager.php @@ -4,23 +4,23 @@ namespace Synolia\SyliusMaintenancePlugin\FileManager; +use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Yaml; use Webmozart\Assert\Assert; -final class ConfigurationFileManager +final readonly class ConfigurationFileManager { public const MAINTENANCE_CACHE_KEY = 'synolia_maintenance_configuration'; private const MAINTENANCE_FILE = 'maintenance.yaml'; - private string $maintenanceDirectory; - - public function __construct(private Filesystem $filesystem, KernelInterface $kernel, string $maintenanceDirectory) - { - $this->maintenanceDirectory = $kernel->getProjectDir() . '/' . $maintenanceDirectory; + public function __construct( + private Filesystem $filesystem, + #[Autowire(value: '%kernel.project_dir%/%synolia_maintenance_dir%')] + private string $maintenanceDirectory, + ) { } public function hasMaintenanceFile(): bool diff --git a/src/Form/Type/MaintenanceConfigurationType.php b/src/Form/Type/MaintenanceConfigurationType.php index 72250ee..40ab05a 100644 --- a/src/Form/Type/MaintenanceConfigurationType.php +++ b/src/Form/Type/MaintenanceConfigurationType.php @@ -19,7 +19,7 @@ final class MaintenanceConfigurationType extends AbstractType { - public function __construct(private ChannelRepositoryInterface $channelRepository) + public function __construct(private readonly ChannelRepositoryInterface $channelRepository) { } @@ -82,6 +82,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->get('channels') ->addModelTransformer(new CallbackTransformer( fn (array $codesToChannels): array => \array_map( + /** @phpstan-ignore-next-line */ fn (string $channelCode): ?ChannelInterface => $this->channelRepository->findOneByCode($channelCode), $codesToChannels, ), diff --git a/src/Menu/AdminMenuListener.php b/src/Menu/AdminMenuListener.php index 01329fc..8f9e88f 100644 --- a/src/Menu/AdminMenuListener.php +++ b/src/Menu/AdminMenuListener.php @@ -6,7 +6,9 @@ use Knp\Menu\ItemInterface; use Sylius\Bundle\UiBundle\Menu\Event\MenuBuilderEvent; +use Symfony\Component\EventDispatcher\Attribute\AsEventListener; +#[AsEventListener(event: 'sylius.menu.admin.main', method: 'addAdminMenuItems')] final class AdminMenuListener { public function addAdminMenuItems(MenuBuilderEvent $event): void diff --git a/src/Model/MaintenanceConfiguration.php b/src/Model/MaintenanceConfiguration.php index 5107576..e547d24 100644 --- a/src/Model/MaintenanceConfiguration.php +++ b/src/Model/MaintenanceConfiguration.php @@ -14,9 +14,9 @@ class MaintenanceConfiguration private string $customMessage = ''; - private ?\DateTime $startDate; + private ?\DateTime $startDate = null; - private ?\DateTime $endDate; + private ?\DateTime $endDate = null; private array $channels = []; @@ -26,8 +26,6 @@ class MaintenanceConfiguration public function __construct() { - $this->startDate = null; - $this->endDate = null; $this->token = bin2hex(random_bytes(16)); } diff --git a/src/Resources/config/admin_routing.yaml b/src/Resources/config/admin_routing.yaml deleted file mode 100644 index 32505b5..0000000 --- a/src/Resources/config/admin_routing.yaml +++ /dev/null @@ -1,15 +0,0 @@ -sylius_admin_maintenance_configuration: - path: /maintenance/configuration - methods: [ GET|POST ] - defaults: - _controller: Synolia\SyliusMaintenancePlugin\Controller\MaintenanceConfigurationController - _sylius: - permission: true - section: admin - alias: plugin_synolia_maintenance - -sylius_admin_maintenance_token_storage: - path: /maintenance/token-storage - methods: [GET, POST] - defaults: - _controller: Synolia\SyliusMaintenancePlugin\Controller\TokenStorageController diff --git a/src/Resources/config/config.yaml b/src/Resources/config/config.yaml deleted file mode 100644 index 3786cbc..0000000 --- a/src/Resources/config/config.yaml +++ /dev/null @@ -1,2 +0,0 @@ -imports: - - { resource: "@SynoliaSyliusMaintenancePlugin/Resources/config/services.yaml" } diff --git a/src/Resources/config/services.yaml b/src/Resources/config/services.yaml deleted file mode 100644 index 982830d..0000000 --- a/src/Resources/config/services.yaml +++ /dev/null @@ -1,36 +0,0 @@ -parameters: - env(SYNOLIA_MAINTENANCE_DIR): '' - synolia_maintenance_dir: '%env(resolve:SYNOLIA_MAINTENANCE_DIR)%' - env(SYNOLIA_MAINTENANCE_CACHE): 0 - synolia_maintenance_cache: '%env(resolve:int:SYNOLIA_MAINTENANCE_CACHE)%' - -services: - _defaults: - autowire: true - autoconfigure: true - public: false - bind: - $maintenanceDirectory: '%synolia_maintenance_dir%' - $maintenanceCache: '%synolia_maintenance_cache%' - - _instanceof: - Synolia\SyliusMaintenancePlugin\Checker\IsMaintenanceCheckerInterface: - tags: - - { name: !php/const Synolia\SyliusMaintenancePlugin\Checker\IsMaintenanceCheckerInterface::TAG_ID } - - Synolia\SyliusMaintenancePlugin\: - resource: '../../*' - exclude: '../../{Controller,Migrations,SynoliaSyliusMaintenancePlugin.php}' - - Synolia\SyliusMaintenancePlugin\Controller\: - resource: '../../Controller/*' - tags: ['controller.service_arguments'] - - Synolia\SyliusMaintenancePlugin\Menu\AdminMenuListener: - tags: - - { name: kernel.event_listener, event: sylius.menu.admin.main, method: addAdminMenuItems } - - Synolia\SyliusMaintenancePlugin\Voter\IsMaintenanceVoterInterface: - class: Synolia\SyliusMaintenancePlugin\Voter\IsMaintenanceVoter - arguments: - - !tagged_iterator { tag: !php/const Synolia\SyliusMaintenancePlugin\Checker\IsMaintenanceCheckerInterface::TAG_ID } diff --git a/src/Resources/config/shop_routing.yaml b/src/Resources/config/shop_routing.yaml deleted file mode 100644 index 3982ed5..0000000 --- a/src/Resources/config/shop_routing.yaml +++ /dev/null @@ -1 +0,0 @@ -# Delete these routes and define your own shop routes here diff --git a/src/Storage/TokenStorage.php b/src/Storage/TokenStorage.php index 383538c..39b86a9 100644 --- a/src/Storage/TokenStorage.php +++ b/src/Storage/TokenStorage.php @@ -6,7 +6,7 @@ use Symfony\Component\HttpFoundation\RequestStack; -final class TokenStorage +final readonly class TokenStorage { public const MAINTENANCE_TOKEN_NAME = 'synolia_maintenance_token'; @@ -16,20 +16,13 @@ public function __construct(private RequestStack $requestStack) public function set(string $token): void { - if (method_exists($this->requestStack, 'getMainRequest')) { - $this->requestStack->getMainRequest()?->getSession()->set(self::MAINTENANCE_TOKEN_NAME, $token); - } - - /** @TODO Drop after remove Symfony 4.4 compatibility */ - if (method_exists($this->requestStack, 'getMasterRequest')) { - $this->requestStack->getMasterRequest()?->getSession()->set(self::MAINTENANCE_TOKEN_NAME, $token); - } + $this->requestStack->getMainRequest()?->getSession()->set(self::MAINTENANCE_TOKEN_NAME, $token); } public function get(): string { $token = $this->requestStack->getSession()->get(self::MAINTENANCE_TOKEN_NAME); - if (null === $token || !is_string($token)) { + if (!is_string($token)) { $token = ''; } diff --git a/src/SynoliaSyliusMaintenancePlugin.php b/src/SynoliaSyliusMaintenancePlugin.php index 2916e78..2ea3cae 100644 --- a/src/SynoliaSyliusMaintenancePlugin.php +++ b/src/SynoliaSyliusMaintenancePlugin.php @@ -10,4 +10,9 @@ final class SynoliaSyliusMaintenancePlugin extends Bundle { use SyliusPluginTrait; + + public function getPath(): string + { + return \dirname(__DIR__); + } } diff --git a/src/Voter/IsMaintenanceVoter.php b/src/Voter/IsMaintenanceVoter.php index 829ea85..38cac0a 100644 --- a/src/Voter/IsMaintenanceVoter.php +++ b/src/Voter/IsMaintenanceVoter.php @@ -4,22 +4,23 @@ namespace Synolia\SyliusMaintenancePlugin\Voter; +use Symfony\Component\DependencyInjection\Attribute\TaggedIterator; use Symfony\Component\HttpFoundation\Request; +use Synolia\SyliusMaintenancePlugin\Checker\IsMaintenanceCheckerInterface; use Synolia\SyliusMaintenancePlugin\Model\MaintenanceConfiguration; class IsMaintenanceVoter implements IsMaintenanceVoterInterface { - /** @var array<\Synolia\SyliusMaintenancePlugin\Checker\IsMaintenanceCheckerInterface> */ - private array $isMaintenanceCheckers; - - public function __construct(\Traversable $checkers) - { - $this->isMaintenanceCheckers = iterator_to_array($checkers); + /** @param iterable $checkers */ + public function __construct( + #[TaggedIterator(IsMaintenanceCheckerInterface::class)] + private readonly iterable $checkers, + ) { } public function isMaintenance(MaintenanceConfiguration $configuration, Request $request): bool { - foreach ($this->isMaintenanceCheckers as $checker) { + foreach ($this->checkers as $checker) { $result = $checker->isMaintenance($configuration, $request); // As soon as a voter says that the site is accessible then we deactivate the maintenance diff --git a/src/Resources/views/Admin/maintenanceConfiguration.html.twig b/templates/Admin/maintenanceConfiguration.html.twig similarity index 93% rename from src/Resources/views/Admin/maintenanceConfiguration.html.twig rename to templates/Admin/maintenanceConfiguration.html.twig index a959c0c..abb33c0 100644 --- a/src/Resources/views/Admin/maintenanceConfiguration.html.twig +++ b/templates/Admin/maintenanceConfiguration.html.twig @@ -16,10 +16,10 @@

-
+ {{ 'maintenance.ui.title'|trans }} -
{{ 'maintenance.ui.subtitle'|trans }}
-
+ {{ 'maintenance.ui.subtitle'|trans }} +

{{ breadcrumb.crumble(breadcrumbs) }}
diff --git a/src/Resources/views/maintenance.html.twig b/templates/maintenance.html.twig similarity index 98% rename from src/Resources/views/maintenance.html.twig rename to templates/maintenance.html.twig index dd27ea7..7e5bae3 100644 --- a/src/Resources/views/maintenance.html.twig +++ b/templates/maintenance.html.twig @@ -1,2 +1 @@ - {{ custom_message|default('maintenance.ui.message'|trans)|raw }} diff --git a/tests/PHPUnit/AbstractWebTestCase.php b/tests/PHPUnit/AbstractWebTestCase.php index f7ed20b..3a3030c 100644 --- a/tests/PHPUnit/AbstractWebTestCase.php +++ b/tests/PHPUnit/AbstractWebTestCase.php @@ -30,7 +30,7 @@ protected function setUp(): void $this->file = $constant->getValue(); @\unlink($this->file); - if (!self::$client) { + if (!self::$client instanceof AbstractBrowser) { self::$client = self::createClient(); } diff --git a/tests/PHPUnit/AssertTrait.php b/tests/PHPUnit/AssertTrait.php index 37e6194..43c3e2d 100644 --- a/tests/PHPUnit/AssertTrait.php +++ b/tests/PHPUnit/AssertTrait.php @@ -13,9 +13,11 @@ protected function assertSiteIsUp(): void self::assertSelectorTextContains('#footer', 'Powered by Sylius'); } - protected function assertSiteIsInMaintenance(string $message = 'The website is under maintenance'): void + protected function assertSiteIsInMaintenance(string $message = 'maintenance.ui.message'): void { + $translator = self::getContainer()->get('translator'); + self::assertResponseStatusCodeSame(503); - self::assertSelectorTextContains('body', $message); + self::assertSelectorTextContains('body', $translator->trans($message)); } } diff --git a/tests/PHPUnit/MaintenanceByChannelTest.php b/tests/PHPUnit/MaintenanceByChannelTest.php index 77ac45b..b75723d 100644 --- a/tests/PHPUnit/MaintenanceByChannelTest.php +++ b/tests/PHPUnit/MaintenanceByChannelTest.php @@ -20,7 +20,7 @@ protected function setUp(): void /** @var DefaultChannelFactory $channelFactory */ $channelFactory = self::$kernel->getContainer()->get('sylius.behat.factory.default_channel'); - // set hostname for actuel channel + // set hostname for actual channel $channel = $channelRepository->findOneByCode('FASHION_WEB'); $channel->setHostname('fashion.localhost'); diff --git a/tests/PHPUnit/MaintenanceByFileTest.php b/tests/PHPUnit/MaintenanceByFileTest.php index 332bb28..5b805b7 100644 --- a/tests/PHPUnit/MaintenanceByFileTest.php +++ b/tests/PHPUnit/MaintenanceByFileTest.php @@ -57,10 +57,10 @@ public function testMaintenanceFileWithScheduler( bool $maintenance, ): void { $scheduler = []; - if (null !== $startDate) { + if ($startDate instanceof \DateTime) { $scheduler['start_date'] = $startDate->format('Y-m-d H:i:s'); } - if (null !== $endDate) { + if ($endDate instanceof \DateTime) { $scheduler['end_date'] = $endDate->format('Y-m-d H:i:s'); } diff --git a/tests/PHPUnit/MulitChannelMaintenanceTest.php b/tests/PHPUnit/MultiChannelMaintenanceTest.php similarity index 76% rename from tests/PHPUnit/MulitChannelMaintenanceTest.php rename to tests/PHPUnit/MultiChannelMaintenanceTest.php index 6bfb6b4..f567442 100644 --- a/tests/PHPUnit/MulitChannelMaintenanceTest.php +++ b/tests/PHPUnit/MultiChannelMaintenanceTest.php @@ -9,7 +9,7 @@ use Sylius\Component\Core\Test\Services\DefaultChannelFactory; use Symfony\Component\Yaml\Yaml; -final class MulitChannelMaintenanceTest extends AbstractWebTestCase +final class MultiChannelMaintenanceTest extends AbstractWebTestCase { protected function setUp(): void { @@ -20,7 +20,7 @@ protected function setUp(): void /** @var DefaultChannelFactory $channelFactory */ $channelFactory = self::$kernel->getContainer()->get('sylius.behat.factory.default_channel'); - // set hostname for actuel channel + // set hostname for actual channel $channel = $channelRepository->findOneByCode('FASHION_WEB'); $channel->setHostname('fashion.localhost'); @@ -32,6 +32,20 @@ protected function setUp(): void $this->manager->flush(); } + protected function tearDown(): void + { + /** @var ChannelRepositoryInterface $channelRepository */ + $channelRepository = $this->manager->getRepository(ChannelInterface::class); + + // remove test channel + $maintenanceChannel = $channelRepository->findOneByCode('test'); + $this->manager->remove($maintenanceChannel); + + $this->manager->flush(); + + parent::tearDown(); + } + public function testMaintenanceIsNotEnabledWhenFileIsNotEnabled(): void { \file_put_contents( diff --git a/tests/datas/sylius_fixtures.yaml b/tests/data/sylius_fixtures.yaml similarity index 100% rename from tests/datas/sylius_fixtures.yaml rename to tests/data/sylius_fixtures.yaml diff --git a/src/Resources/translations/messages.en.yml b/translations/messages.en.yml similarity index 100% rename from src/Resources/translations/messages.en.yml rename to translations/messages.en.yml diff --git a/src/Resources/translations/messages.fr.yml b/translations/messages.fr.yml similarity index 100% rename from src/Resources/translations/messages.fr.yml rename to translations/messages.fr.yml