Commit a9a2cf8f authored by Alexander Schnitzler's avatar Alexander Schnitzler Committed by Benni Mack
Browse files

[TASK] Fix phpstan checkFunctionArgumentTypes errors in ext:install

This patch fixes incompatible type usage in function arguments
and is preparatory work for introducing native type hints and
strict mode in all core files.

Releases: master, 10.4
Resolves: #92108
Change-Id: I9aa59588a183ee3cb43091fadd6eab2491a7cbdb
Reviewed-on: https://review.typo3.org/c/Packages/TYPO3.CMS/+/65463


Tested-by: default avatarTYPO3com <noreply@typo3.com>
Tested-by: Daniel Goerz's avatarDaniel Goerz <daniel.goerz@posteo.de>
Tested-by: default avatarJörg Bösche <typo3@joergboesche.de>
Tested-by: Benni Mack's avatarBenni Mack <benni@typo3.org>
Reviewed-by: Oliver Klee's avatarOliver Klee <typo3-coding@oliverklee.de>
Reviewed-by: Daniel Goerz's avatarDaniel Goerz <daniel.goerz@posteo.de>
Reviewed-by: default avatarJörg Bösche <typo3@joergboesche.de>
Reviewed-by: Benni Mack's avatarBenni Mack <benni@typo3.org>
parent 238fb038
......@@ -73,8 +73,8 @@ class LanguagePackCommand extends Command
{
$languagePackService = GeneralUtility::makeInstance(LanguagePackService::class);
$noProgress = $input->getOption('no-progress') || $output->isVerbose();
$isos = $input->getArgument('locales');
$skipExtensions = $input->getOption('skip-extension');
$isos = (array)$input->getArgument('locales');
$skipExtensions = (array)$input->getOption('skip-extension');
if (empty($isos)) {
$isos = $languagePackService->getActiveLanguages();
}
......
......@@ -115,6 +115,7 @@ class UpgradeWizardRunCommand extends Command
$result = 0;
if ($input->getArgument('wizardName')) {
$wizardToExecute = $input->getArgument('wizardName');
$wizardToExecute = is_string($wizardToExecute) ? $wizardToExecute : '';
if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update'][$wizardToExecute])) {
$className = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update'][$wizardToExecute];
$upgradeWizard = $this->getWizard($className, $wizardToExecute);
......
......@@ -455,10 +455,10 @@ class EnvironmentController extends AbstractController
if ($imResult !== null && is_file($imResult[3])) {
if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['gif_compress']) {
clearstatcache();
$previousSize = GeneralUtility::formatSize(filesize($imResult[3]));
$previousSize = GeneralUtility::formatSize((int)filesize($imResult[3]));
$methodUsed = GraphicalFunctions::gifCompress($imResult[3], '');
clearstatcache();
$compressedSize = GeneralUtility::formatSize(filesize($imResult[3]));
$compressedSize = GeneralUtility::formatSize((int)filesize($imResult[3]));
$messages->enqueue(new FlashMessage(
'Method used by compress: ' . $methodUsed . LF
. ' Previous filesize: ' . $previousSize . '. Current filesize:' . $compressedSize,
......@@ -1088,10 +1088,10 @@ class EnvironmentController extends AbstractController
foreach ($testResult as $resultKey => $value) {
if ($resultKey === 'referenceFile') {
$fileExt = end(explode('.', $testResult['referenceFile']));
$responseData['referenceFile'] = 'data:image/' . $fileExt . ';base64,' . base64_encode(file_get_contents($testResult['referenceFile']));
$responseData['referenceFile'] = 'data:image/' . $fileExt . ';base64,' . base64_encode((string)file_get_contents($testResult['referenceFile']));
} elseif ($resultKey === 'outputFile') {
$fileExt = end(explode('.', $testResult['outputFile']));
$responseData['outputFile'] = 'data:image/' . $fileExt . ';base64,' . base64_encode(file_get_contents($testResult['outputFile']));
$responseData['outputFile'] = 'data:image/' . $fileExt . ';base64,' . base64_encode((string)file_get_contents($testResult['outputFile']));
} else {
$responseData[$resultKey] = $value;
}
......
......@@ -638,11 +638,12 @@ class UpgradeController extends AbstractController
}
// Build array of file (hashes) not affected by current scan, if they are tagged as "FullyScanned"
$parsedRestFile = array_pop($documentationFile->getListEntry(str_replace(
$listEntries = $documentationFile->getListEntry(str_replace(
'\\',
'/',
realpath($restFile->getPathname())
)));
(string)realpath($restFile->getPathname())
));
$parsedRestFile = array_pop($listEntries);
if (!in_array($parsedRestFile['file_hash'], $foundRestFileHashes, true)
&& in_array('FullyScanned', $parsedRestFile['tags'], true)
) {
......@@ -759,11 +760,12 @@ class UpgradeController extends AbstractController
$restFileLocation = $restFile->getPathname();
break;
}
$parsedRestFile = array_pop($documentationFile->getListEntry(str_replace(
$listEntries = $documentationFile->getListEntry(str_replace(
'\\',
'/',
realpath($restFileLocation)
)));
(string)realpath($restFileLocation)
));
$parsedRestFile = array_pop($listEntries);
$version = GeneralUtility::trimExplode(DIRECTORY_SEPARATOR, $restFileLocation);
array_pop($version);
// something like "8.2" .. "8.7" .. "master"
......@@ -1235,7 +1237,7 @@ class UpgradeController extends AbstractController
{
$documentationFileService = new DocumentationFile();
$documentationDirectories = $documentationFileService->findDocumentationDirectories(
str_replace('\\', '/', realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog'))
str_replace('\\', '/', (string)realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog'))
);
return array_reverse($documentationDirectories);
}
......@@ -1250,7 +1252,7 @@ class UpgradeController extends AbstractController
{
$documentationFileService = new DocumentationFile();
$documentationFiles = $documentationFileService->findDocumentationFiles(
str_replace('\\', '/', realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog/' . $version))
str_replace('\\', '/', (string)realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog/' . $version))
);
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_registry');
......
......@@ -187,7 +187,7 @@ abstract class AbstractNode
*/
protected function getCurrentPermission()
{
$permissions = decoct(fileperms($this->getAbsolutePath()));
$permissions = decoct((int)fileperms($this->getAbsolutePath()));
return substr($permissions, -4);
}
......
......@@ -257,7 +257,7 @@ class FileNode extends AbstractNode implements NodeInterface
$result = true;
} else {
$targetContentHash = md5($this->targetContent);
$currentContentHash = md5(file_get_contents($absolutePath));
$currentContentHash = md5((string)file_get_contents($absolutePath));
if ($targetContentHash === $currentContentHash) {
$result = true;
}
......
......@@ -455,7 +455,7 @@ class CoreUpdateService
FlashMessage::ERROR
));
} else {
$isCurrentCoreSymlinkAbsolute = PathUtility::isAbsolutePath(readlink($this->symlinkToCoreFiles));
$isCurrentCoreSymlinkAbsolute = PathUtility::isAbsolutePath((string)readlink($this->symlinkToCoreFiles));
$unlinkResult = unlink($this->symlinkToCoreFiles);
if (!$unlinkResult) {
$success = false;
......
......@@ -132,7 +132,7 @@ class EnableFileService
public static function isInstallToolEnableFilePermanent()
{
if (self::installToolEnableFileExists()) {
$content = @file_get_contents(self::getInstallToolEnableFilePath());
$content = (string)@file_get_contents(self::getInstallToolEnableFilePath());
if (strpos($content, 'KEEP_FILE') !== false) {
return true;
}
......@@ -188,7 +188,9 @@ class EnableFileService
*/
protected static function getFirstInstallFilePaths()
{
$files = array_filter(scandir(Environment::getPublicPath() . '/'), function ($file) {
$files = scandir(Environment::getPublicPath() . '/');
$files = is_array($files) ? $files : [];
$files = array_filter($files, function ($file) {
return @is_file(Environment::getPublicPath() . '/' . $file) && preg_match('~^' . self::FIRST_INSTALL_FILE_PATH . '.*~i', $file);
});
return $files;
......
......@@ -120,9 +120,9 @@ class FileSessionHandler implements \SessionHandlerInterface
if ($fd = fopen($sessionFile, 'rb')) {
$lockres = flock($fd, LOCK_SH);
if ($lockres) {
$length = filesize($sessionFile);
$length = (int)filesize($sessionFile);
if ($length > 0) {
$content = fread($fd, $length);
$content = (string)fread($fd, $length);
}
flock($fd, LOCK_UN);
}
......
......@@ -71,7 +71,7 @@ class SessionService implements SingletonInterface
);
session_set_save_handler($sessionHandler);
session_name($this->cookieName);
ini_set('session.cookie_httponly', true);
ini_set('session.cookie_httponly', 'On');
if ($this->hasSameSiteCookieSupport()) {
ini_set('session.cookie_samesite', Cookie::SAMESITE_STRICT);
}
......@@ -79,7 +79,7 @@ class SessionService implements SingletonInterface
// Always call the garbage collector to clean up stale session files
ini_set('session.gc_probability', (string)100);
ini_set('session.gc_divisor', (string)100);
ini_set('session.gc_maxlifetime', (string)$this->expireTimeInMinutes * 2 * 60);
ini_set('session.gc_maxlifetime', (string)($this->expireTimeInMinutes * 2 * 60));
if ($this->isSessionAutoStartEnabled()) {
$sessionCreationError = 'Error: session.auto-start is enabled.<br />';
$sessionCreationError .= 'The PHP option session.auto-start is enabled. Disable this option in php.ini or .htaccess:<br />';
......
......@@ -48,7 +48,11 @@ class UpgradeWizardsService
public function __construct()
{
$this->output = new StreamOutput(fopen('php://temp', 'wb'), Output::VERBOSITY_NORMAL, false);
$fileName = 'php://temp';
if (($stream = fopen($fileName, 'wb')) === false) {
throw new \RuntimeException('Unable to open stream "' . $fileName . '"', 1598341765);
}
$this->output = new StreamOutput($stream, Output::VERBOSITY_NORMAL, false);
}
/**
......@@ -259,6 +263,7 @@ class UpgradeWizardsService
{
$wizards = [];
foreach (array_keys($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update']) as $identifier) {
$identifier = (string)$identifier;
if ($this->isWizardDone($identifier)) {
continue;
}
......@@ -317,7 +322,7 @@ class UpgradeWizardsService
$radioAttributes = [
'type' => 'radio',
'name' => 'install[values][' . $updateObject->getIdentifier() . '][install]',
'value' => 0
'value' => '0'
];
$markup[] = '<div class="panel panel-danger">';
$markup[] = ' <div class="panel-heading">';
......@@ -329,7 +334,7 @@ class UpgradeWizardsService
if (!$updateObject->getConfirmation()->isRequired()) {
$markup[] = ' <label class="btn btn-default active"><input ' . GeneralUtility::implodeAttributes($radioAttributes, true) . ' checked="checked" />' . $updateObject->getConfirmation()->getDeny() . '</label>';
}
$radioAttributes['value'] = 1;
$radioAttributes['value'] = '1';
$markup[] = ' <label class="btn btn-default"><input ' . GeneralUtility::implodeAttributes($radioAttributes, true) . ' />' . $updateObject->getConfirmation()->getConfirm() . '</label>';
$markup[] = ' </div>';
$markup[] = ' </div>';
......@@ -402,14 +407,14 @@ class UpgradeWizardsService
}
$messages->enqueue(
new FlashMessage(
stream_get_contents($stream),
(string)stream_get_contents($stream),
'Update successful'
)
);
} else {
$messages->enqueue(
new FlashMessage(
stream_get_contents($stream),
(string)stream_get_contents($stream),
'Update failed!',
FlashMessage::ERROR
)
......
......@@ -140,7 +140,7 @@ class Check implements CheckInterface
*/
protected function checkCurrentDirectoryIsInIncludePath()
{
$includePath = ini_get('include_path');
$includePath = (string)ini_get('include_path');
$delimiter = $this->isWindowsOs() ? ';' : ':';
$pathArray = $this->trimExplode($delimiter, $includePath);
if (!in_array('.', $pathArray)) {
......@@ -190,8 +190,8 @@ class Check implements CheckInterface
*/
protected function checkPostUploadSizeIsHigherOrEqualMaximumFileUploadSize()
{
$maximumUploadFilesize = $this->getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
$maximumPostSize = $this->getBytesFromSizeMeasurement(ini_get('post_max_size'));
$maximumUploadFilesize = $this->getBytesFromSizeMeasurement((string)ini_get('upload_max_filesize'));
$maximumPostSize = $this->getBytesFromSizeMeasurement((string)ini_get('post_max_size'));
if ($maximumPostSize > 0 && $maximumPostSize < $maximumUploadFilesize) {
$this->messageQueue->enqueue(new FlashMessage(
'upload_max_filesize=' . ini_get('upload_max_filesize') . LF
......@@ -222,7 +222,7 @@ class Check implements CheckInterface
{
$minimumMemoryLimit = 64;
$recommendedMemoryLimit = 128;
$memoryLimit = $this->getBytesFromSizeMeasurement(ini_get('memory_limit'));
$memoryLimit = $this->getBytesFromSizeMeasurement((string)ini_get('memory_limit'));
if ($memoryLimit <= 0) {
$this->messageQueue->enqueue(new FlashMessage(
'PHP is configured not to limit memory usage at all. This is a risk'
......@@ -371,7 +371,7 @@ class Check implements CheckInterface
*/
protected function checkDisableFunctions()
{
$disabledFunctions = trim(ini_get('disable_functions'));
$disabledFunctions = trim((string)ini_get('disable_functions'));
// Filter "disable_functions"
$disabledFunctionsArray = $this->trimExplode(',', $disabledFunctions);
......@@ -422,7 +422,7 @@ class Check implements CheckInterface
*/
protected function checkDocRoot()
{
$docRootSetting = trim(ini_get('doc_root'));
$docRootSetting = trim((string)ini_get('doc_root'));
if ($docRootSetting !== '') {
$this->messageQueue->enqueue(new FlashMessage(
'doc_root=' . $docRootSetting . LF
......@@ -447,7 +447,7 @@ class Check implements CheckInterface
*/
protected function checkOpenBaseDir()
{
$openBaseDirSetting = trim(ini_get('open_basedir'));
$openBaseDirSetting = trim((string)ini_get('open_basedir'));
if ($openBaseDirSetting !== '') {
$this->messageQueue->enqueue(new FlashMessage(
'open_basedir = ' . ini_get('open_basedir') . LF
......@@ -818,6 +818,7 @@ class Check implements CheckInterface
protected function trimExplode($delimiter, $string)
{
$explodedValues = explode($delimiter, $string);
$explodedValues = is_array($explodedValues) ? $explodedValues : [];
$resultWithPossibleEmptyValues = array_map('trim', $explodedValues);
$result = [];
foreach ($resultWithPossibleEmptyValues as $value) {
......
......@@ -230,7 +230,7 @@ class ServerResponseCheck implements CheckInterface
$messageParts[] = sprintf(
'unexpected content-type %s',
$this->wrapValue(
$fileDeclaration->getUnexpectedContentType(),
(string)$fileDeclaration->getUnexpectedContentType(),
'<code>',
'</code>'
)
......@@ -240,7 +240,7 @@ class ServerResponseCheck implements CheckInterface
$messageParts[] = sprintf(
'content-type mismatch %s, got %s',
$this->wrapValue(
$fileDeclaration->getExpectedContent(),
(string)$fileDeclaration->getExpectedContent(),
'<code>',
'</code>'
),
......@@ -255,7 +255,7 @@ class ServerResponseCheck implements CheckInterface
$messageParts[] = sprintf(
'unexpected content %s',
$this->wrapValue(
$fileDeclaration->getUnexpectedContent(),
(string)$fileDeclaration->getUnexpectedContent(),
'<code>',
'</code>'
)
......@@ -265,7 +265,7 @@ class ServerResponseCheck implements CheckInterface
$messageParts[] = sprintf(
'content mismatch %s',
$this->wrapValue(
$fileDeclaration->getExpectedContent(),
(string)$fileDeclaration->getExpectedContent(),
'<code>',
'</code>'
)
......
......@@ -120,7 +120,7 @@ class SetupCheck implements CheckInterface
*/
protected function checkSystemLocale()
{
$currentLocale = setlocale(LC_CTYPE, 0);
$currentLocale = (string)setlocale(LC_CTYPE, '0');
// On Windows an empty locale value uses the regional settings from the Control Panel
if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale'] === '' && !Environment::isWindows()) {
......@@ -162,7 +162,7 @@ class SetupCheck implements CheckInterface
));
} else {
$testString = 'ÖöĄĆŻĘĆćążąęó.jpg';
$currentLocale = setlocale(LC_CTYPE, 0);
$currentLocale = (string)setlocale(LC_CTYPE, '0');
$quote = Environment::isWindows() ? '"' : '\'';
setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
if (escapeshellarg($testString) === $quote . $testString . $quote) {
......
......@@ -152,6 +152,7 @@ class DatabaseRowsUpdateWizard implements UpgradeWizardInterface, RepeatableInte
// Scope of the row updater is to update all rows that have TCA,
// our list of tables is just the list of loaded TCA tables.
/** @var string[] $listOfAllTables */
$listOfAllTables = array_keys($GLOBALS['TCA']);
// In case the PHP ended for whatever reason, fetch the last position from registry
......
......@@ -60,7 +60,7 @@ class DocumentationFile
if ($this->registry === null) {
$this->registry = new Registry();
}
$this->changelogPath = $changelogDir !== '' ? $changelogDir : realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog');
$this->changelogPath = $changelogDir !== '' ? $changelogDir : (string)realpath(ExtensionManagementUtility::extPath('core') . 'Documentation/Changelog');
$this->changelogPath = str_replace('\\', '/', $this->changelogPath);
}
......@@ -129,6 +129,7 @@ class DocumentationFile
throw new \InvalidArgumentException('the given file does not belong to the changelog dir. Aborting', 1485425531);
}
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = is_array($lines) ? $lines : [];
$headline = $this->extractHeadline($lines);
$entry['version'] = PathUtility::basename(PathUtility::dirname($file));
$entry['headline'] = $headline;
......@@ -144,7 +145,7 @@ class DocumentationFile
}
}
$entry['tagList'] = implode(',', $entry['tags']);
$entry['content'] = file_get_contents($file);
$entry['content'] = (string)file_get_contents($file);
$entry['parsedContent'] = $this->parseContent($entry['content']);
$entry['file_hash'] = md5($entry['content']);
if ($entry['version'] !== '') {
......@@ -338,11 +339,11 @@ class DocumentationFile
protected function parseContent(string $rstContent): string
{
$content = htmlspecialchars($rstContent);
$content = preg_replace('/:issue:`([\d]*)`/', '<a href="https://forge.typo3.org/issues/\\1" target="_blank" rel="noreferrer">\\1</a>', $content);
$content = preg_replace('/#([\d]*)/', '#<a href="https://forge.typo3.org/issues/\\1" target="_blank" rel="noreferrer">\\1</a>', $content);
$content = preg_replace('/(\n([=]*)\n(.*)\n([=]*)\n)/', '', $content, 1);
$content = preg_replace('/.. index::(.*)/', '', $content);
$content = preg_replace('/.. include::(.*)/', '', $content);
$content = (string)preg_replace('/:issue:`([\d]*)`/', '<a href="https://forge.typo3.org/issues/\\1" target="_blank" rel="noreferrer">\\1</a>', $content);
$content = (string)preg_replace('/#([\d]*)/', '#<a href="https://forge.typo3.org/issues/\\1" target="_blank" rel="noreferrer">\\1</a>', $content);
$content = (string)preg_replace('/(\n([=]*)\n(.*)\n([=]*)\n)/', '', $content, 1);
$content = (string)preg_replace('/.. index::(.*)/', '', $content);
$content = (string)preg_replace('/.. include::(.*)/', '', $content);
return trim($content);
}
......
......@@ -75,8 +75,8 @@ class PhpInfoViewHelper extends AbstractViewHelper
protected static function removeAllHtmlOutsideBody($html)
{
// Delete anything outside of the body tag and the body tag itself
$html = preg_replace('/^.*?<body.*?>/is', '', $html);
$html = preg_replace('/<\/body>.*?$/is', '', $html);
$html = (string)preg_replace('/^.*?<body.*?>/is', '', $html);
$html = (string)preg_replace('/<\/body>.*?$/is', '', $html);
return $html;
}
......@@ -90,7 +90,7 @@ class PhpInfoViewHelper extends AbstractViewHelper
protected static function changeHtmlToHtml5($html)
{
// Delete obsolete attributes
$html = preg_replace('#\s(cellpadding|border|width)="[^"]+"#', '', $html);
$html = (string)preg_replace('#\s(cellpadding|border|width)="[^"]+"#', '', $html);
// Replace font tag with span
return str_replace(['<font', '</font>'], ['<span', '</span>'], $html);
......
......@@ -43,7 +43,7 @@ class ActionViewHelper extends AbstractViewHelper
*/
public function initializeArguments()
{
$this->registerArgument('action', 'string', 'Target action', '');
$this->registerArgument('action', 'string', 'Target action', false);
$this->registerArgument('controller', 'string', 'Target controller.', false, 'maintenance');
$this->registerArgument('arguments', 'array', 'Arguments', false, []);
$this->registerArgument('section', 'string', 'The anchor to be added to the URI', false, '');
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment