Skip to content

Commit

Permalink
[TASK] Add rector/rector
Browse files Browse the repository at this point in the history
Additionally add an automated check in cgl stage
  • Loading branch information
christianfutterlieb committed May 3, 2024
1 parent 43731b9 commit 0532e50
Show file tree
Hide file tree
Showing 21 changed files with 139 additions and 118 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ jobs:
run: Build/Scripts/builder.sh -p ${{ matrix.php }} -n test:qa:cgl
- name: PHPStan
run: Build/Scripts/builder.sh -p ${{ matrix.php }} test:qa:phpstan
# - name: Rector
# run: Build/Scripts/builder.sh -p ${{ matrix.php }} test:qa:rector
- name: Rector
run: Build/Scripts/builder.sh -p ${{ matrix.php }} -n test:qa:rector
testsuite:
runs-on: ubuntu-latest
strategy:
Expand Down
28 changes: 14 additions & 14 deletions Build/Scripts/builder.sh
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ createCommandList() {
test:qa:cgl Run php-cs-fixer. Use -n to run only the check without changing the code
test:qa:phpstan Run phpstan (static code analysis)
test:qa:phpstan:baseline Generate phpstan baseline (not available in CI environment)
# test:qa:rector Run rector. Use -n to run only the check without changing the code
test:qa:rector Run rector. Use -n to run only the check without changing the code
test:unit Run unit tests
"
}
Expand Down Expand Up @@ -385,19 +385,19 @@ case ${command} in
usedDockerImage=${dockerImagePhp}
fi
;;
# test:qa:rector)
# rectorArguments="process --config Build/rector/rector.php"
# if [ $isCiEnvironment -eq 1 ]; then
# rectorArguments="${rectorArguments} --no-progress-bar"
# fi
# if [ ${isDryRun} -eq 1 ]; then
# rectorArguments="${rectorArguments} --dry-run"
# fi
#
# docker run ${dockerArguments} ${dockerImagePhp} php ${rootDir}/${composerBinDir}/rector ${rectorArguments}
# commandExitCode=$?
# usedDockerImage=${dockerImagePhp}
# ;;
test:qa:rector)
rectorArguments="process --config Build/rector/rector.php"
if [ $isCiEnvironment -eq 1 ]; then
rectorArguments="${rectorArguments} --no-progress-bar"
fi
if [ ${isDryRun} -eq 1 ]; then
rectorArguments="${rectorArguments} --dry-run"
fi

docker run ${dockerArguments} ${dockerImagePhp} php ${rootDir}/${composerBinDir}/rector ${rectorArguments} ${@}
commandExitCode=$?
usedDockerImage=${dockerImagePhp}
;;
test:unit)
dockerArguments="${dockerArguments} -e TYPO3_PATH_ROOT=${rootDir}/.Build/public"
phpunitArguments="-c Build/phpunit/UnitTests.xml"
Expand Down
7 changes: 5 additions & 2 deletions Build/php-cs-fixer/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

declare(strict_types=1);

use PhpCsFixer\Config;
use PhpCsFixer\Finder;

