Skip to content

Commit

Permalink
Handle strict type errors (see #110)
Browse files Browse the repository at this point in the history
* Cast interger values to string (#108)

* Handle more strict type logic errors
  • Loading branch information
zoglo authored Aug 10, 2024
1 parent c68bade commit 69132bf
Show file tree
Hide file tree
Showing 9 changed files with 57 additions and 29 deletions.
3 changes: 3 additions & 0 deletions src/ContaoManager/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ public function getBundles(ParserInterface $parser): array
];
}

/**
* @throws \Exception
*/
public function getRouteCollection(LoaderResolverInterface $resolver, KernelInterface $kernel): RouteCollection|null
{
return $resolver
Expand Down
18 changes: 13 additions & 5 deletions src/Controller/BackendModule/ImportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ public function __invoke(): Response
// Add xml extension as valid upload type
Config::set('uploadTypes', Config::get('uploadTypes') . ',xml');

/** @var FileUpload $objUploader */
$objUploader = new FileUpload();

// Get current request
Expand Down Expand Up @@ -143,7 +142,10 @@ public function createImportTree($archives, $groups, $files): array
{
$collection[ $alias ] = $group;

array_splice($_groups, array_search($alias, $_groups), 1);
// If nothing was found, cast strings and false to 0
$offset = (int) array_search($alias, $_groups);

array_splice($_groups, $offset, 1);
}
}

