Commit db61a944 authored by Daniel Goerz's avatar Daniel Goerz Committed by Benni Mack
Browse files

[TASK] Fix phpstan checkFunctionArgumentTypes errors in ext:backend Controller

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: #92578
Change-Id: I4532bbbd9ed907fe364f56caf6f330feda7c32bc
Reviewed-on: https://review.typo3.org/c/Packages/TYPO3.CMS/+/66157

Tested-by: Daniel Goerz's avatarDaniel Goerz <daniel.goerz@posteo.de>
Tested-by: default avatarTYPO3com <noreply@typo3.com>
Tested-by: Benni Mack's avatarBenni Mack <benni@typo3.org>
Reviewed-by: Daniel Goerz's avatarDaniel Goerz <daniel.goerz@posteo.de>
Reviewed-by: Oliver Klee's avatarOliver Klee <typo3-coding@oliverklee.de>
Reviewed-by: Benni Mack's avatarBenni Mack <benni@typo3.org>
parent e400229a
......@@ -81,7 +81,7 @@ abstract class AbstractFormEngineAjaxController
{
if (strpos($stylesheetFile, 'EXT:') === 0) {
$stylesheetFile = GeneralUtility::getFileAbsFileName($stylesheetFile);
$stylesheetFile = PathUtility::getRelativePathTo($stylesheetFile);
$stylesheetFile = PathUtility::getRelativePathTo($stylesheetFile) ?? '';
$stylesheetFile = rtrim($stylesheetFile, '/');
} else {
$stylesheetFile = GeneralUtility::resolveBackPath($stylesheetFile);
......
......@@ -304,7 +304,7 @@ class BackendController
// Add further attributes
foreach ($additionalAttributes as $name => $value) {
$liAttributes[$name] = $value;
$liAttributes[(string)$name] = (string)$value;
}
// Create a unique id from class name
......@@ -315,7 +315,7 @@ class BackendController
$liAttributes['id'] = $className;
// Create data attribute identifier
$shortName = substr($fullyQualifiedClassName, strrpos($fullyQualifiedClassName, '\\') + 1);
$shortName = substr($fullyQualifiedClassName, (int)strrpos($fullyQualifiedClassName, '\\') + 1);
$dataToolbarIdentifier = GeneralUtility::camelCaseToLowerCaseUnderscored($shortName);
$dataToolbarIdentifier = str_replace('_', '-', $dataToolbarIdentifier);
$liAttributes['data-toolbar-identifier'] = $dataToolbarIdentifier;
......@@ -402,13 +402,13 @@ class BackendController
$beUser = $this->getBackendUser();
$userTsConfig = $this->getBackendUser()->getTSConfig();
// EDIT page
$editId = preg_replace('/[^[:alnum:]_]/', '', $request->getQueryParams()['edit'] ?? '');
$editId = preg_replace('/[^[:alnum:]_]/', '', $request->getQueryParams()['edit'] ?? '') ?? '';
if ($editId) {
// Looking up the page to edit, checking permissions:
$where = ' AND (' . $beUser->getPagePermsClause(Permission::PAGE_EDIT) . ' OR ' . $beUser->getPagePermsClause(Permission::CONTENT_EDIT) . ')';
$editRecord = null;
if (MathUtility::canBeInterpretedAsInteger($editId)) {
$editRecord = BackendUtility::getRecordWSOL('pages', $editId, '*', $where);
$editRecord = BackendUtility::getRecordWSOL('pages', (int)$editId, '*', $where);
}
// If the page was accessible, then let the user edit it.
if (is_array($editRecord) && $beUser->isInWebMount($editRecord)) {
......@@ -427,7 +427,7 @@ class BackendController
return '
// Warning about page editing:
require(["TYPO3/CMS/Backend/Modal", "TYPO3/CMS/Backend/Severity"], function(Modal, Severity) {
Modal.show("", ' . GeneralUtility::quoteJSvalue(sprintf($this->getLanguageService()->getLL('noEditPage'), $editId)) . ', Severity.notice, [{
Modal.show("", ' . GeneralUtility::quoteJSvalue(sprintf($this->getLanguageService()->getLL('noEditPage'), (string)$editId)) . ', Severity.notice, [{
text: ' . GeneralUtility::quoteJSvalue($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:close')) . ',
active: true,
btnClass: "btn-info",
......@@ -552,7 +552,7 @@ class BackendController
protected function getCollapseStateOfMenu(): bool
{
$uc = json_decode(json_encode($this->getBackendUser()->uc), true);
$uc = json_decode((string)json_encode($this->getBackendUser()->uc), true);
$collapseState = $uc['BackendComponents']['States']['typo3-module-menu']['collapsed'] ?? false;
return $collapseState === true || $collapseState === 'true';
......
......@@ -288,6 +288,7 @@ class ElementHistoryController
protected function displayMultipleDiff(array $diff)
{
// Get all array keys needed
/** @var string[] $arrayKeys */
$arrayKeys = array_merge(array_keys($diff['newData']), array_keys($diff['insertsDeletes']), array_keys($diff['oldData']));
$arrayKeys = array_unique($arrayKeys);
if (!empty($arrayKeys)) {
......@@ -309,7 +310,7 @@ class ElementHistoryController
'newRecord' => $diff['oldData'][$key],
'oldRecord' => $diff['newData'][$key]
];
$singleLine['differences'] = $this->renderDiff($tmpArr, $elParts[0], $elParts[1]);
$singleLine['differences'] = $this->renderDiff($tmpArr, $elParts[0], (int)$elParts[1]);
}
$elParts = explode(':', $key);
$singleLine['revertRecordUrl'] = $this->buildUrl(['rollbackFields' => $key]);
......@@ -363,6 +364,7 @@ class ElementHistoryController
if (!$this->showDiff) {
// Display field names instead of full diff
// Re-write field names with labels
/** @var string[] $tmpFieldList */
$tmpFieldList = array_keys($entry['newRecord']);
foreach ($tmpFieldList as $key => $value) {
$tmp = str_replace(':', '', $languageService->sL(BackendUtility::getItemLabel($entry['tablename'], $value)));
......@@ -460,7 +462,7 @@ class ElementHistoryController
{
$title = $table . ':' . $uid;
if (!empty($GLOBALS['TCA'][$table]['ctrl']['label'])) {
$record = $this->getRecord($table, $uid);
$record = $this->getRecord($table, (int)$uid) ?? [];
$title .= ' (' . BackendUtility::getRecordTitle($table, $record, true) . ')';
}
return $title;
......
......@@ -369,7 +369,7 @@ class ElementInformationController
$label = $label ?: $name;
$propertiesForTable['fields'][] = [
'fieldValue' => BackendUtility::getProcessedValue($this->table, $name, $this->row[$name], 0, 0, false, $uid),
'fieldValue' => BackendUtility::getProcessedValue($this->table, $name, $this->row[$name], 0, false, false, $uid),
'fieldLabel' => htmlspecialchars($label)
];
}
......@@ -413,6 +413,7 @@ class ElementInformationController
// show the metadata of a file as well
$table = 'sys_file_metadata';
$metaDataRepository = GeneralUtility::makeInstance(MetaDataRepository::class);
/** @var array<string, string> $metaData */
$metaData = $metaDataRepository->findByFileUid($this->row['uid']);
$allowedFields = $this->getFieldList($table, (int)$metaData['uid']);
......@@ -431,7 +432,7 @@ class ElementInformationController
$label = $label ?: $name;
$propertiesForTable['fields'][] = [
'fieldValue' => BackendUtility::getProcessedValue($table, $name, $metaData[$name], 0, 0, false, $metaData['uid']),
'fieldValue' => BackendUtility::getProcessedValue($table, $name, $metaData[$name], 0, false, false, (int)$metaData['uid']),
'fieldLabel' => htmlspecialchars($label)
];
}
......@@ -498,7 +499,7 @@ class ElementInformationController
} else {
foreach (['crdate' => 'creationDate', 'tstamp' => 'timestamp', 'cruser_id' => 'creationUserId'] as $field => $label) {
if (isset($GLOBALS['TCA'][$this->table]['ctrl'][$field])) {
$extraFields[$GLOBALS['TCA'][$this->table]['ctrl'][$field]] = htmlspecialchars($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.' . $label));
$extraFields[(string)$GLOBALS['TCA'][$this->table]['ctrl'][$field]] = htmlspecialchars($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.' . $label));
}
}
}
......@@ -516,7 +517,7 @@ class ElementInformationController
// show the backend username who created the issue
if ($name === 'cruser_id' && $rowValue) {
$creatorRecord = BackendUtility::getRecord('be_users', $rowValue);
$creatorRecord = BackendUtility::getRecord('be_users', (int)$rowValue);
if ($creatorRecord) {
/** @var Avatar $avatar */
$avatar = GeneralUtility::makeInstance(Avatar::class);
......@@ -631,7 +632,7 @@ class ElementInformationController
* Make reference display
*
* @param string $table Table name
* @param string|\TYPO3\CMS\Core\Resource\File $ref Filename or uid
* @param int|\TYPO3\CMS\Core\Resource\File $ref Filename or uid
* @param ServerRequestInterface $request
* @return array
* @throws RouteNotFoundException
......@@ -735,7 +736,7 @@ class ElementInformationController
* Make reference display (what this elements points to)
*
* @param string $table Table name
* @param string $ref Filename or uid
* @param int $ref Filename or uid
* @param ServerRequestInterface $request
* @return array
*/
......
......@@ -75,7 +75,7 @@ class EditDocumentController
/**
* An array looking approx like [tablename][list-of-ids]=command, eg. "&edit[pages][123]=edit".
*
* @var array
* @var array<string,array>
*/
protected $editconf = [];
......@@ -615,10 +615,10 @@ class EditDocumentController
}
// Find the current table
reset($this->editconf);
$nTable = key($this->editconf);
$nTable = (string)key($this->editconf);
// Finding the first id, getting the records pid+uid
reset($this->editconf[$nTable]);
$nUid = key($this->editconf[$nTable]);
$nUid = (int)key($this->editconf[$nTable]);
$recordFields = 'pid,uid';
if (BackendUtility::isTableWorkspaceEnabled($nTable)) {
$recordFields .= ',t3ver_oid';
......@@ -658,7 +658,7 @@ class EditDocumentController
$this->closeDocument(self::DOCUMENT_CLOSE_MODE_NO_REDIRECT, $request);
// Find current table
reset($this->editconf);
$nTable = key($this->editconf);
$nTable = (string)key($this->editconf);
// Find the first id, getting the records pid+uid
reset($this->editconf[$nTable]);
$nUid = key($this->editconf[$nTable]);
......@@ -1657,15 +1657,15 @@ class EditDocumentController
$referenceCountMessage = BackendUtility::referenceCount(
$this->firstEl['table'],
(int)$this->firstEl['uid'],
(string)(int)$this->firstEl['uid'],
$this->getLanguageService()->sL(
'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.referencesToRecord'
),
$numberOfReferences
(string)$numberOfReferences
);
$translationCountMessage = BackendUtility::translationCount(
$this->firstEl['table'],
(int)$this->firstEl['uid'],
(string)(int)$this->firstEl['uid'],
$this->getLanguageService()->sL(
'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.translationsOfRecord'
)
......@@ -2439,7 +2439,7 @@ class EditDocumentController
// If ->returnEditConf is set, then add the current content of editconf to the ->retUrl variable: used by
// other scripts, like wizard_add, to know which records was created or so...
if ($this->returnEditConf && $this->retUrl != (string)$this->uriBuilder->buildUriFromRoute('dummy')) {
$this->retUrl .= '&returnEditConf=' . rawurlencode(json_encode($this->editconf));
$this->retUrl .= '&returnEditConf=' . rawurlencode((string)json_encode($this->editconf));
}
// If mode is NOT set (means 0) OR set to 1, then make a header location redirect to $this->retUrl
if ($mode === self::DOCUMENT_CLOSE_MODE_DEFAULT || $mode === self::DOCUMENT_CLOSE_MODE_REDIRECT) {
......@@ -2448,7 +2448,7 @@ class EditDocumentController
if ($this->retUrl === '') {
return null;
}
$retUrl = $this->returnUrl;
$retUrl = (string)$this->returnUrl;
if (is_array($this->docHandler) && !empty($this->docHandler)) {
if (!empty($setupArr[2])) {
$sParts = parse_url($request->getAttribute('normalizedParams')->getRequestUri());
......
......@@ -111,7 +111,7 @@ class ThumbnailController
);
if ($processedImage->isImage()) {
return new RedirectResponse(
GeneralUtility::locationHeaderUrl($processedImage->getPublicUrl(true))
GeneralUtility::locationHeaderUrl($processedImage->getPublicUrl(true) ?? '')
);
}
......
......@@ -50,7 +50,7 @@ class FormInlineAjaxController extends AbstractFormEngineAjaxController
$domObjectId = $ajaxArguments[0];
$inlineFirstPid = $this->getInlineFirstPidFromDomObjectId($domObjectId);
if (!MathUtility::canBeInterpretedAsInteger($inlineFirstPid) && strpos($inlineFirstPid, 'NEW') !== 0) {
if (!MathUtility::canBeInterpretedAsInteger($inlineFirstPid) && strpos((string)$inlineFirstPid, 'NEW') !== 0) {
throw new \RuntimeException(
'inlineFirstPid should either be an integer or a "NEW..." string',
1521220491
......@@ -675,7 +675,7 @@ class FormInlineAjaxController extends AbstractFormEngineAjaxController
* Get inlineFirstPid from a given objectId string
*
* @param string $domObjectId The id attribute of an element
* @return int|null Pid or null
* @return int|string|null Pid or null
*/
protected function getInlineFirstPidFromDomObjectId($domObjectId)
{
......
......@@ -68,7 +68,7 @@ class FormSlugAjaxController extends AbstractFormEngineAjaxController
$queryParameters = $request->getParsedBody() ?? [];
$values = $queryParameters['values'];
$mode = $queryParameters['mode'];
$tableName = $queryParameters['tableName'];
$tableName = (string)($queryParameters['tableName'] ?? '');
$pid = (int)$queryParameters['pageId'];
$parentPageId = (int)$queryParameters['parentPageId'];
$recordId = (int)$queryParameters['recordId'];
......@@ -76,7 +76,7 @@ class FormSlugAjaxController extends AbstractFormEngineAjaxController
$fieldName = $queryParameters['fieldName'];
$fieldConfig = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'] ?? [];
$row = BackendUtility::getRecord($tableName, $recordId);
$row = (array)BackendUtility::getRecord($tableName, $recordId);
$recordType = BackendUtility::getTCAtypeValue($tableName, $row);
$columnsOverridesConfigOfField = $GLOBALS['TCA'][$tableName]['types'][$recordType]['columnsOverrides'][$fieldName]['config'] ?? null;
if ($columnsOverridesConfigOfField) {
......
......@@ -104,7 +104,7 @@ class HelpController
$this->initializeView($action);
$result = call_user_func_array([$this, $action . 'Action'], [$request]);
$result = $this->{$action . 'Action'}($request);
if ($result instanceof ResponseInterface) {
return $result;
}
......
......@@ -523,6 +523,7 @@ class NewRecordController
if (is_array($GLOBALS['TCA'])) {
$groupName = '';
foreach ($GLOBALS['TCA'] as $table => $v) {
/** @var string $table */
$rootLevelConfiguration = isset($v['ctrl']['rootLevel']) ? (int)$v['ctrl']['rootLevel'] : 0;
if ($table !== 'pages'
&& $this->isRecordCreationAllowedForTable($table)
......@@ -576,7 +577,7 @@ class NewRecordController
$title = (string)($v['ctrl']['title'] ?? '');
if (strpos($title, 'LLL:EXT:') === 0) {
$_EXTKEY = substr($title, 8);
$_EXTKEY = substr($_EXTKEY, 0, strpos($_EXTKEY, '/'));
$_EXTKEY = substr($_EXTKEY, 0, (int)strpos($_EXTKEY, '/'));
if ($_EXTKEY !== '') {
// First try to get localisation of extension title
$temp = explode(':', substr($title, 9 + strlen($_EXTKEY)));
......
......@@ -403,7 +403,7 @@ class PageLayoutController
$path = BackendUtility::getRecordPath($targetPage['uid'], $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW), 1000);
$linkedPath = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($path) . '</a>';
$message .= sprintf(htmlspecialchars($lang->getLL('pageIsInternalLinkMessage')), $linkedPath);
$message .= ' (' . htmlspecialchars($lang->sL(BackendUtility::getLabelFromItemlist('pages', 'shortcut_mode', $shortcutMode))) . ')';
$message .= ' (' . htmlspecialchars($lang->sL(BackendUtility::getLabelFromItemlist('pages', 'shortcut_mode', (string)$shortcutMode))) . ')';
$state = InfoboxViewHelper::STATE_INFO;
}
} else {
......@@ -426,8 +426,9 @@ class PageLayoutController
]);
$content .= $view->render();
} else {
$externalUrl = htmlspecialchars(GeneralUtility::makeInstance(PageRepository::class)->getExtURL($this->pageinfo));
if ($externalUrl !== false) {
$externalUrl = GeneralUtility::makeInstance(PageRepository::class)->getExtURL($this->pageinfo);
if (is_string($externalUrl)) {
$externalUrl = htmlspecialchars($externalUrl);
$externalUrlHtml = '<a href="' . $externalUrl . '" target="_blank" rel="noreferrer">' . $externalUrl . '</a>';
$view->assignMultiple([
'title' => $this->pageinfo['title'],
......@@ -440,7 +441,7 @@ class PageLayoutController
}
// If content from different pid is displayed
if ($this->pageinfo['content_from_pid']) {
$contentPage = BackendUtility::getRecord('pages', (int)$this->pageinfo['content_from_pid']);
$contentPage = (array)BackendUtility::getRecord('pages', (int)$this->pageinfo['content_from_pid']);
$linkToPid = GeneralUtility::linkThisScript(['id' => $this->pageinfo['content_from_pid']]);
$title = BackendUtility::getRecordTitle('pages', $contentPage);
$link = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($title) . ' (PID ' . (int)$this->pageinfo['content_from_pid'] . ')</a>';
......
......@@ -106,7 +106,7 @@ class SiteConfigurationController
$this->initializeView($action);
$result = call_user_func_array([$this, $action . 'Action'], [$request]);
$result = $this->{$action . 'Action'}($request);
if ($result instanceof ResponseInterface) {
return $result;
}
......
......@@ -63,7 +63,7 @@ class SuggestWizardController
$fieldNameInPageTsConfig = $fieldName;
// With possible columnsOverrides
$row = BackendUtility::getRecord($tableName, $uid);
$row = BackendUtility::getRecord($tableName, $uid) ?? [];
$recordType = BackendUtility::getTCAtypeValue($tableName, $row);
$columnsOverridesConfigOfField = $GLOBALS['TCA'][$tableName]['types'][$recordType]['columnsOverrides'][$fieldName]['config'] ?? null;
if ($columnsOverridesConfigOfField) {
......
......@@ -598,7 +598,8 @@ class TableController extends AbstractWizardController
// Setting number of columns
// auto...
if (!$columns && trim($tableLines[0])) {
$columns = count(explode($this->tableParsing_delimiter, $tableLines[0]));
$exploded = explode($this->tableParsing_delimiter, $tableLines[0]);
$columns = is_array($exploded) ? count($exploded) : 0;
}
$columns = $columns ?: 4;
// Traverse the number of table elements:
......
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