/*
* This file is initially copied from TYPO3 core's php-cs-fixer config.php
* branch 12.4
Expand Down Expand Up @@ -34,9 +37,9 @@
// - Remove unused use statements in the PHP source code
// - Ensure Concatenation to have at least one whitespace around
// - Remove trailing whitespace at the end of blank lines.
return (new \PhpCsFixer\Config())
return (new Config())
->setFinder(
(new PhpCsFixer\Finder())
(new Finder())
->ignoreVCSIgnored(true)
->in([
__DIR__ . '/../..',
Expand Down
53 changes: 33 additions & 20 deletions Build/phpunit/UnitTestsBootstrap.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
<?php

use TYPO3\CMS\Core\Cache\Backend\NullBackend;
use TYPO3\CMS\Core\Cache\Frontend\PhpFrontend;
use TYPO3\CMS\Core\Configuration\ConfigurationManager;
use TYPO3\CMS\Core\Core\Bootstrap;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Core\SystemEnvironmentBuilder;
use TYPO3\CMS\Core\Package\PackageManager;
use TYPO3\CMS\Core\Package\UnitTestPackageManager;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\TestingFramework\Core\Testbase;

/*
* This file is initially copied from typo3/testing-framework
*
Expand All @@ -19,8 +32,8 @@
* according script within TYPO3 core's Build/Scripts directory and
* adapt to extensions needs.
*/
(static function () {
$testbase = new \TYPO3\TestingFramework\Core\Testbase();
(static function (): void {
$testbase = new Testbase();

// These if's are for core testing (package typo3/cms) only. cms-composer-installer does
// not create the autoload-include.php file that sets these env vars and sets composer
Expand All @@ -29,48 +42,48 @@
// is called to run the tests since the 'relative to entry script' path calculation within
// SystemEnvironmentBuilder is not used. However, the binary must be called from the document
// root since getWebRoot() uses 'getcwd()'.
if (!getenv('TYPO3_PATH_ROOT')) {
if (getenv('TYPO3_PATH_ROOT') === '' || getenv('TYPO3_PATH_ROOT') === '0' || getenv('TYPO3_PATH_ROOT') === [] || getenv('TYPO3_PATH_ROOT') === false) {
putenv('TYPO3_PATH_ROOT=' . rtrim($testbase->getWebRoot(), '/'));
}
if (!getenv('TYPO3_PATH_WEB')) {
if (getenv('TYPO3_PATH_WEB') === '' || getenv('TYPO3_PATH_WEB') === '0' || getenv('TYPO3_PATH_WEB') === [] || getenv('TYPO3_PATH_WEB') === false) {
putenv('TYPO3_PATH_WEB=' . rtrim($testbase->getWebRoot(), '/'));
}

$testbase->defineSitePath();

// We can use the "typo3/cms-composer-installers" constant "TYPO3_COMPOSER_MODE" to determine composer mode.
// This should be always true except for TYPO3 mono repository.
$composerMode = defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE === true;
$requestType = \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_BE | \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_CLI;
$composerMode = defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE;
$requestType = SystemEnvironmentBuilder::REQUESTTYPE_BE | SystemEnvironmentBuilder::REQUESTTYPE_CLI;
\TYPO3\TestingFramework\Core\SystemEnvironmentBuilder::run(0, $requestType, $composerMode);

$testbase->createDirectory(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/typo3conf/ext');
$testbase->createDirectory(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/typo3temp/assets');
$testbase->createDirectory(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/typo3temp/var/tests');
$testbase->createDirectory(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/typo3temp/var/transient');
$testbase->createDirectory(Environment::getPublicPath() . '/typo3conf/ext');
$testbase->createDirectory(Environment::getPublicPath() . '/typo3temp/assets');
$testbase->createDirectory(Environment::getPublicPath() . '/typo3temp/var/tests');
$testbase->createDirectory(Environment::getPublicPath() . '/typo3temp/var/transient');

// Retrieve an instance of class loader and inject to core bootstrap
$classLoader = require $testbase->getPackagesPath() . '/autoload.php';
\TYPO3\CMS\Core\Core\Bootstrap::initializeClassLoader($classLoader);
Bootstrap::initializeClassLoader($classLoader);

// Initialize default TYPO3_CONF_VARS
$configurationManager = new \TYPO3\CMS\Core\Configuration\ConfigurationManager();
$configurationManager = new ConfigurationManager();
$GLOBALS['TYPO3_CONF_VARS'] = $configurationManager->getDefaultConfiguration();
$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] = 'encryption-key-for-phpunit-' . bin2hex(random_bytes(8));

$cache = new \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend(
$cache = new PhpFrontend(
'core',
new \TYPO3\CMS\Core\Cache\Backend\NullBackend('production', [])
new NullBackend('production', [])
);
$packageManager = \TYPO3\CMS\Core\Core\Bootstrap::createPackageManager(
\TYPO3\CMS\Core\Package\UnitTestPackageManager::class,
\TYPO3\CMS\Core\Core\Bootstrap::createPackageCache($cache)
$packageManager = Bootstrap::createPackageManager(
UnitTestPackageManager::class,
Bootstrap::createPackageCache($cache)
);

\TYPO3\CMS\Core\Utility\GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Package\PackageManager::class, $packageManager);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::setPackageManager($packageManager);
GeneralUtility::setSingletonInstance(PackageManager::class, $packageManager);
ExtensionManagementUtility::setPackageManager($packageManager);

$testbase->dumpClassLoadingInformation();

\TYPO3\CMS\Core\Utility\GeneralUtility::purgeInstances();
GeneralUtility::purgeInstances();
})();
34 changes: 34 additions & 0 deletions Build/rector/rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

use Rector\Caching\ValueObject\Storage\FileCacheStorage;
use Rector\Config\RectorConfig;
use Rector\ValueObject\PhpVersion;

return RectorConfig::configure()
->withImportNames(
importShortClasses: false,
)
->withPhpVersion(PhpVersion::PHP_81)
->withCache(
'.Build/.cache/rector',
FileCacheStorage::class
)
->withPaths([
__DIR__ . '/../..',
])
->withSkip([
__DIR__ . '/../../.Build',
])
->withPhpSets(
php83: true,
)
->withPreparedSets(
codeQuality: true,
deadCode: true,
earlyReturn: true,
instanceOf: true,
strictBooleans: true,
typeDeclarations: true,
);
3 changes: 2 additions & 1 deletion Classes/Command/SynchronizeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TYPO3\CMS\Core\Locking\Exception\LockCreateException;
use TYPO3\CMS\Core\Locking\LockingStrategyInterface;

/**
Expand Down Expand Up @@ -50,7 +51,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
// Acquire lock
try {
$this->locker->acquire();
} catch (\TYPO3\CMS\Core\Locking\Exception\LockCreateException $e) {
} catch (LockCreateException $e) {
$output->writeln('Error: cannot create lock: ' . $e->getMessage());
return Command::FAILURE;
} catch (\Exception $e) {
Expand Down
6 changes: 0 additions & 6 deletions Classes/Controller/ManagementController.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,6 @@ protected function synchronizeAllBackendUserGroupRolesAction(): ResponseInterfac
return $this->redirect('index');
}

/**
* @param int $backendUserGroupUid
*/
protected function resetBackendUserGroupToDefaultsAction(int $backendUserGroupUid): ResponseInterface
{
$affectedRows = $this->synchronizer->resetManagedFieldsToDefaults($backendUserGroupUid);
Expand All @@ -143,9 +140,6 @@ protected function resetBackendUserGroupToDefaultsAction(int $backendUserGroupUi
return $this->redirect('index');
}

/**
* @param int $backendUserGroupUid
*/
protected function exportAsRoleAction(int $backendUserGroupUid): ResponseInterface
{
try {
Expand Down
2 changes: 1 addition & 1 deletion Classes/FormEngine/BackendRoleSelectItemsProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public function process(array &$params): void
}

// Add items (if there are any)
if (!empty($selectItems)) {
if ($selectItems !== []) {
// Create the empty item
if (!is_array($params['items'] ?? null)) {
$params['items'] = [
Expand Down
8 changes: 3 additions & 5 deletions Classes/Role/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,7 @@ public function toArray(): array
'non_exclude_fields' => $this->nonExcludeFields,
];

return array_filter($array, function ($value) {
return $value !== null;
});
return array_filter($array, fn($value): bool => $value !== null);
}

public function getIdentifier(): string
Expand Down Expand Up @@ -212,15 +210,15 @@ public function getFilePermissions(): ?array
}

/**
* @return ?mixed[]
* @phpstan-return ?mixed[]
*/
public function getExplicitAllowdeny(): ?array
{
return $this->explicitAllowdeny;
}

/**
* @return ?mixed[]
* @phpstan-return ?mixed[]
*/
public function getNonExcludeFields(): ?array
{
Expand Down
25 changes: 6 additions & 19 deletions Classes/Role/Definition/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

use AawTeam\BackendRoles\Role\Definition;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
* Formatter
Expand Down Expand Up @@ -57,14 +57,11 @@ public function getManagedColumnsWithDefaultValues(): array
return $return;
}

/**
* @param Definition $definition
*/
public function formatTitle(Definition $definition): string
{
$return = trim($definition->getTitle() ?? '');
if ($return === '') {
$return = $definition->getIdentifier();
return $definition->getIdentifier();
}
return $return;
}
Expand Down Expand Up @@ -177,17 +174,12 @@ public function formatFromDbToArray(array $backendUserGroup): array

// Strings
if (is_string($dataToProcess['TSconfig'] ?? null)) {
$return['TSconfig'] = trim((string)$dataToProcess['TSconfig']);
$return['TSconfig'] = trim($dataToProcess['TSconfig']);
}

// Comma-separated to array
if (is_string($dataToProcess['pagetypes_select'] ?? null)) {
$return['pagetypes_select'] = array_filter(explode(',', $dataToProcess['pagetypes_select']), function ($value) {
return MathUtility::canBeInterpretedAsInteger($value);
});
array_walk($return['pagetypes_select'], function (&$v) {
$v = (int)$v;
});
$return['pagetypes_select'] = GeneralUtility::intExplode(',', $dataToProcess['pagetypes_select'], true);
}
if (is_string($dataToProcess['tables_select'] ?? null)) {
$return['tables_select'] = array_filter(explode(',', $dataToProcess['tables_select']));
Expand All @@ -202,12 +194,7 @@ public function formatFromDbToArray(array $backendUserGroup): array
$return['file_permissions'] = array_filter(explode(',', $dataToProcess['file_permissions']));
}
if (is_string($dataToProcess['allowed_languages'] ?? null)) {
$return['allowed_languages'] = array_filter(explode(',', $dataToProcess['allowed_languages']), function ($value) {
return MathUtility::canBeInterpretedAsInteger($value);
});
array_walk($return['allowed_languages'], function (&$v) {
$v = (int)$v;
});
$return['allowed_languages'] = GeneralUtility::intExplode(',', $dataToProcess['allowed_languages'], true);
}

// Comma-separated to multi-array
Expand All @@ -219,7 +206,7 @@ public function formatFromDbToArray(array $backendUserGroup): array
continue;
}
if (str_contains($entry, ';')) {
list($path, $ffPath) = explode(';', $entry, 2);
[$path, $ffPath] = explode(';', $entry, 2);
$parts = explode(';', $ffPath);
$value = array_pop($parts);
array_unshift($parts, $path);
Expand Down
16 changes: 5 additions & 11 deletions Classes/Role/Definition/Loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,15 @@ public function getRoleDefinitions(): DefinitionCollection
$cacheIdentifier = $this->getRoleDefinitionCacheIdentifier();
if ($this->cache->has($cacheIdentifier)) {
$roleDefinitions = new DefinitionCollection();
array_map(function (array $definitionArray) use (&$roleDefinitions) {
array_map(function (array $definitionArray) use (&$roleDefinitions): void {
$roleDefinitions->add(
$this->definitionFactory->create($definitionArray)
);
}, $this->cache->require($cacheIdentifier));
} else {
$roleDefinitions = $this->loadRoleDefinitions();
$roleDefinitionsArray = array_map(
function (Definition $definition): array {
return $definition->toArray();
},
fn(Definition $definition): array => $definition->toArray(),
$roleDefinitions->toArray()
);
$this->cache->set($cacheIdentifier, 'return ' . var_export($roleDefinitionsArray, true) . ';');
Expand All @@ -67,12 +65,8 @@ protected function loadRoleDefinitions(): DefinitionCollection

// Define config loader functions
// @todo: move functions to service classes
$yamlConfigLoader = function (string $fileName): mixed {
return $this->yamlFileLoader->load($fileName, YamlFileLoader::PROCESS_IMPORTS)['RoleDefinitions'] ?? null;
};
$phpConfigLoader = function (string $fileName): mixed {
return require $fileName;
};
$yamlConfigLoader = fn(string $fileName): mixed => $this->yamlFileLoader->load($fileName, YamlFileLoader::PROCESS_IMPORTS)['RoleDefinitions'] ?? null;
$phpConfigLoader = fn(string $fileName): mixed => require $fileName;

// Load from global configuration
$globalConfigurationPath = rtrim(Environment::getConfigPath(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
Expand Down Expand Up @@ -153,7 +147,7 @@ private function getRoleDefinitionCacheIdentifier(): string
Environment::getProjectPath(),
serialize($this->extensionInformationProvider->getLoadedExtensionListArray()),
]),
$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
(string)$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
);
}
}
Loading

0 comments on commit 0532e50

Please sign in to comment.