Expand Down Expand Up @@ -191,6 +193,7 @@ public function importByFileUploader(FileUpload $objUploader, bool $partial = fa
$uploaded = $objUploader->uploadTo('system/tmp');

// Get root dir
/** @var string $rootDir */
$rootDir = System::getContainer()->getParameter('kernel.project_dir');

if (empty($uploaded))
Expand Down Expand Up @@ -273,7 +276,7 @@ public static function importFiles(array $files, bool $blnSave = true, ?array $a
// Continue if there is no readable XML file
if (!$xml->loadXML($objFile->getContent()))
{
Message::addError($translator->trans('tl_theme.missing_xml', [basename($filePath)], 'contao_default'));
Message::addError($translator?->trans('tl_theme.missing_xml', [basename($filePath)], 'contao_default'));
continue;
}

Expand Down Expand Up @@ -362,7 +365,7 @@ public static function importFiles(array $files, bool $blnSave = true, ?array $a
if($strField === 'field')
{
$strName = $archive->item($a)->getAttribute('title');
$strValue = $archive->item($a)->nodeValue;
$strValue = $archive->item($a)->nodeValue ?? '';

if($strName === 'id' || strtolower($strValue) === 'null')
{
Expand Down Expand Up @@ -425,9 +428,12 @@ public static function importFiles(array $files, bool $blnSave = true, ?array $a
case 'cssClasses':
if($objChildren->{$strName})
{
/** @var array<array<int|string>> $arrClasses */
$arrClasses = StringUtil::deserialize($objChildren->{$strName}, true);
$arrExists = Sync::flattenKeyValueArray($arrClasses);
$arrValues = StringUtil::deserialize($strValue, true);

/** @var array<array<int|string>> $arrValues */
$arrValues = StringUtil::deserialize($strValue, true);

foreach($arrValues as $cssClass)
{
Expand All @@ -451,7 +457,9 @@ public static function importFiles(array $files, bool $blnSave = true, ?array $a

if(isset($dcaField['eval']['multiple']) && !!$dcaField['eval']['multiple'] && $dcaField['inputType'] === 'checkbox')
{
/** @var array<array<int|string>> $arrElements */
$arrElements = StringUtil::deserialize($objChildren->{$strName}, true);
/** @var array<array<int|string>> $arrValues */
$arrValues = StringUtil::deserialize($strValue, true);

foreach($arrValues as $element)
Expand Down
4 changes: 2 additions & 2 deletions src/EventSubscriber/KernelRequestSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@

class KernelRequestSubscriber implements EventSubscriberInterface
{
protected $scopeMatcher;
protected ScopeMatcher $scopeMatcher;

public function __construct(ScopeMatcher $scopeMatcher)
{
$this->scopeMatcher = $scopeMatcher;
}

public static function getSubscribedEvents()
public static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => 'onKernelRequest'];
}
Expand Down
12 changes: 8 additions & 4 deletions src/StyleManager/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,10 @@ public static function getGroups(?string $table=null): ?array
*/
public static function getBundleConfigurationFiles(): ?array
{

/** @var string $projectDir */
$projectDir = System::getContainer()->getParameter('kernel.project_dir');
$arrFiles = System::getContainer()->get('contao.resource_finder')->findIn('templates')->files()->name('style-manager-*.xml');
$arrFiles = System::getContainer()->get('contao.resource_finder')?->findIn('templates')?->files()?->name('style-manager-*.xml');
$arrBundleConfigs = null;

if ($projectTemplates = array_merge((glob($projectDir . '/templates/style-manager-*.xml') ?: []), (glob($projectDir . '/templates/*/style-manager-*.xml') ?: [])))
Expand Down Expand Up @@ -129,9 +131,11 @@ public static function getBundleConfigurationFiles(): ?array
*/
protected function loadBundleConfiguration(): array
{
if($arrFiles = $this->getBundleConfigurationFiles())
{
return ImportController::importFiles($arrFiles, false);
if (
($arrFiles = $this->getBundleConfigurationFiles())
&& (is_array($bundleConfig = ImportController::importFiles($arrFiles, false)))
) {
return $bundleConfig;
}

return [[],[]];
Expand Down
1 change: 1 addition & 0 deletions src/StyleManager/StyleManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public static function clearClasses(mixed $varValue, $dc)
$arrValues[ $k ] = ' ' . $v . ' ';
}

// Might need a strict type check for varvalue in the future as all following operations won't work with id or null
$varValue = ' ' . $varValue . ' ';
$varValue = str_replace($arrValues, ' ', $varValue);
$varValue = trim(preg_replace('#\s+#', ' ', $varValue));
Expand Down
7 changes: 6 additions & 1 deletion src/StyleManager/Styles.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public function format(string $format, string $method=''): string

if(null !== $this->exclGroups)
{
$arrValues = array_diff($arrValues, $this->exclGroups);
$arrValues = array_diff($arrValues ?? [], $this->exclGroups);
}

if($arrValues !== null && $jsonValue = json_encode($arrValues))
Expand Down Expand Up @@ -224,6 +224,11 @@ private function parseValueType($strValue)
*/
private function removeExcludedGroups(array &$currGroups): void
{
if (null === $this->exclGroups)
{
return;
}

foreach ($this->exclGroups as $exclude)
{
if (array_key_exists($exclude, $currGroups))
Expand Down
23 changes: 14 additions & 9 deletions src/StyleManager/Sync.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,9 @@ public static function mergeGroupObjects(?StyleManagerModel $objOriginal, ?Style
foreach ($objMerge->row() as $field => $value)
{
if(
($skipEmpty && (!$value || strtolower((string) $value) === 'null')) ||
(null !== $skipFields && in_array($field, $skipFields))
)
{
($skipEmpty && (!$value || strtolower((string) $value) === 'null'))
|| (null !== $skipFields && in_array($field, $skipFields))
) {
continue;
}

Expand All @@ -209,9 +208,12 @@ public static function mergeGroupObjects(?StyleManagerModel $objOriginal, ?Style
case 'cssClasses':
if($objOriginal->{$field})
{
/** @var array $arrClasses */
$arrClasses = StringUtil::deserialize($objOriginal->{$field}, true);
$arrExists = self::flattenKeyValueArray($arrClasses);
$arrValues = StringUtil::deserialize($value, true);
$arrExists = self::flattenKeyValueArray($arrClasses);

/** @var array $arrValues */
$arrValues = StringUtil::deserialize($value, true);

foreach($arrValues as $cssClass)
{
Expand Down Expand Up @@ -250,8 +252,11 @@ public static function mergeGroupObjects(?StyleManagerModel $objOriginal, ?Style

if(isset($fieldOptions['eval']['multiple']) && !!$fieldOptions['eval']['multiple'] && $fieldOptions['inputType'] === 'checkbox')
{
/** @var array $arrElements */
$arrElements = StringUtil::deserialize($objOriginal->{$field}, true);
$arrValues = StringUtil::deserialize($value, true);

/** @var array $arrValues */
$arrValues = StringUtil::deserialize($value, true);

foreach($arrValues as $element)
{
Expand Down Expand Up @@ -399,7 +404,7 @@ protected function addRowData(DOMDocument $xml, DOMNode $row, array $arrData): v
$v = 'NULL';
}

$value = $xml->createTextNode($v);
$value = $xml->createTextNode((string) $v);
$field->appendChild($value);
}
}
Expand All @@ -411,7 +416,7 @@ public static function flattenKeyValueArray($arr): array
{
if(empty($arr))
{
return $arr;
return [];
}

$arrTmp = array();
Expand Down
1 change: 1 addition & 0 deletions src/Twig/StyleManagerExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public function createContext(array $data): Styles
$arrStyles = StringUtil::deserialize($data['styleManager'], true);
}*/

/** @var array $arrStyles */
$arrStyles = StringUtil::deserialize($data['styleManager'], true);

return new Styles($arrStyles[StyleManager::VARS_KEY] ?? null);
Expand Down
17 changes: 9 additions & 8 deletions src/Widget/ComponentStyleSelect.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ class ComponentStyleSelect extends Widget
*/
protected $strTemplate = 'be_widget';

private readonly ContaoCsrfTokenManager $tokenManager;
private readonly ?ContaoCsrfTokenManager $tokenManager;

private readonly InsertTagParser $insertTagParser;
private readonly ?InsertTagParser $insertTagParser;

private readonly RequestStack $requestStack;
private readonly ?RequestStack $requestStack;

private readonly bool $showGroupTitle;

Expand Down Expand Up @@ -120,7 +120,8 @@ public function generate()
// skip specific content elements
if(!!$objStyleGroup->extendContentElement && $this->strTable === 'tl_content')
{
$arrContentElements = StringUtil::deserialize($objStyleGroup->contentElements);
/** @var array $arrContentElements */
$arrContentElements = StringUtil::deserialize($objStyleGroup->contentElements, true);

if($arrContentElements !== null && !in_array($this->activeRecord->type, $arrContentElements))
{
Expand Down Expand Up @@ -253,8 +254,8 @@ public function generate()
return $this->renderEmptyMessage();
}

$objSession = $this->requestStack->getSession()->getBag('contao_backend');
$arrSession = $objSession->get('stylemanager_section_states');
$objSession = $this->requestStack?->getSession()->getBag('contao_backend');
$arrSession = $objSession?->get('stylemanager_section_states');

$arrGroups = array();
$arrSections = array();
Expand Down Expand Up @@ -290,7 +291,7 @@ public function generate()
$this->id,
$groupAlias,
$identifier,
$this->tokenManager->getDefaultTokenValue()
$this->tokenManager?->getDefaultTokenValue()
);

$arrNavigation[ $index ] = sprintf('<input type="radio" id="nav-%s" class="tab-nav" name="nav-%s" %s><label for="nav-%s" %s>%s</label>',
Expand All @@ -304,7 +305,7 @@ public function generate()

$arrContent[ $index ] = sprintf('<div id="tab-%s" class="tab-content">%s%s</div>',
$identifier,
(trim($group['desc'] ?? '') ? '<div class="long desc">' . $this->insertTagParser->replaceInline(nl2br($group['desc'])) . '</div>' : ''),
(trim($group['desc'] ?? '') ? '<div class="long desc">' . $this->insertTagParser?->replaceInline(nl2br($group['desc'])) . '</div>' : ''),
implode("", $group['fields'])
);

Expand Down

0 comments on commit 69132bf

Please sign in to comment.