diff --git a/bundles/CoreBundle/src/Command/Bundle/ListCommand.php b/bundles/CoreBundle/src/Command/Bundle/ListCommand.php index 0db20a3a60e..f02016427cb 100644 --- a/bundles/CoreBundle/src/Command/Bundle/ListCommand.php +++ b/bundles/CoreBundle/src/Command/Bundle/ListCommand.php @@ -96,9 +96,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } if ($input->getOption('json')) { - $jsonData = array_map(static function ($row) use ($returnData) { - return array_combine($returnData['headers'], $row); - }, $returnData['rows']); + $jsonData = array_map(fn($row) => array_combine($returnData['headers'], $row), $returnData['rows']); $output->write(\json_encode($jsonData, \JSON_PRETTY_PRINT)); } else { $table = new Table($output); diff --git a/bundles/CoreBundle/src/Command/DeleteUnusedLocaleDataCommand.php b/bundles/CoreBundle/src/Command/DeleteUnusedLocaleDataCommand.php index 870abc628da..f29c4581fe8 100644 --- a/bundles/CoreBundle/src/Command/DeleteUnusedLocaleDataCommand.php +++ b/bundles/CoreBundle/src/Command/DeleteUnusedLocaleDataCommand.php @@ -88,43 +88,38 @@ protected function execute(InputInterface $input, OutputInterface $output): int //drop unused localized view e.g. object_localized_classId_* $existingViews = $db->fetchAllAssociative("SHOW TABLES LIKE 'object\_localized\_{$classId}\_%'"); + foreach ($existingViews as $existingView) { + $localizedView = current($existingView); + $existingLanguage = str_replace('object_localized_'.$classId.'_', '', $localizedView); - if (is_array($existingViews)) { - foreach ($existingViews as $existingView) { - $localizedView = current($existingView); - $existingLanguage = str_replace('object_localized_'.$classId.'_', '', $localizedView); - - if (!in_array($existingLanguage, $validLanguages)) { - $sqlDropView = 'DROP VIEW IF EXISTS object_localized_' . $classId . '_' .$existingLanguage; - $printLine = true; - - if (!$this->isDryRun()) { - $output->writeln($sqlDropView); - $db->executeQuery($sqlDropView); - } else { - $output->writeln($this->dryRunMessage($sqlDropView)); - } + if (!in_array($existingLanguage, $validLanguages)) { + $sqlDropView = 'DROP VIEW IF EXISTS object_localized_' . $classId . '_' .$existingLanguage; + $printLine = true; + + if (!$this->isDryRun()) { + $output->writeln($sqlDropView); + $db->executeQuery($sqlDropView); + } else { + $output->writeln($this->dryRunMessage($sqlDropView)); } } } //drop unused localized table e.g. object_localized_query_classId_* $existingTables = $db->fetchAllAssociative("SHOW TABLES LIKE 'object\_localized\_query\_{$classId}\_%'"); - if (is_array($existingTables)) { - foreach ($existingTables as $existingTable) { - $localizedTable = current($existingTable); - $existingLanguage = str_replace('object_localized_query_'.$classId.'_', '', $localizedTable); - - if (!in_array($existingLanguage, $validLanguages)) { - $sqlDropTable = 'DROP TABLE IF EXISTS object_localized_query_' . $classId . '_' .$existingLanguage; - $printLine = true; - - if (!$this->isDryRun()) { - $output->writeln($sqlDropTable); - $db->executeQuery($sqlDropTable); - } else { - $output->writeln($this->dryRunMessage($sqlDropTable)); - } + foreach ($existingTables as $existingTable) { + $localizedTable = current($existingTable); + $existingLanguage = str_replace('object_localized_query_'.$classId.'_', '', $localizedTable); + + if (!in_array($existingLanguage, $validLanguages)) { + $sqlDropTable = 'DROP TABLE IF EXISTS object_localized_query_' . $classId . '_' .$existingLanguage; + $printLine = true; + + if (!$this->isDryRun()) { + $output->writeln($sqlDropTable); + $db->executeQuery($sqlDropTable); + } else { + $output->writeln($this->dryRunMessage($sqlDropTable)); } } } diff --git a/bundles/CustomReportsBundle/src/Controller/Reports/CustomReportController.php b/bundles/CustomReportsBundle/src/Controller/Reports/CustomReportController.php index 9d4dfff1891..9342d32ea27 100644 --- a/bundles/CustomReportsBundle/src/Controller/Reports/CustomReportController.php +++ b/bundles/CustomReportsBundle/src/Controller/Reports/CustomReportController.php @@ -223,9 +223,6 @@ public function columnConfigAction(Request $request): JsonResponse throw $this->createNotFoundException(); } $columnConfiguration = $report->getColumnConfiguration(); - if (!is_array($columnConfiguration)) { - $columnConfiguration = []; - } $configuration = json_decode($request->get('configuration')); $configuration = $configuration[0] ?? null; @@ -238,9 +235,6 @@ public function columnConfigAction(Request $request): JsonResponse try { $adapter = Tool\Config::getAdapter($configuration); $columns = $adapter->getColumns($configuration); - if (!is_array($columns)) { - $columns = []; - } foreach ($columnConfiguration as $item) { $name = $item['name']; diff --git a/bundles/CustomReportsBundle/src/Tool/Adapter/Sql.php b/bundles/CustomReportsBundle/src/Tool/Adapter/Sql.php index cc48eb36d58..be841ddbc3e 100644 --- a/bundles/CustomReportsBundle/src/Tool/Adapter/Sql.php +++ b/bundles/CustomReportsBundle/src/Tool/Adapter/Sql.php @@ -132,55 +132,50 @@ protected function getBaseQuery(array $filters, array $fields, bool $ignoreSelec $sql = $this->buildQueryString($this->config, $ignoreSelectAndGroupBy, $drillDownFilters, $selectField); - $data = ''; $extractAllFields = empty($fields); - if ($filters) { - if (is_array($filters)) { - foreach ($filters as $filter) { - $value = $filter['value'] ?? null; - $type = $filter['type']; - $operator = $filter['operator']; - $maxValue = null; + foreach ($filters as $filter) { + $value = $filter['value'] ?? null; + $type = $filter['type']; + $operator = $filter['operator']; + $maxValue = null; + if ($type == 'date') { + if ($operator == 'eq') { + $maxValue = strtotime($value . '+23 hours 59 minutes'); + } + $value = strtotime($value); + } + + switch ($operator) { + case 'like': + $fields[] = $filter['property']; + $condition[] = $db->quoteIdentifier($filter['property']) . ' LIKE ' . $db->quote('%' . $value. '%'); + + break; + case 'lt': + case 'gt': + case 'eq': + $compMapping = [ + 'lt' => '<', + 'gt' => '>', + 'eq' => '=', + ]; + if ($type == 'date') { if ($operator == 'eq') { - $maxValue = strtotime($value . '+23 hours 59 minutes'); - } - $value = strtotime($value); - } - - switch ($operator) { - case 'like': - $fields[] = $filter['property']; - $condition[] = $db->quoteIdentifier($filter['property']) . ' LIKE ' . $db->quote('%' . $value. '%'); + $condition[] = $db->quoteIdentifier($filter['property']) . ' BETWEEN ' . $db->quote($value) . ' AND ' . $db->quote($maxValue); break; - case 'lt': - case 'gt': - case 'eq': - $compMapping = [ - 'lt' => '<', - 'gt' => '>', - 'eq' => '=', - ]; - - if ($type == 'date') { - if ($operator == 'eq') { - $condition[] = $db->quoteIdentifier($filter['property']) . ' BETWEEN ' . $db->quote($value) . ' AND ' . $db->quote($maxValue); - - break; - } - } - $fields[] = $filter['property']; - $condition[] = $db->quoteIdentifier($filter['property']) . ' ' . $compMapping[$operator] . ' ' . $db->quote($value); + } + } + $fields[] = $filter['property']; + $condition[] = $db->quoteIdentifier($filter['property']) . ' ' . $compMapping[$operator] . ' ' . $db->quote($value); - break; - case '=': - $fields[] = $filter['property']; - $condition[] = $db->quoteIdentifier($filter['property']) . ' = ' . $db->quote($value); + break; + case '=': + $fields[] = $filter['property']; + $condition[] = $db->quoteIdentifier($filter['property']) . ' = ' . $db->quote($value); - break; - } - } + break; } } diff --git a/bundles/CustomReportsBundle/src/Tool/Config.php b/bundles/CustomReportsBundle/src/Tool/Config.php index 6b9a6b15e72..ca9e5d37304 100644 --- a/bundles/CustomReportsBundle/src/Tool/Config.php +++ b/bundles/CustomReportsBundle/src/Tool/Config.php @@ -228,7 +228,7 @@ public function setDataSourceConfig(array $dataSourceConfig): void public function getDataSourceConfig(): ?\stdClass { - if (is_array($this->dataSourceConfig) && isset($this->dataSourceConfig[0])) { + if (isset($this->dataSourceConfig[0])) { $dataSourceConfig = new \stdClass(); $dataSourceConfigArray = $this->dataSourceConfig[0]; diff --git a/bundles/GlossaryBundle/src/Twig/Extension/GlossaryExtension.php b/bundles/GlossaryBundle/src/Twig/Extension/GlossaryExtension.php index 690a98aa220..0c6253ce3cd 100644 --- a/bundles/GlossaryBundle/src/Twig/Extension/GlossaryExtension.php +++ b/bundles/GlossaryBundle/src/Twig/Extension/GlossaryExtension.php @@ -42,7 +42,7 @@ public function getFilters(): array public function applyGlossary(string $string, array $options = []): string { - if (empty($string) || !is_string($string)) { + if (!$string) { return $string; } diff --git a/bundles/SeoBundle/src/EventListener/UrlSlugUpdateListener.php b/bundles/SeoBundle/src/EventListener/UrlSlugUpdateListener.php index 4e7e71ff72a..58863890514 100644 --- a/bundles/SeoBundle/src/EventListener/UrlSlugUpdateListener.php +++ b/bundles/SeoBundle/src/EventListener/UrlSlugUpdateListener.php @@ -43,7 +43,7 @@ public function onURLSlugUpdate(UrlSlugEvent $event): void $pimcore_seo_redirects = Pimcore::getContainer()->getParameter('pimcore_seo.redirects'); $data = $event->getData(); // check for previous slugs and create redirects - if (!is_array($data) || !$pimcore_seo_redirects['auto_create_redirects']) { + if (!$pimcore_seo_redirects['auto_create_redirects']) { return; } diff --git a/bundles/SeoBundle/src/Redirect/Csv.php b/bundles/SeoBundle/src/Redirect/Csv.php index 2392abfb678..7305e1a2ab8 100644 --- a/bundles/SeoBundle/src/Redirect/Csv.php +++ b/bundles/SeoBundle/src/Redirect/Csv.php @@ -34,6 +34,9 @@ */ class Csv { + /** + * @var string[] + */ private array $columns = [ 'id', 'type', diff --git a/bundles/SimpleBackendSearchBundle/src/Controller/SearchController.php b/bundles/SimpleBackendSearchBundle/src/Controller/SearchController.php index ead16ad760f..4bc2928910c 100644 --- a/bundles/SimpleBackendSearchBundle/src/Controller/SearchController.php +++ b/bundles/SimpleBackendSearchBundle/src/Controller/SearchController.php @@ -187,7 +187,7 @@ public function findAction(Request $request, EventDispatcherInterface $eventDisp } } - if (is_array($types) && !empty($types[0])) { + if ($types[0]) { $conditionTypeParts = []; foreach ($types as $type) { $conditionTypeParts[] = $db->quote($type); @@ -198,7 +198,7 @@ public function findAction(Request $request, EventDispatcherInterface $eventDisp $conditionParts[] = '( maintype IN (' . implode(',', $conditionTypeParts) . ') )'; } - if (is_array($subtypes) && !empty($subtypes[0])) { + if ($subtypes[0]) { $conditionSubtypeParts = []; foreach ($subtypes as $subtype) { $conditionSubtypeParts[] = $db->quote($subtype); @@ -206,7 +206,7 @@ public function findAction(Request $request, EventDispatcherInterface $eventDisp $conditionParts[] = '( `type` IN (' . implode(',', $conditionSubtypeParts) . ') )'; } - if (is_array($classnames) && !empty($classnames[0])) { + if ($classnames[0]) { if (in_array('folder', $subtypes)) { $classnames[] = 'folder'; } @@ -222,10 +222,8 @@ public function findAction(Request $request, EventDispatcherInterface $eventDisp $tagIds = $allParams['tagIds']; $tagsTypeCondition = ''; - if (is_array($types) && !empty($types[0])) { + if ($types[0]) { $tagsTypeCondition = 'ctype IN (\'' . implode('\',\'', $types) . '\') AND'; - } elseif (!is_array($types)) { - $tagsTypeCondition = 'ctype = ' . $db->quote($types) . ' AND '; } foreach ($tagIds as $tagId) { diff --git a/bundles/SimpleBackendSearchBundle/src/DataProvider/GDPR/DataObjects.php b/bundles/SimpleBackendSearchBundle/src/DataProvider/GDPR/DataObjects.php index 606f85031ad..3af045e8ee2 100644 --- a/bundles/SimpleBackendSearchBundle/src/DataProvider/GDPR/DataObjects.php +++ b/bundles/SimpleBackendSearchBundle/src/DataProvider/GDPR/DataObjects.php @@ -65,7 +65,7 @@ public function searchData(int $id, string $firstname, string $lastname, string } } - if (is_array($classnames) && !empty($classnames[0])) { + if ($classnames) { $conditionClassnameParts = []; foreach ($classnames as $classname) { $conditionClassnameParts[] = $db->quote($classname); diff --git a/bundles/SimpleBackendSearchBundle/src/Model/Search/Backend/Data.php b/bundles/SimpleBackendSearchBundle/src/Model/Search/Backend/Data.php index 5d5e96d2e78..10ccde605cc 100644 --- a/bundles/SimpleBackendSearchBundle/src/Model/Search/Backend/Data.php +++ b/bundles/SimpleBackendSearchBundle/src/Model/Search/Backend/Data.php @@ -337,15 +337,13 @@ public function setDataFromElement(Element\ElementInterface $element): static $this->properties = ''; $properties = $element->getProperties(); - if (is_array($properties)) { - foreach ($properties as $nextProperty) { - $pData = (string) $nextProperty->getData(); - if ($nextProperty->getName() === 'bool') { - $pData = $pData ? 'true' : 'false'; - } - - $this->properties .= $nextProperty->getName() . ':' . $pData .' '; + foreach ($properties as $nextProperty) { + $pData = (string) $nextProperty->getData(); + if ($nextProperty->getName() === 'bool') { + $pData = $pData ? 'true' : 'false'; } + + $this->properties .= $nextProperty->getName() . ':' . $pData .' '; } $this->data = ''; @@ -359,18 +357,16 @@ public function setDataFromElement(Element\ElementInterface $element): static } elseif ($element instanceof Document\PageSnippet) { $this->published = $element->isPublished(); $editables = $element->getEditables(); - if (is_array($editables) && !empty($editables)) { - foreach ($editables as $editable) { - if ($editable instanceof Document\Editable\EditableInterface) { - // areabrick elements are handled by getElementTypes()/getElements() as they return area elements as well - if ($editable instanceof Document\Editable\Area || $editable instanceof Document\Editable\Areablock) { - continue; - } - - ob_start(); - $this->data .= strip_tags((string) $editable->frontend()).' '; - $this->data .= ob_get_clean(); + foreach ($editables as $editable) { + if ($editable instanceof Document\Editable\EditableInterface) { + // areabrick elements are handled by getElementTypes()/getElements() as they return area elements as well + if ($editable instanceof Document\Editable\Area || $editable instanceof Document\Editable\Areablock) { + continue; } + + ob_start(); + $this->data .= strip_tags((string) $editable->frontend()).' '; + $this->data .= ob_get_clean(); } } if ($element instanceof Document\Page) { diff --git a/bundles/StaticRoutesBundle/src/Controller/SettingsController.php b/bundles/StaticRoutesBundle/src/Controller/SettingsController.php index c049340524e..9202580d4e6 100644 --- a/bundles/StaticRoutesBundle/src/Controller/SettingsController.php +++ b/bundles/StaticRoutesBundle/src/Controller/SettingsController.php @@ -111,9 +111,7 @@ public function staticroutesAction(Request $request): JsonResponse foreach ($list->getRoutes() as $routeFromList) { $route = $routeFromList->getObjectVars(); $route['writeable'] = $routeFromList->isWriteable(); - if (is_array($routeFromList->getSiteId())) { - $route['siteId'] = implode(',', $routeFromList->getSiteId()); - } + $route['siteId'] = implode(',', $routeFromList->getSiteId()); $routes[] = $route; } diff --git a/bundles/StaticRoutesBundle/src/Model/Staticroute.php b/bundles/StaticRoutesBundle/src/Model/Staticroute.php index af39b4a6292..c1284eb046e 100644 --- a/bundles/StaticRoutesBundle/src/Model/Staticroute.php +++ b/bundles/StaticRoutesBundle/src/Model/Staticroute.php @@ -481,13 +481,11 @@ public function match(string $path, array $params = []): bool|array preg_match_all($this->getPattern(), $path, $matches); - if (is_array($matches) && count($matches) > 1) { - foreach ($matches as $index => $match) { - if (isset($variables[$index - 1]) && $variables[$index - 1]) { - $paramValue = urldecode($match[0]); - if (!empty($paramValue) || !array_key_exists($variables[$index - 1], $params)) { - $params[$variables[$index - 1]] = $paramValue; - } + foreach ($matches as $index => $match) { + if (isset($variables[$index - 1]) && $variables[$index - 1]) { + $paramValue = urldecode($match[0]); + if (!empty($paramValue) || !array_key_exists($variables[$index - 1], $params)) { + $params[$variables[$index - 1]] = $paramValue; } } } diff --git a/composer.json b/composer.json index 85749815d72..65928b9ce26 100644 --- a/composer.json +++ b/composer.json @@ -140,8 +140,8 @@ "codeception/module-symfony": "^3.1.0", "codeception/phpunit-wrapper": "^9", "ergebnis/phpstan-rules": "^2.0", - "phpstan/phpstan": "1.10.5", - "phpstan/phpstan-symfony": "^1.2.20", + "phpstan/phpstan": "1.10.26", + "phpstan/phpstan-symfony": "^1.3.2", "phpunit/phpunit": "^9.3", "gotenberg/gotenberg-php": "^1.1", "composer/composer": "*", diff --git a/lib/Cache/FullPage/SessionStatus.php b/lib/Cache/FullPage/SessionStatus.php index 570f7a0f0c0..39641c04bf6 100644 --- a/lib/Cache/FullPage/SessionStatus.php +++ b/lib/Cache/FullPage/SessionStatus.php @@ -50,11 +50,7 @@ public function isDisabledBySession(Request $request): bool // we fall back to $_SESSION from here on as the session API does not expose a list of namespaces $sessionData = $_SESSION ?? null; - if (empty($sessionData)) { - return false; - } - - if (!is_array($sessionData)) { + if (!$sessionData) { return false; } diff --git a/lib/Composer.php b/lib/Composer.php index 6428987b9b7..e38fc2c610c 100644 --- a/lib/Composer.php +++ b/lib/Composer.php @@ -159,13 +159,8 @@ protected static function getPhp(bool $includeArgs = true): string */ protected static function getPhpArguments(): array { - $ini = null; - $arguments = []; - $phpFinder = new PhpExecutableFinder(); - if (method_exists($phpFinder, 'findArguments')) { - $arguments = $phpFinder->findArguments(); - } + $arguments = $phpFinder->findArguments(); if(!empty($_SERVER['COMPOSER_ORIGINAL_INIS'])) { $paths = explode(PATH_SEPARATOR, $_SERVER['COMPOSER_ORIGINAL_INIS']); diff --git a/lib/Composer/PackageInfo.php b/lib/Composer/PackageInfo.php index a426f33d3cb..3099f40bdf8 100644 --- a/lib/Composer/PackageInfo.php +++ b/lib/Composer/PackageInfo.php @@ -51,7 +51,7 @@ private function readInstalledPackages(): array } $json = $this->readComposerFile(PIMCORE_COMPOSER_PATH . '/composer/installed.json'); - if ($json && is_array($json)) { + if ($json) { return $this->installedPackages = $json['packages'] ?? $json; } diff --git a/lib/DataObject/ClassBuilder/FieldCollectionClassBuilder.php b/lib/DataObject/ClassBuilder/FieldCollectionClassBuilder.php index c64d9f356bb..6e7717c9a25 100644 --- a/lib/DataObject/ClassBuilder/FieldCollectionClassBuilder.php +++ b/lib/DataObject/ClassBuilder/FieldCollectionClassBuilder.php @@ -72,19 +72,17 @@ public function buildClass(Definition $definition): string $cd .= "\n\n"; $fdDefs = $definition->getFieldDefinitions(); - if (is_array($fdDefs) && count($fdDefs)) { - foreach ($fdDefs as $key => $def) { - $cd .= $def->getGetterCodeFieldcollection($definition); + foreach ($fdDefs as $def) { + $cd .= $def->getGetterCodeFieldcollection($definition); - if ($def instanceof ClassDefinition\Data\Localizedfields) { - $cd .= $def->getGetterCode($definition); - } + if ($def instanceof ClassDefinition\Data\Localizedfields) { + $cd .= $def->getGetterCode($definition); + } - $cd .= $def->getSetterCodeFieldcollection($definition); + $cd .= $def->getSetterCodeFieldcollection($definition); - if ($def instanceof ClassDefinition\Data\Localizedfields) { - $cd .= $def->getSetterCode($definition); - } + if ($def instanceof ClassDefinition\Data\Localizedfields) { + $cd .= $def->getSetterCode($definition); } } diff --git a/lib/DataObject/ClassBuilder/FieldDefinitionPropertiesBuilder.php b/lib/DataObject/ClassBuilder/FieldDefinitionPropertiesBuilder.php index a0e5f7ac719..e55d59f94e2 100644 --- a/lib/DataObject/ClassBuilder/FieldDefinitionPropertiesBuilder.php +++ b/lib/DataObject/ClassBuilder/FieldDefinitionPropertiesBuilder.php @@ -27,12 +27,10 @@ public function buildProperties(ClassDefinition $classDefinition): string $cd .= 'protected $classId = "' . $classDefinition->getId(). "\";\n"; $cd .= 'protected $className = "'.$classDefinition->getName().'"'.";\n"; - if (is_array($classDefinition->getFieldDefinitions()) && count($classDefinition->getFieldDefinitions())) { - foreach ($classDefinition->getFieldDefinitions() as $key => $def) { - if (!$def instanceof ClassDefinition\Data\ReverseObjectRelation && !$def instanceof ClassDefinition\Data\CalculatedValue - ) { - $cd .= 'protected $'.$key.";\n"; - } + foreach ($classDefinition->getFieldDefinitions() as $key => $def) { + if (!$def instanceof ClassDefinition\Data\ReverseObjectRelation && !$def instanceof ClassDefinition\Data\CalculatedValue + ) { + $cd .= 'protected $'.$key.";\n"; } } diff --git a/lib/DataObject/ClassBuilder/ListingClassBuilder.php b/lib/DataObject/ClassBuilder/ListingClassBuilder.php index a839ad74e42..e09f7878ced 100644 --- a/lib/DataObject/ClassBuilder/ListingClassBuilder.php +++ b/lib/DataObject/ClassBuilder/ListingClassBuilder.php @@ -61,10 +61,8 @@ public function buildListingClass(ClassDefinition $classDefinition): string $cd .= "\n\n"; - if (\is_array($classDefinition->getFieldDefinitions())) { - foreach ($classDefinition->getFieldDefinitions() as $def) { - $cd .= $this->fieldDefinitionBuilder->buildListingClassFieldDefinition($classDefinition, $def); - } + foreach ($classDefinition->getFieldDefinitions() as $def) { + $cd .= $this->fieldDefinitionBuilder->buildListingClassFieldDefinition($classDefinition, $def); } $cd .= "\n\n"; diff --git a/lib/Document/Adapter.php b/lib/Document/Adapter.php index cb42fc309d9..8bbd634f979 100644 --- a/lib/Document/Adapter.php +++ b/lib/Document/Adapter.php @@ -49,15 +49,15 @@ abstract public function load(Asset\Document $asset): static; abstract public function saveImage(string $imageTargetPath, int $page = 1, int $resolution = 200): mixed; /** - * * @return resource + * + * @throws \Exception */ abstract public function getPdf(?Asset\Document $asset = null); abstract public function isFileTypeSupported(string $fileType): bool; /** - * * @throws \Exception */ abstract public function getPageCount(): int; diff --git a/lib/Document/Adapter/Ghostscript.php b/lib/Document/Adapter/Ghostscript.php index f6c33f7e8e9..a9a6b372632 100644 --- a/lib/Document/Adapter/Ghostscript.php +++ b/lib/Document/Adapter/Ghostscript.php @@ -103,7 +103,12 @@ public function getPdf(?Asset\Document $asset = null) } if (preg_match("/\.?pdf$/i", $asset->getFilename())) { // only PDF's are supported - return $asset->getStream(); + $file = $asset->getStream(); + if (!is_resource($file)) { + throw new \Exception(sprintf('Could not get pdf from asset with id %s', $asset->getId())); + } + + return $file; } $message = "Couldn't load document " . $asset->getRealFullPath() . ' only PDF documents are currently supported'; diff --git a/lib/Document/Adapter/Gotenberg.php b/lib/Document/Adapter/Gotenberg.php index aae4362e92e..eb4c16aa664 100644 --- a/lib/Document/Adapter/Gotenberg.php +++ b/lib/Document/Adapter/Gotenberg.php @@ -109,11 +109,6 @@ public function load(Asset\Document $asset): static return $this; } - /** - * - * - * @throws \Exception - */ public function getPdf(?Asset\Document $asset = null) { if (!$asset && $this->asset) { diff --git a/lib/Document/Adapter/LibreOffice.php b/lib/Document/Adapter/LibreOffice.php index 24ccd00fd5f..bf5945865bb 100644 --- a/lib/Document/Adapter/LibreOffice.php +++ b/lib/Document/Adapter/LibreOffice.php @@ -169,12 +169,9 @@ public function getText(?int $page = null, ?Asset\Document $asset = null, ?strin try { if (!parent::isFileTypeSupported($asset->getFilename())) { $file = $this->getPdf($asset); - if (!is_resource($file)) { - throw new \Exception(sprintf('Could not convert asset with id %s to pdf', $asset->getId())); - } $fileMetaData = stream_get_meta_data($file); - if (array_key_exists('uri', $fileMetaData) && !empty($fileMetaData['uri'])) { + if ($fileMetaData['uri']) { $path = $fileMetaData['uri']; } } diff --git a/lib/Extension/Bundle/PimcoreBundleLocator.php b/lib/Extension/Bundle/PimcoreBundleLocator.php index de6ce1a81c9..a2a5cc30c39 100644 --- a/lib/Extension/Bundle/PimcoreBundleLocator.php +++ b/lib/Extension/Bundle/PimcoreBundleLocator.php @@ -134,7 +134,7 @@ private function findComposerBundles(): array private function processBundleClass(string $bundle, array &$result): void { - if (empty($bundle) || !is_string($bundle)) { + if (!$bundle) { return; } diff --git a/lib/Image/Adapter/Imagick.php b/lib/Image/Adapter/Imagick.php index 6851be49061..0b6de87ef08 100644 --- a/lib/Image/Adapter/Imagick.php +++ b/lib/Image/Adapter/Imagick.php @@ -86,9 +86,7 @@ public function load(string $imagePath, array $options = []): static|false $this->resource = $i; if (!$this->reinitializing && !$this->isPreserveColor()) { - if (method_exists($i, 'setColorspace')) { - $i->setColorspace(\Imagick::COLORSPACE_SRGB); - } + $i->setColorspace(\Imagick::COLORSPACE_SRGB); if ($this->isVectorGraphic($imagePath)) { // only for vector graphics diff --git a/lib/Localization/LocaleService.php b/lib/Localization/LocaleService.php index f0784c99933..e4143be9d71 100644 --- a/lib/Localization/LocaleService.php +++ b/lib/Localization/LocaleService.php @@ -102,7 +102,7 @@ public function setLocale(?string $locale): void { $this->locale = $locale; - if ($locale && is_string($locale)) { + if ($locale) { if ($this->requestStack) { $mainRequest = $this->requestStack->getMainRequest(); if ($mainRequest) { diff --git a/lib/Mail.php b/lib/Mail.php index 1e73d62db70..057f896146b 100644 --- a/lib/Mail.php +++ b/lib/Mail.php @@ -304,11 +304,7 @@ public function setParams(array $params): static */ public function setParam(int|string $key, mixed $value): static { - if (is_string($key) || is_int($key)) { - $this->params[$key] = $value; - } else { - Logger::warn('$key has to be a string or integer - Param ignored!'); - } + $this->params[$key] = $value; return $this; } @@ -365,11 +361,7 @@ public function unsetParams(array $params): static */ public function unsetParam(int|string $key): static { - if (is_string($key) || is_int($key)) { - unset($this->params[$key]); - } else { - Logger::warn('$key has to be a string or integer - unsetParam ignored!'); - } + unset($this->params[$key]); return $this; } diff --git a/lib/Maintenance/Tasks/LogCleanupTask.php b/lib/Maintenance/Tasks/LogCleanupTask.php index 8da315055a7..44c52c4e638 100644 --- a/lib/Maintenance/Tasks/LogCleanupTask.php +++ b/lib/Maintenance/Tasks/LogCleanupTask.php @@ -61,14 +61,12 @@ public function execute(): void $files = array_merge($files, $archivedLogFiles); } - if (is_array($files)) { - foreach ($files as $file) { - if (filemtime($file) < (time() - (86400 * 7))) { // we keep the logs for 7 days - unlink($file); - } elseif (!preg_match("/\.gz$/", $file)) { - gzcompressfile($file); - unlink($file); - } + foreach ($files as $file) { + if (filemtime($file) < (time() - (86400 * 7))) { // we keep the logs for 7 days + unlink($file); + } elseif (!preg_match("/\.gz$/", $file)) { + gzcompressfile($file); + unlink($file); } } } diff --git a/lib/Maintenance/Tasks/VersionsCleanupTask.php b/lib/Maintenance/Tasks/VersionsCleanupTask.php index 94824b0976a..56d734b61bf 100644 --- a/lib/Maintenance/Tasks/VersionsCleanupTask.php +++ b/lib/Maintenance/Tasks/VersionsCleanupTask.php @@ -113,63 +113,61 @@ private function doVersionCleanup(): void $this->logger->debug('versions to check: ' . count($versions)); - if (is_array($versions)) { - $totalCount = count($versions); - foreach ($versions as $index => $id) { - if (!$version = Version::getById($id)) { - $ignoredIds[] = $id; - $this->logger->debug('Version with ' . $id . " not found\n"); - - continue; - } + $totalCount = count($versions); + foreach ($versions as $index => $id) { + if (!$version = Version::getById($id)) { + $ignoredIds[] = $id; + $this->logger->debug('Version with ' . $id . " not found\n"); - $counter++; + continue; + } - // do not delete public versions - if ($version->getPublic()) { - $ignoredIds[] = $version->getId(); + $counter++; - continue; - } + // do not delete public versions + if ($version->getPublic()) { + $ignoredIds[] = $version->getId(); - // do not delete versions referenced in the scheduler - if ($dao->isVersionUsedInScheduler($version)) { - $ignoredIds[] = $version->getId(); + continue; + } - continue; - } + // do not delete versions referenced in the scheduler + if ($dao->isVersionUsedInScheduler($version)) { + $ignoredIds[] = $version->getId(); - $element = null; + continue; + } - if ($version->getCtype() === 'document') { - $element = Document::getById($version->getCid()); - } elseif ($version->getCtype() === 'asset') { - $element = Asset::getById($version->getCid()); - } elseif ($version->getCtype() === 'object') { - $element = DataObject::getById($version->getCid()); - } + $element = null; - if ($element instanceof Element\ElementInterface) { - $this->logger->debug('currently checking Element-ID: ' . $element->getId() . ' Element-Type: ' . Element\Service::getElementType($element) . ' in cycle: ' . $counter . '/' . $totalCount); - - if ($element->getModificationDate() >= $version->getDate()) { - // delete version if it is outdated - $this->logger->debug('delete version: ' . $version->getId() . ' because it is outdated'); - $version->delete(); - } else { - $ignoredIds[] = $version->getId(); - $this->logger->debug('do not delete version (' . $version->getId() . ") because version's date is newer than the actual modification date of the element. Element-ID: " . $element->getId() . ' Element-Type: ' . Element\Service::getElementType($element)); - } - } else { - // delete version if the corresponding element doesn't exist anymore - $this->logger->debug('delete version (' . $version->getId() . ") because the corresponding element doesn't exist anymore"); + if ($version->getCtype() === 'document') { + $element = Document::getById($version->getCid()); + } elseif ($version->getCtype() === 'asset') { + $element = Asset::getById($version->getCid()); + } elseif ($version->getCtype() === 'object') { + $element = DataObject::getById($version->getCid()); + } + + if ($element instanceof Element\ElementInterface) { + $this->logger->debug('currently checking Element-ID: ' . $element->getId() . ' Element-Type: ' . Element\Service::getElementType($element) . ' in cycle: ' . $counter . '/' . $totalCount); + + if ($element->getModificationDate() >= $version->getDate()) { + // delete version if it is outdated + $this->logger->debug('delete version: ' . $version->getId() . ' because it is outdated'); $version->delete(); + } else { + $ignoredIds[] = $version->getId(); + $this->logger->debug('do not delete version (' . $version->getId() . ") because version's date is newer than the actual modification date of the element. Element-ID: " . $element->getId() . ' Element-Type: ' . Element\Service::getElementType($element)); } + } else { + // delete version if the corresponding element doesn't exist anymore + $this->logger->debug('delete version (' . $version->getId() . ") because the corresponding element doesn't exist anymore"); + $version->delete(); + } - // call the garbage collector if memory consumption is > 100MB - if (memory_get_usage() > 100000000) { - \Pimcore::collectGarbage(); - } + // call the garbage collector if memory consumption is > 100MB + if (memory_get_usage() > 100000000) { + \Pimcore::collectGarbage(); } } } diff --git a/lib/Model/AbstractModel.php b/lib/Model/AbstractModel.php index ff8c3e26064..e19678679e4 100644 --- a/lib/Model/AbstractModel.php +++ b/lib/Model/AbstractModel.php @@ -166,10 +166,8 @@ public static function locateDaoClass(string $modelClass): ?string */ public function setValues(array $data = [], bool $ignoreEmptyValues = false): static { - if (is_array($data) && count($data) > 0) { - foreach ($data as $key => $value) { - $this->setValue($key, $value, $ignoreEmptyValues); - } + foreach ($data as $key => $value) { + $this->setValue($key, $value, $ignoreEmptyValues); } return $this; diff --git a/lib/Model/Listing/Dao/AbstractDao.php b/lib/Model/Listing/Dao/AbstractDao.php index b99c3e6dc91..fe3d17c511a 100644 --- a/lib/Model/Listing/Dao/AbstractDao.php +++ b/lib/Model/Listing/Dao/AbstractDao.php @@ -39,16 +39,14 @@ protected function getOrder(): string $lastOrder = $order[0] ?? null; $parts = []; - if (is_array($orderKey)) { - foreach ($orderKey as $key) { - if (isset($order[$c])) { - $lastOrder = $order[$c]; - } + foreach ($orderKey as $key) { + if (isset($order[$c])) { + $lastOrder = $order[$c]; + } - $parts[] = $key . ' ' . $lastOrder; + $parts[] = $key . ' ' . $lastOrder; - $c++; - } + $c++; } if (!empty($parts)) { diff --git a/lib/Model/Listing/Dao/QueryBuilderHelperTrait.php b/lib/Model/Listing/Dao/QueryBuilderHelperTrait.php index a7ba3192522..11d05b4ee54 100644 --- a/lib/Model/Listing/Dao/QueryBuilderHelperTrait.php +++ b/lib/Model/Listing/Dao/QueryBuilderHelperTrait.php @@ -101,16 +101,14 @@ private function applyOrderByToQueryBuilder(QueryBuilder $queryBuilder): void $c = 0; $lastOrder = $order[0] ?? null; - if (is_array($orderKey)) { - foreach ($orderKey as $key) { - if (!empty($order[$c])) { - $lastOrder = $order[$c]; - } + foreach ($orderKey as $key) { + if (!empty($order[$c])) { + $lastOrder = $order[$c]; + } - $parts[] = $key . ' ' . $lastOrder; + $parts[] = $key . ' ' . $lastOrder; - $c++; - } + $c++; } if (!empty($parts)) { diff --git a/lib/Navigation/Builder.php b/lib/Navigation/Builder.php index bf04d912fc5..c51f5849a51 100644 --- a/lib/Navigation/Builder.php +++ b/lib/Navigation/Builder.php @@ -341,10 +341,6 @@ protected function buildNextLevel(Document $parentDocument, bool $isRoot = false $children = $this->getChildren($parentDocument); $parents[$parentDocument->getId()] = $parentDocument; - if (!is_array($children)) { - return $pages; - } - foreach ($children as $child) { $classes = ''; diff --git a/lib/Navigation/Container.php b/lib/Navigation/Container.php index b811b5f5f5f..45c61dccdd3 100644 --- a/lib/Navigation/Container.php +++ b/lib/Navigation/Container.php @@ -191,13 +191,11 @@ public function removePage(Page|int $page, bool $recursive = false): bool { if ($page instanceof Page) { $hash = $page->hashCode(); - } elseif (is_int($page)) { + } else { $this->_sort(); if (!$hash = array_search($page, $this->_index)) { return false; } - } else { - return false; } if (isset($this->_pages[$hash])) { diff --git a/lib/Navigation/Page.php b/lib/Navigation/Page.php index 31abfa2fb9b..a36dcd7e0b2 100644 --- a/lib/Navigation/Page.php +++ b/lib/Navigation/Page.php @@ -165,10 +165,6 @@ abstract class Page extends Container */ public static function factory(array $options): Url|Page { - if (!is_array($options)) { - throw new \Exception('Invalid argument: $options must be an array'); - } - if (isset($options['type'])) { $type = $options['type']; } elseif (self::getDefaultPageType() != null) { @@ -970,9 +966,7 @@ public function __toString(): string */ public function addRel(string $relation, mixed $value): static { - if (is_string($relation)) { - $this->_rel[$relation] = $value; - } + $this->_rel[$relation] = $value; return $this; } @@ -988,9 +982,7 @@ public function addRel(string $relation, mixed $value): static */ public function addRev(string $relation, mixed $value): static { - if (is_string($relation)) { - $this->_rev[$relation] = $value; - } + $this->_rev[$relation] = $value; return $this; } @@ -1004,9 +996,7 @@ public function addRev(string $relation, mixed $value): static */ public function removeRel(string $relation): static { - if (isset($this->_rel[$relation])) { - unset($this->_rel[$relation]); - } + unset($this->_rel[$relation]); return $this; } diff --git a/lib/Navigation/Renderer/AbstractRenderer.php b/lib/Navigation/Renderer/AbstractRenderer.php index ee8f242260a..e69005aeee4 100644 --- a/lib/Navigation/Renderer/AbstractRenderer.php +++ b/lib/Navigation/Renderer/AbstractRenderer.php @@ -128,6 +128,9 @@ public function getMaxDepth(): ?int return $this->_maxDepth; } + /** + * @return $this + */ public function setIndent(string $indent): static { $this->_indent = $this->_getWhitespace($indent); @@ -145,11 +148,12 @@ public function getEOL(): string return "\n"; } + /** + * @return $this + */ public function setPrefixForId(string $prefix): static { - if (is_string($prefix)) { - $this->_prefixForId = trim($prefix); - } + $this->_prefixForId = trim($prefix); return $this; } @@ -166,6 +170,9 @@ public function getPrefixForId(): ?string return $this->_prefixForId; } + /** + * @return $this + */ public function skipPrefixForId(bool $flag = true): static { $this->_skipPrefixForId = $flag; @@ -178,6 +185,9 @@ public function getRenderInvisible(): bool return $this->_renderInvisible; } + /** + * @return $this + */ public function setRenderInvisible(bool $renderInvisible = true): static { $this->_renderInvisible = $renderInvisible; @@ -220,7 +230,7 @@ public function findActive(Container $container, int $minDepth = null, int $maxD } } - if (is_int($maxDepth) && $foundDepth > $maxDepth) { + if ($foundDepth > $maxDepth) { while ($foundDepth > $maxDepth) { if (--$foundDepth < $minDepth) { $found = null; diff --git a/lib/Navigation/Renderer/Breadcrumbs.php b/lib/Navigation/Renderer/Breadcrumbs.php index 5b85999af69..4903c963b63 100644 --- a/lib/Navigation/Renderer/Breadcrumbs.php +++ b/lib/Navigation/Renderer/Breadcrumbs.php @@ -82,13 +82,14 @@ public function getSeparator(): string public function setSeparator(string $separator): static { - if (is_string($separator)) { - $this->_separator = $separator; - } + $this->_separator = $separator; return $this; } + /** + * @return $this + */ public function setLinkLast(bool $linkLast): static { $this->_linkLast = $linkLast; diff --git a/lib/Navigation/Renderer/Menu.php b/lib/Navigation/Renderer/Menu.php index a91f5405a6e..cb13220ac7f 100644 --- a/lib/Navigation/Renderer/Menu.php +++ b/lib/Navigation/Renderer/Menu.php @@ -121,9 +121,7 @@ class Menu extends AbstractRenderer */ public function setUlClass(string $ulClass): static { - if (is_string($ulClass)) { - $this->_ulClass = $ulClass; - } + $this->_ulClass = $ulClass; return $this; } @@ -175,9 +173,7 @@ public function getUlId(): ?string */ public function setActiveClass(string $activeClass): static { - if (is_string($activeClass)) { - $this->_activeClass = $activeClass; - } + $this->_activeClass = $activeClass; return $this; } @@ -201,9 +197,7 @@ public function getActiveClass(): string */ public function setParentClass(string $parentClass): static { - if (is_string($parentClass)) { - $this->_parentClass = $parentClass; - } + $this->_parentClass = $parentClass; return $this; } diff --git a/lib/Templating/Renderer/IncludeRenderer.php b/lib/Templating/Renderer/IncludeRenderer.php index ea1abd8d03e..8eb556161fb 100644 --- a/lib/Templating/Renderer/IncludeRenderer.php +++ b/lib/Templating/Renderer/IncludeRenderer.php @@ -45,10 +45,6 @@ public function __construct( */ public function render(mixed $include, array $params = [], bool $editmode = false, bool $cacheEnabled = true): string { - if (!is_array($params)) { - $params = []; - } - $originalInclude = $include; // this is if $this->inc is called eg. with $this->relation() as argument diff --git a/lib/Tool.php b/lib/Tool.php index 74f5f1747e6..e93eb14b85b 100644 --- a/lib/Tool.php +++ b/lib/Tool.php @@ -441,7 +441,7 @@ public static function getHttpData(string $url, array $paramsGet = [], array $pa $options['timeout'] = 5; } - if (is_array($paramsGet) && count($paramsGet) > 0) { + if (count($paramsGet) > 0) { //need to insert get params from url to $paramsGet because otherwise they would be ignored $urlParts = parse_url($url); @@ -458,7 +458,7 @@ public static function getHttpData(string $url, array $paramsGet = [], array $pa $options[RequestOptions::QUERY] = $paramsGet; } - if (is_array($paramsPost) && count($paramsPost) > 0) { + if (count($paramsPost) > 0) { $options[RequestOptions::FORM_PARAMS] = $paramsPost; $requestType = 'POST'; } diff --git a/lib/Tool/Serialize.php b/lib/Tool/Serialize.php index a23aed29c67..228f3d32075 100644 --- a/lib/Tool/Serialize.php +++ b/lib/Tool/Serialize.php @@ -27,7 +27,7 @@ public static function serialize(mixed $data): string public static function unserialize(?string $data = null): mixed { - if (!empty($data) && is_string($data)) { + if ($data) { $data = unserialize($data); } diff --git a/lib/Tool/Text.php b/lib/Tool/Text.php index 29fe35e7007..5082b2b565d 100644 --- a/lib/Tool/Text.php +++ b/lib/Tool/Text.php @@ -181,7 +181,7 @@ public static function wysiwygText(?string $text, array $params = []): ?string private static function getElementsTagsInWysiwyg(string $text): array { - if (!is_string($text) || strlen($text) < 1) { + if (strlen($text) < 1) { return []; } diff --git a/lib/Twig/Extension/Templating/HeadScript.php b/lib/Twig/Extension/Templating/HeadScript.php index 40998e216d0..8cfd3bcedec 100644 --- a/lib/Twig/Extension/Templating/HeadScript.php +++ b/lib/Twig/Extension/Templating/HeadScript.php @@ -160,21 +160,13 @@ public function __construct( */ public function __invoke(string $mode = self::FILE, string $spec = null, string $placement = 'APPEND', array $attrs = [], string $type = 'text/javascript'): static { - if ((null !== $spec) && is_string($spec)) { + if (is_string($spec)) { $action = ucfirst(strtolower($mode)); $placement = strtolower($placement); - switch ($placement) { - case 'set': - case 'prepend': - case 'append': - $action = $placement . $action; - - break; - default: - $action = 'append' . $action; - - break; - } + $action = match ($placement) { + 'set', 'prepend', 'append' => $placement . $action, + default => 'append' . $action, + }; $this->$action($spec, $type, $attrs); } diff --git a/lib/Twig/Extension/Templating/HeadStyle.php b/lib/Twig/Extension/Templating/HeadStyle.php index f866f68a6b0..1e13da1a23b 100644 --- a/lib/Twig/Extension/Templating/HeadStyle.php +++ b/lib/Twig/Extension/Templating/HeadStyle.php @@ -118,22 +118,12 @@ public function __construct(ContainerService $containerService) */ public function __invoke(string $content = null, string $placement = 'APPEND', array|string $attributes = []): static { - if ((null !== $content) && is_string($content)) { - switch (strtoupper($placement)) { - case 'SET': - $action = 'setStyle'; - - break; - case 'PREPEND': - $action = 'prependStyle'; - - break; - case 'APPEND': - default: - $action = 'appendStyle'; - - break; - } + if (is_string($content)) { + $action = match (strtoupper($placement)) { + 'SET' => 'setStyle', + 'PREPEND' => 'prependStyle', + default => 'appendStyle', + }; $this->$action($content, $attributes); } diff --git a/lib/Twig/Extension/Templating/PimcoreUrl.php b/lib/Twig/Extension/Templating/PimcoreUrl.php index 140ec7f4886..a06b59954a9 100644 --- a/lib/Twig/Extension/Templating/PimcoreUrl.php +++ b/lib/Twig/Extension/Templating/PimcoreUrl.php @@ -75,7 +75,6 @@ protected function generateUrl(array|string $name = null, ?array $parameters = [ $name = $this->getCurrentRoute(); } - /** @var Concrete | null $object */ $object = $parameters['object'] ?? null; $linkGenerator = null; diff --git a/lib/Workflow/Place/OptionsProvider.php b/lib/Workflow/Place/OptionsProvider.php index bbfe2b591d4..aafcf6ae0a3 100644 --- a/lib/Workflow/Place/OptionsProvider.php +++ b/lib/Workflow/Place/OptionsProvider.php @@ -77,9 +77,6 @@ public function getOptions(array $context, Data $fieldDefinition): array protected function generatePlaceLabel(PlaceConfig $placeConfig): string { - if (!method_exists($this->translator, 'getLocale')) { - return ''; - } // do not translate or format options when not in admin context if (empty($this->translator->getLocale())) { return $placeConfig->getLabel(); diff --git a/lib/Workflow/Service.php b/lib/Workflow/Service.php index df1856c50d5..a88e903b7ca 100644 --- a/lib/Workflow/Service.php +++ b/lib/Workflow/Service.php @@ -109,17 +109,15 @@ public static function createActionNote(Element\ElementInterface $element, strin $note->setDescription($description); $note->setUser($user ? $user->getId() : 0); - if (is_array($noteData)) { - foreach ($noteData as $row) { - if ($row['key'] === 'noteDate' && $row['type'] === 'date') { - /** - * @var \DateTime $date - */ - $date = $row['value']; - $note->setDate($date->getTimestamp()); - } else { - $note->addData($row['key'], $row['type'], $row['value']); - } + foreach ($noteData as $row) { + if ($row['key'] === 'noteDate' && $row['type'] === 'date') { + /** + * @var \DateTime $date + */ + $date = $row['value']; + $note->setDate($date->getTimestamp()); + } else { + $note->addData($row['key'], $row['type'], $row['value']); } } diff --git a/models/Asset.php b/models/Asset.php index 8a6c1c1fb2a..ee2a91c4b0b 100644 --- a/models/Asset.php +++ b/models/Asset.php @@ -369,10 +369,6 @@ private static function checkMaxPixels(string $localPath, array $data): void */ public static function getList(array $config = []): Listing { - if (!is_array($config)) { - throw new Exception('Unable to initiate list class - please provide valid configuration array'); - } - $listClass = Listing::class; /** @var Listing $list */ @@ -511,7 +507,7 @@ public function save(array $parameters = []): static } $additionalTags = []; - if (isset($updatedChildren) && is_array($updatedChildren)) { + if (isset($updatedChildren)) { foreach ($updatedChildren as $assetId) { $tag = 'asset_' . $assetId; $additionalTags[] = $tag; @@ -702,15 +698,13 @@ protected function update(array $params = []): void // save properties $this->getProperties(); $this->getDao()->deleteAllProperties(); - if (is_array($this->getProperties()) && count($this->getProperties()) > 0) { - foreach ($this->getProperties() as $property) { - if (!$property->getInherited()) { - $property->setDao(null); - $property->setCid($this->getId()); - $property->setCtype('asset'); - $property->setCpath($this->getRealFullPath()); - $property->save(); - } + foreach ($this->getProperties() as $property) { + if (!$property->getInherited()) { + $property->setDao(null); + $property->setCid($this->getId()); + $property->setCtype('asset'); + $property->setCpath($this->getRealFullPath()); + $property->save(); } } @@ -1189,6 +1183,9 @@ public function getLocalFile(): string return self::getLocalFileFromStream($this->getStream()); } + /** + * @return $this + */ public function setCustomSetting(string $key, mixed $value): static { $this->customSettings[$key] = $value; @@ -1198,18 +1195,12 @@ public function setCustomSetting(string $key, mixed $value): static public function getCustomSetting(string $key): mixed { - if (is_array($this->customSettings) && array_key_exists($key, $this->customSettings)) { - return $this->customSettings[$key]; - } - - return null; + return $this->customSettings[$key] ?? null; } public function removeCustomSetting(string $key): void { - if (is_array($this->customSettings) && array_key_exists($key, $this->customSettings)) { - unset($this->customSettings[$key]); - } + unset($this->customSettings[$key]); } public function getCustomSettings(): array @@ -1217,6 +1208,9 @@ public function getCustomSettings(): array return $this->customSettings; } + /** + * @return $this + */ public function setCustomSettings(mixed $customSettings): static { if (is_string($customSettings)) { @@ -1293,6 +1287,9 @@ public function getHasMetaData(): bool return $this->hasMetaData; } + /** + * @return $this + */ public function setHasMetaData(bool $hasMetaData): static { $this->hasMetaData = $hasMetaData; @@ -1311,9 +1308,6 @@ public function addMetadata(string $name, string $type, mixed $data = null, stri if ($name && $type) { $tmp = []; $name = str_replace('~', '---', $name); - if (!is_array($this->metadata)) { - $this->metadata = []; - } foreach ($this->metadata as $item) { if ($item['name'] != $name || $language != $item['language']) { @@ -1347,14 +1341,14 @@ public function addMetadata(string $name, string $type, mixed $data = null, stri return $this; } + /** + * @return $this + */ public function removeMetadata(string $name, ?string $language = null): static { if ($name) { $tmp = []; $name = str_replace('~', '---', $name); - if (!is_array($this->metadata)) { - $this->metadata = []; - } foreach ($this->metadata as $item) { if ($item['name'] === $name && ($language == $item['language'] || $language === '*')) { diff --git a/models/Asset/Dao.php b/models/Asset/Dao.php index 6008615e85f..f679b0fd936 100644 --- a/models/Asset/Dao.php +++ b/models/Asset/Dao.php @@ -490,9 +490,9 @@ public function isAllowed(string $type, User $user): bool } /** + * @param string[] $columns * * @return array - * */ public function areAllowed(array $columns, User $user): array { diff --git a/models/Asset/Image/Thumbnail/Config.php b/models/Asset/Image/Thumbnail/Config.php index 453f4614880..1afac12dda7 100644 --- a/models/Asset/Image/Thumbnail/Config.php +++ b/models/Asset/Image/Thumbnail/Config.php @@ -349,6 +349,9 @@ public function selectMedia(string $name): bool return false; } + /** + * @return $this + */ public function setDescription(string $description): static { $this->description = $description; @@ -361,6 +364,9 @@ public function getDescription(): string return $this->description; } + /** + * @return $this + */ public function setItems(array $items): static { $this->items = $items; @@ -373,6 +379,9 @@ public function getItems(): array return $this->items; } + /** + * @return $this + */ public function setName(string $name): static { $this->name = $name; @@ -385,6 +394,9 @@ public function getName(): string return $this->name; } + /** + * @return $this + */ public function setFormat(string $format): static { $this->format = $format; @@ -397,6 +409,9 @@ public function getFormat(): string return $this->format; } + /** + * @return $this + */ public function setQuality(int $quality): static { if ($quality) { @@ -575,70 +590,68 @@ public function getEstimatedDimensions(Model\Asset\Image $asset): array ]; $transformations = $this->getItems(); - if (is_array($transformations) && count($transformations) > 0) { - if ($originalWidth && $originalHeight) { - foreach ($transformations as $transformation) { - if (!empty($transformation)) { - $arg = $transformation['arguments']; - - $forceResize = false; - if (isset($arg['forceResize']) && $arg['forceResize'] === true) { - $forceResize = true; - } + if ($originalWidth && $originalHeight) { + foreach ($transformations as $transformation) { + if (!empty($transformation)) { + $arg = $transformation['arguments']; + + $forceResize = false; + if (isset($arg['forceResize']) && $arg['forceResize'] === true) { + $forceResize = true; + } - if (in_array($transformation['method'], ['resize', 'cover', 'frame', 'crop'])) { + if (in_array($transformation['method'], ['resize', 'cover', 'frame', 'crop'])) { + $dimensions['width'] = $arg['width']; + $dimensions['height'] = $arg['height']; + } elseif ($transformation['method'] == '1x1_pixel') { + return [ + 'width' => 1, + 'height' => 1, + ]; + } elseif ($transformation['method'] == 'scaleByWidth') { + if ($arg['width'] <= $dimensions['width'] || $asset->isVectorGraphic() || $forceResize) { + $dimensions['height'] = round(($arg['width'] / $dimensions['width']) * $dimensions['height'], 0); $dimensions['width'] = $arg['width']; + } + } elseif ($transformation['method'] == 'scaleByHeight') { + if ($arg['height'] < $dimensions['height'] || $asset->isVectorGraphic() || $forceResize) { + $dimensions['width'] = round(($arg['height'] / $dimensions['height']) * $dimensions['width'], 0); $dimensions['height'] = $arg['height']; - } elseif ($transformation['method'] == '1x1_pixel') { - return [ - 'width' => 1, - 'height' => 1, - ]; - } elseif ($transformation['method'] == 'scaleByWidth') { - if ($arg['width'] <= $dimensions['width'] || $asset->isVectorGraphic() || $forceResize) { - $dimensions['height'] = round(($arg['width'] / $dimensions['width']) * $dimensions['height'], 0); - $dimensions['width'] = $arg['width']; - } - } elseif ($transformation['method'] == 'scaleByHeight') { - if ($arg['height'] < $dimensions['height'] || $asset->isVectorGraphic() || $forceResize) { - $dimensions['width'] = round(($arg['height'] / $dimensions['height']) * $dimensions['width'], 0); - $dimensions['height'] = $arg['height']; - } - } elseif ($transformation['method'] == 'contain') { - $x = $dimensions['width'] / $arg['width']; - $y = $dimensions['height'] / $arg['height']; + } + } elseif ($transformation['method'] == 'contain') { + $x = $dimensions['width'] / $arg['width']; + $y = $dimensions['height'] / $arg['height']; - if (!$forceResize && $x <= 1 && $y <= 1 && !$asset->isVectorGraphic()) { - continue; - } + if (!$forceResize && $x <= 1 && $y <= 1 && !$asset->isVectorGraphic()) { + continue; + } - if ($x > $y) { - $dimensions['height'] = round(($arg['width'] / $dimensions['width']) * $dimensions['height'], 0); - $dimensions['width'] = $arg['width']; - } else { - $dimensions['width'] = round(($arg['height'] / $dimensions['height']) * $dimensions['width'], 0); - $dimensions['height'] = $arg['height']; - } - } elseif ($transformation['method'] == 'cropPercent') { - $dimensions['width'] = ceil($dimensions['width'] * ($arg['width'] / 100)); - $dimensions['height'] = ceil($dimensions['height'] * ($arg['height'] / 100)); - } elseif (in_array($transformation['method'], ['rotate', 'trim'])) { - // unable to calculate dimensions -> return empty - return []; + if ($x > $y) { + $dimensions['height'] = round(($arg['width'] / $dimensions['width']) * $dimensions['height'], 0); + $dimensions['width'] = $arg['width']; + } else { + $dimensions['width'] = round(($arg['height'] / $dimensions['height']) * $dimensions['width'], 0); + $dimensions['height'] = $arg['height']; } + } elseif ($transformation['method'] == 'cropPercent') { + $dimensions['width'] = ceil($dimensions['width'] * ($arg['width'] / 100)); + $dimensions['height'] = ceil($dimensions['height'] * ($arg['height'] / 100)); + } elseif (in_array($transformation['method'], ['rotate', 'trim'])) { + // unable to calculate dimensions -> return empty + return []; } } - } else { - // this method is only if we don't have the source dimensions - // this doesn't necessarily return both with & height - // and is only a very rough estimate, you should avoid falling back to this functionality - foreach ($transformations as $transformation) { - if (!empty($transformation)) { - if (is_array($transformation['arguments']) && in_array($transformation['method'], ['resize', 'scaleByWidth', 'scaleByHeight', 'cover', 'frame'])) { - foreach ($transformation['arguments'] as $key => $value) { - if ($key == 'width' || $key == 'height') { - $dimensions[$key] = $value; - } + } + } else { + // this method is only if we don't have the source dimensions + // this doesn't necessarily return both with & height + // and is only a very rough estimate, you should avoid falling back to this functionality + foreach ($transformations as $transformation) { + if (!empty($transformation)) { + if (is_array($transformation['arguments']) && in_array($transformation['method'], ['resize', 'scaleByWidth', 'scaleByHeight', 'cover', 'frame'])) { + foreach ($transformation['arguments'] as $key => $value) { + if ($key == 'width' || $key == 'height') { + $dimensions[$key] = $value; } } } diff --git a/models/Asset/Image/Thumbnail/Processor.php b/models/Asset/Image/Thumbnail/Processor.php index 4d704927f95..8f5b06b543e 100644 --- a/models/Asset/Image/Thumbnail/Processor.php +++ b/models/Asset/Image/Thumbnail/Processor.php @@ -317,7 +317,7 @@ public static function process(Asset $asset, Config $config, mixed $fileSystemPa } } - if (is_array($transformations) && count($transformations) > 0) { + if ($transformations) { $sourceImageWidth = PHP_INT_MAX; $sourceImageHeight = PHP_INT_MAX; if ($asset instanceof Asset\Image) { @@ -463,12 +463,10 @@ public static function process(Asset $asset, Config $config, mixed $fileSystemPa private static function containsTransformationType(Config $config, string $transformationType): bool { $transformations = $config->getItems(); - if (is_array($transformations) && count($transformations) > 0) { - foreach ($transformations as $transformation) { - if (!empty($transformation)) { - if ($transformation['method'] == $transformationType) { - return true; - } + foreach ($transformations as $transformation) { + if (!empty($transformation)) { + if ($transformation['method'] == $transformationType) { + return true; } } } diff --git a/models/Asset/Service.php b/models/Asset/Service.php index 1b0bdd68171..28b8186320c 100644 --- a/models/Asset/Service.php +++ b/models/Asset/Service.php @@ -376,10 +376,6 @@ public static function rewriteIds(Asset $asset, array $rewriteConfig): Asset */ public static function minimizeMetadata(array $metadata, string $mode): array { - if (!is_array($metadata)) { - return $metadata; - } - $result = []; foreach ($metadata as $item) { $loader = \Pimcore::getContainer()->get('pimcore.implementation_loader.asset.metadata.data'); @@ -411,10 +407,6 @@ public static function minimizeMetadata(array $metadata, string $mode): array */ public static function expandMetadataForEditmode(array $metadata): array { - if (!is_array($metadata)) { - return $metadata; - } - $result = []; foreach ($metadata as $item) { $loader = \Pimcore::getContainer()->get('pimcore.implementation_loader.asset.metadata.data'); diff --git a/models/Asset/Video/Thumbnail/Config.php b/models/Asset/Video/Thumbnail/Config.php index 4adb05536a4..2ab1decbcc2 100644 --- a/models/Asset/Video/Thumbnail/Config.php +++ b/models/Asset/Video/Thumbnail/Config.php @@ -328,14 +328,12 @@ public function getEstimatedDimensions(): array { $dimensions = []; $transformations = $this->getItems(); - if (is_array($transformations) && count($transformations) > 0) { - foreach ($transformations as $transformation) { - if (!empty($transformation)) { - if (is_array($transformation['arguments'])) { - foreach ($transformation['arguments'] as $key => $value) { - if ($key == 'width' || $key == 'height') { - $dimensions[$key] = $value; - } + foreach ($transformations as $transformation) { + if (!empty($transformation)) { + if (is_array($transformation['arguments'])) { + foreach ($transformation['arguments'] as $key => $value) { + if ($key == 'width' || $key == 'height') { + $dimensions[$key] = $value; } } } diff --git a/models/Asset/Video/Thumbnail/Processor.php b/models/Asset/Video/Thumbnail/Processor.php index 542b895490e..a2ba89a03da 100644 --- a/models/Asset/Video/Thumbnail/Processor.php +++ b/models/Asset/Video/Thumbnail/Processor.php @@ -230,9 +230,7 @@ public static function execute(string $processId): void } Storage::get('thumbnail')->writeStream($converter->getStorageFile(), $source); - if (is_resource($source)) { - fclose($source); - } + fclose($source); unlink($converter->getDestinationFile()); diff --git a/models/DataObject/AbstractObject.php b/models/DataObject/AbstractObject.php index 6edf6ff7ea6..044018a7295 100644 --- a/models/DataObject/AbstractObject.php +++ b/models/DataObject/AbstractObject.php @@ -312,19 +312,17 @@ public static function getList(array $config = []): Listing } } - if (is_array($config)) { - if (!empty($config['class'])) { - $className = ltrim($config['class'], '\\'); - } + if (!empty($config['class'])) { + $className = ltrim($config['class'], '\\'); + } - if ($className) { - $listClass = $className . '\\Listing'; - /** @var DataObject\Listing $list */ - $list = self::getModelFactory()->build($listClass); - $list->setValues($config); + if ($className) { + $listClass = $className . '\\Listing'; + /** @var DataObject\Listing $list */ + $list = self::getModelFactory()->build($listClass); + $list->setValues($config); - return $list; - } + return $list; } throw new \Exception('Unable to initiate list class - class not found or invalid configuration'); @@ -604,7 +602,7 @@ public function save(array $parameters = []): static } $additionalTags = []; - if (isset($updatedChildren) && is_array($updatedChildren)) { + if (isset($updatedChildren)) { foreach ($updatedChildren as $objectId) { $tag = 'object_' . $objectId; $additionalTags[] = $tag; @@ -709,15 +707,13 @@ protected function update(bool $isUpdate = null, array $params = []): void $this->getProperties(); $this->getDao()->deleteAllProperties(); - if (is_array($this->getProperties()) && count($this->getProperties()) > 0) { - foreach ($this->getProperties() as $property) { - if (!$property->getInherited()) { - $property->setDao(null); - $property->setCid($this->getId()); - $property->setCtype('object'); - $property->setCpath($this->getRealFullPath()); - $property->save(); - } + foreach ($this->getProperties() as $property) { + if (!$property->getInherited()) { + $property->setDao(null); + $property->setCid($this->getId()); + $property->setCtype('object'); + $property->setCpath($this->getRealFullPath()); + $property->save(); } } diff --git a/models/DataObject/AbstractObject/Dao.php b/models/DataObject/AbstractObject/Dao.php index ba71bb22168..37e78d0f102 100644 --- a/models/DataObject/AbstractObject/Dao.php +++ b/models/DataObject/AbstractObject/Dao.php @@ -535,9 +535,9 @@ public function isAllowed(string $type, User $user): bool } /** + * @param string[] $columns * * @return array - * */ public function areAllowed(array $columns, User $user): array { diff --git a/models/DataObject/ClassDefinition.php b/models/DataObject/ClassDefinition.php index d5b4216e00a..c17d056188f 100644 --- a/models/DataObject/ClassDefinition.php +++ b/models/DataObject/ClassDefinition.php @@ -527,12 +527,10 @@ public function delete(): void $modified = false; $classDefinitions = $brickDefinition->getClassDefinitions(); - if (is_array($classDefinitions)) { - foreach ($classDefinitions as $key => $classDefinition) { - if ($classDefinition['classname'] == $this->getId()) { - unset($classDefinitions[$key]); - $modified = true; - } + foreach ($classDefinitions as $key => $classDefinition) { + if ($classDefinition['classname'] == $this->getId()) { + unset($classDefinitions[$key]); + $modified = true; } } if ($modified) { @@ -932,9 +930,7 @@ public function getPropertyVisibility(): array */ public function setPropertyVisibility(array $propertyVisibility): static { - if (is_array($propertyVisibility)) { - $this->propertyVisibility = $propertyVisibility; - } + $this->propertyVisibility = $propertyVisibility; return $this; } diff --git a/models/DataObject/ClassDefinition/Dao.php b/models/DataObject/ClassDefinition/Dao.php index 59f2182ee19..8898b496320 100644 --- a/models/DataObject/ClassDefinition/Dao.php +++ b/models/DataObject/ClassDefinition/Dao.php @@ -158,41 +158,39 @@ public function update(): void DataObject\ClassDefinition\Service::updateTableDefinitions($this->tableDefinitions, [$objectTable, $objectDatastoreTable]); // add non existing columns in the table - if (is_array($this->model->getFieldDefinitions()) && count($this->model->getFieldDefinitions())) { - foreach ($this->model->getFieldDefinitions() as $key => $value) { - if ($value instanceof DataObject\ClassDefinition\Data\ResourcePersistenceAwareInterface - && $value instanceof DataObject\ClassDefinition\Data) { - // if a datafield requires more than one column in the datastore table => only for non-relation types - if (!$value->isRelationType()) { - if (is_array($value->getColumnType())) { - foreach ($value->getColumnType() as $fkey => $fvalue) { - $this->addModifyColumn($objectDatastoreTable, $key . '__' . $fkey, $fvalue, '', 'NULL'); - $protectedDatastoreColumns[] = $key . '__' . $fkey; - } - } elseif ($value->getColumnType()) { - $this->addModifyColumn($objectDatastoreTable, $key, $value->getColumnType(), '', 'NULL'); - $protectedDatastoreColumns[] = $key; + foreach ($this->model->getFieldDefinitions() as $key => $value) { + if ($value instanceof DataObject\ClassDefinition\Data\ResourcePersistenceAwareInterface + && $value instanceof DataObject\ClassDefinition\Data) { + // if a datafield requires more than one column in the datastore table => only for non-relation types + if (!$value->isRelationType()) { + if (is_array($value->getColumnType())) { + foreach ($value->getColumnType() as $fkey => $fvalue) { + $this->addModifyColumn($objectDatastoreTable, $key . '__' . $fkey, $fvalue, '', 'NULL'); + $protectedDatastoreColumns[] = $key . '__' . $fkey; } + } elseif ($value->getColumnType()) { + $this->addModifyColumn($objectDatastoreTable, $key, $value->getColumnType(), '', 'NULL'); + $protectedDatastoreColumns[] = $key; } - - $this->addIndexToField($value, $objectDatastoreTable, 'getColumnType', true); } - if ($value instanceof DataObject\ClassDefinition\Data\QueryResourcePersistenceAwareInterface - && $value instanceof DataObject\ClassDefinition\Data) { - // if a datafield requires more than one column in the query table - if (is_array($value->getQueryColumnType())) { - foreach ($value->getQueryColumnType() as $fkey => $fvalue) { - $this->addModifyColumn($objectTable, $key . '__' . $fkey, $fvalue, '', 'NULL'); - $protectedColumns[] = $key . '__' . $fkey; - } - } elseif ($value->getQueryColumnType()) { - $this->addModifyColumn($objectTable, $key, $value->getQueryColumnType(), '', 'NULL'); - $protectedColumns[] = $key; - } + $this->addIndexToField($value, $objectDatastoreTable, 'getColumnType', true); + } - $this->addIndexToField($value, $objectTable, 'getQueryColumnType'); + if ($value instanceof DataObject\ClassDefinition\Data\QueryResourcePersistenceAwareInterface + && $value instanceof DataObject\ClassDefinition\Data) { + // if a datafield requires more than one column in the query table + if (is_array($value->getQueryColumnType())) { + foreach ($value->getQueryColumnType() as $fkey => $fvalue) { + $this->addModifyColumn($objectTable, $key . '__' . $fkey, $fvalue, '', 'NULL'); + $protectedColumns[] = $key . '__' . $fkey; + } + } elseif ($value->getQueryColumnType()) { + $this->addModifyColumn($objectTable, $key, $value->getQueryColumnType(), '', 'NULL'); + $protectedColumns[] = $key; } + + $this->addIndexToField($value, $objectTable, 'getQueryColumnType'); } } @@ -201,13 +199,11 @@ public function update(): void $this->removeUnusedColumns($objectDatastoreTable, $datastoreColumnsToRemove, $protectedDatastoreColumns); // remove / cleanup unused relations - if (is_array($datastoreColumnsToRemove)) { - foreach ($datastoreColumnsToRemove as $value) { - if (!in_array(strtolower($value), array_map('strtolower', $protectedDatastoreColumns))) { - $tableRelation = 'object_relations_' . $this->model->getId(); - $this->db->delete($tableRelation, ['fieldname' => $value, 'ownertype' => 'object']); - // @TODO: remove localized fields and fieldcollections - } + foreach ($datastoreColumnsToRemove as $value) { + if (!in_array(strtolower($value), array_map('strtolower', $protectedDatastoreColumns))) { + $tableRelation = 'object_relations_' . $this->model->getId(); + $this->db->delete($tableRelation, ['fieldname' => $value, 'ownertype' => 'object']); + // @TODO: remove localized fields and fieldcollections } } diff --git a/models/DataObject/ClassDefinition/Data/AdvancedManyToManyObjectRelation.php b/models/DataObject/ClassDefinition/Data/AdvancedManyToManyObjectRelation.php index 8f95dd280c3..bd261b9f610 100644 --- a/models/DataObject/ClassDefinition/Data/AdvancedManyToManyObjectRelation.php +++ b/models/DataObject/ClassDefinition/Data/AdvancedManyToManyObjectRelation.php @@ -42,6 +42,7 @@ class AdvancedManyToManyObjectRelation extends ManyToManyObjectRelation implemen /** * @internal * + * @var string[]|string|null */ public array|string|null $visibleFields = null; @@ -71,6 +72,7 @@ class AdvancedManyToManyObjectRelation extends ManyToManyObjectRelation implemen /** * @internal * + * @var array> */ public array $visibleFieldDefinitions = []; @@ -598,6 +600,9 @@ public function getVisibleFields(): array|string|null return $this->visibleFields; } + /** + * @return $this + */ public function setColumns(array $columns): static { if (isset($columns['key'])) { diff --git a/models/DataObject/ClassDefinition/Data/Block.php b/models/DataObject/ClassDefinition/Data/Block.php index 93e590977b9..ee4b099cd88 100644 --- a/models/DataObject/ClassDefinition/Data/Block.php +++ b/models/DataObject/ClassDefinition/Data/Block.php @@ -508,11 +508,7 @@ public function setChildren(array $children): static public function hasChildren(): bool { - if (is_array($this->children) && count($this->children) > 0) { - return true; - } - - return false; + return count($this->children) > 0; } /** @@ -921,13 +917,11 @@ public function classSaved(DataObject\ClassDefinition $class, array $params = [] { $blockDefinitions = $this->getFieldDefinitions(); - if (is_array($blockDefinitions)) { - foreach ($blockDefinitions as $field) { - if ($field instanceof LazyLoadingSupportInterface && $field->getLazyLoading()) { - // Lazy loading inside blocks isn't supported, turn it off if possible - if (method_exists($field, 'setLazyLoading')) { - $field->setLazyLoading(false); - } + foreach ($blockDefinitions as $field) { + if ($field instanceof LazyLoadingSupportInterface && $field->getLazyLoading()) { + // Lazy loading inside blocks isn't supported, turn it off if possible + if (method_exists($field, 'setLazyLoading')) { + $field->setLazyLoading(false); } } } diff --git a/models/DataObject/ClassDefinition/Data/BooleanSelect.php b/models/DataObject/ClassDefinition/Data/BooleanSelect.php index 4dc34c1b8da..50ff9c39d2c 100644 --- a/models/DataObject/ClassDefinition/Data/BooleanSelect.php +++ b/models/DataObject/ClassDefinition/Data/BooleanSelect.php @@ -96,6 +96,9 @@ public function getOptions(): array return $this->options; } + /** + * @return $this + */ public function setOptions(array $options): static { // nothing to do @@ -234,6 +237,9 @@ public function getYesLabel(): string return $this->yesLabel; } + /** + * @return $this + */ public function setYesLabel(?string $yesLabel): static { $this->yesLabel = $yesLabel; @@ -244,21 +250,12 @@ public function setYesLabel(?string $yesLabel): static public function setOptionsEntry(int $value, string $label): void { - if (!is_array($this->options)) { - $this->options = [ - [ - 'key' => $label, - 'value' => $value, - ], - ]; - } else { - foreach ($this->options as $idx => $option) { - if ($option['value'] == $value) { - $option['key'] = $label; - $this->options[$idx] = $option; + foreach ($this->options as $idx => $option) { + if ($option['value'] == $value) { + $option['key'] = $label; + $this->options[$idx] = $option; - break; - } + break; } } } @@ -268,6 +265,9 @@ public function getNoLabel(): string return $this->noLabel; } + /** + * @return $this + */ public function setNoLabel(string $noLabel): static { $this->noLabel = $noLabel; @@ -281,6 +281,9 @@ public function getEmptyLabel(): string return $this->emptyLabel; } + /** + * @return $this + */ public function setEmptyLabel(string $emptyLabel): static { $this->emptyLabel = $emptyLabel; diff --git a/models/DataObject/ClassDefinition/Data/Classificationstore.php b/models/DataObject/ClassDefinition/Data/Classificationstore.php index 9fe34fa2b1c..9b6da28234d 100644 --- a/models/DataObject/ClassDefinition/Data/Classificationstore.php +++ b/models/DataObject/ClassDefinition/Data/Classificationstore.php @@ -341,11 +341,9 @@ public function getDataFromEditmode(mixed $data, DataObject\Concrete $object = n // cleanup $existingGroupIds = $classificationStore->getGroupIdsWithData(); - if (is_array($existingGroupIds)) { - foreach ($existingGroupIds as $existingGroupId) { - if (!in_array($existingGroupId, $activeGroupIds)) { - $classificationStore->removeGroupData($existingGroupId); - } + foreach ($existingGroupIds as $existingGroupId) { + if (!in_array($existingGroupId, $activeGroupIds)) { + $classificationStore->removeGroupData($existingGroupId); } } @@ -436,11 +434,7 @@ public function setChildren(array $children): static public function hasChildren(): bool { - if (is_array($this->children) && count($this->children) > 0) { - return true; - } - - return false; + return count($this->children) > 0; } /** @@ -777,11 +771,9 @@ private function recursiveGetActiveGroupCollectionMapping(?Concrete $object, arr $classificationStore = $object->$getter(); $mapping = $classificationStore->getGroupCollectionMappings(); - if (is_array($mapping)) { - foreach ($mapping as $groupId => $collectionId) { - if (!isset($mergedMapping[$groupId]) && $collectionId) { - $mergedMapping[$groupId] = $collectionId; - } + foreach ($mapping as $groupId => $collectionId) { + if (!isset($mergedMapping[$groupId]) && $collectionId) { + $mergedMapping[$groupId] = $collectionId; } } diff --git a/models/DataObject/ClassDefinition/Data/EncryptedField.php b/models/DataObject/ClassDefinition/Data/EncryptedField.php index cf058821c8d..03f0d4818f8 100644 --- a/models/DataObject/ClassDefinition/Data/EncryptedField.php +++ b/models/DataObject/ClassDefinition/Data/EncryptedField.php @@ -287,10 +287,6 @@ public function getForCsvExport(DataObject\Localizedfield|DataObject\Fieldcollec if ($fd) { $data = $this->getDataFromObjectParam($object, $params); $data = $data instanceof Model\DataObject\Data\EncryptedField ? $data->getPlain() : null; - - if (is_array($params)) { - $params = []; - } $params['injectedData'] = $data; return $fd->getForCsvExport($object, $params); @@ -338,9 +334,7 @@ public function setupDelegate(mixed $data): void if ($loader->supports($this->getDelegateDatatype())) { $delegate = $loader->build($this->getDelegateDatatype()); $className = get_class($delegate); - if (method_exists($className, '__set_state')) { - $delegate = $className::__set_state($data); - } + $delegate = $className::__set_state($data); $this->delegate = $delegate; } } diff --git a/models/DataObject/ClassDefinition/Data/Extension/RelationFilterConditionParser.php b/models/DataObject/ClassDefinition/Data/Extension/RelationFilterConditionParser.php index 189241e203f..c19acd102ee 100644 --- a/models/DataObject/ClassDefinition/Data/Extension/RelationFilterConditionParser.php +++ b/models/DataObject/ClassDefinition/Data/Extension/RelationFilterConditionParser.php @@ -25,8 +25,6 @@ trait RelationFilterConditionParser { /** * Parses filter value of a relation field and creates the filter condition - * - * */ public function getRelationFilterCondition(?string $value, string $operator, string $name): string { @@ -38,13 +36,11 @@ public function getRelationFilterCondition(?string $value, string $operator, str return '`' . $name . '` = ' . "'" . $value . "'"; } $values = explode(',', $value); - if (is_array($values)) { - $fieldConditions = array_map(function ($value) use ($name) { - return '`' . $name . "` LIKE '%," . $value . ",%' "; - }, array_filter($values)); - if (!empty($fieldConditions)) { - $result = '(' . implode(' AND ', $fieldConditions) . ')'; - } + $fieldConditions = array_map(function ($value) use ($name) { + return '`' . $name . "` LIKE '%," . $value . ",%' "; + }, array_filter($values)); + if (!empty($fieldConditions)) { + $result = '(' . implode(' AND ', $fieldConditions) . ')'; } return $result; diff --git a/models/DataObject/ClassDefinition/Data/Fieldcollections.php b/models/DataObject/ClassDefinition/Data/Fieldcollections.php index 9a9064d2ff7..7e7a2d370bb 100644 --- a/models/DataObject/ClassDefinition/Data/Fieldcollections.php +++ b/models/DataObject/ClassDefinition/Data/Fieldcollections.php @@ -576,24 +576,22 @@ public function synchronizeWithMainDefinition(DataObject\ClassDefinition\Data $m */ public function classSaved(DataObject\ClassDefinition $class, array $params = []): void { - if (is_array($this->allowedTypes)) { - foreach ($this->allowedTypes as $i => $allowedType) { - if ($definition = DataObject\Fieldcollection\Definition::getByKey($allowedType)) { - $definition->getDao()->createUpdateTable($class); - $fieldDefinition = $definition->getFieldDefinitions(); - - foreach ($fieldDefinition as $fd) { - if ($fd instanceof ClassSavedInterface) { - // defer creation - $fd->classSaved($class, $params); - } + foreach ($this->allowedTypes as $i => $allowedType) { + if ($definition = DataObject\Fieldcollection\Definition::getByKey($allowedType)) { + $definition->getDao()->createUpdateTable($class); + $fieldDefinition = $definition->getFieldDefinitions(); + + foreach ($fieldDefinition as $fd) { + if ($fd instanceof ClassSavedInterface) { + // defer creation + $fd->classSaved($class, $params); } - - $definition->getDao()->classSaved($class); - } else { - Logger::warn("Removed unknown allowed type [ $allowedType ] from allowed types of field collection"); - unset($this->allowedTypes[$i]); } + + $definition->getDao()->classSaved($class); + } else { + Logger::warn("Removed unknown allowed type [ $allowedType ] from allowed types of field collection"); + unset($this->allowedTypes[$i]); } } } @@ -654,14 +652,12 @@ public function setCollapsible(bool $collapsible): void */ public static function collectCalculatedValueItems(array $container, array &$list = []): void { - if (is_array($container)) { - foreach ($container as $childDef) { - if ($childDef instanceof Model\DataObject\ClassDefinition\Data\CalculatedValue) { - $list[] = $childDef; - } else { - if (method_exists($childDef, 'getFieldDefinitions')) { - self::collectCalculatedValueItems($childDef->getFieldDefinitions(), $list); - } + foreach ($container as $childDef) { + if ($childDef instanceof Model\DataObject\ClassDefinition\Data\CalculatedValue) { + $list[] = $childDef; + } else { + if (method_exists($childDef, 'getFieldDefinitions')) { + self::collectCalculatedValueItems($childDef->getFieldDefinitions(), $list); } } } diff --git a/models/DataObject/ClassDefinition/Data/Localizedfields.php b/models/DataObject/ClassDefinition/Data/Localizedfields.php index fb1fa19d559..e9859eaf16b 100644 --- a/models/DataObject/ClassDefinition/Data/Localizedfields.php +++ b/models/DataObject/ClassDefinition/Data/Localizedfields.php @@ -371,7 +371,7 @@ public function setChildren(array $children): static public function hasChildren(): bool { - return is_array($this->children) && count($this->children) > 0; + return count($this->children) > 0; } /** @@ -993,30 +993,28 @@ public function normalize(mixed $value, array $params = []): ?array { if ($value instanceof DataObject\Localizedfield) { $items = $value->getInternalData(); - if (is_array($items)) { - $result = []; - foreach ($items as $language => $languageData) { - $languageResult = []; - foreach ($languageData as $elementName => $elementData) { - $fd = $this->getFieldDefinition($elementName); - if (!$fd) { - // class definition seems to have changed - Logger::warn('class definition seems to have changed, element name: '.$elementName); - - continue; - } + $result = []; + foreach ($items as $language => $languageData) { + $languageResult = []; + foreach ($languageData as $elementName => $elementData) { + $fd = $this->getFieldDefinition($elementName); + if (!$fd) { + // class definition seems to have changed + Logger::warn('class definition seems to have changed, element name: '.$elementName); - if ($fd instanceof NormalizerInterface) { - $dataForResource = $fd->normalize($elementData, $params); - $languageResult[$elementName] = $dataForResource; - } + continue; } - $result[$language] = $languageResult; + if ($fd instanceof NormalizerInterface) { + $dataForResource = $fd->normalize($elementData, $params); + $languageResult[$elementName] = $dataForResource; + } } - return $result; + $result[$language] = $languageResult; } + + return $result; } return null; diff --git a/models/DataObject/ClassDefinition/Data/ManyToManyObjectRelation.php b/models/DataObject/ClassDefinition/Data/ManyToManyObjectRelation.php index 7af8a8a2bc7..382221efa1c 100644 --- a/models/DataObject/ClassDefinition/Data/ManyToManyObjectRelation.php +++ b/models/DataObject/ClassDefinition/Data/ManyToManyObjectRelation.php @@ -47,6 +47,7 @@ class ManyToManyObjectRelation extends AbstractRelations implements QueryResourc /** * @internal * + * @var string[]|string|null */ public array|string|null $visibleFields = null; @@ -644,6 +645,11 @@ public function getDiffDataFromEditmode(array $data, DataObject\Concrete $object return null; } + /** + * @param string[]|string|null $visibleFields + * + * @return $this + */ public function setVisibleFields(array|string|null $visibleFields): static { if (is_array($visibleFields) && count($visibleFields)) { diff --git a/models/DataObject/ClassDefinition/Data/Objectbricks.php b/models/DataObject/ClassDefinition/Data/Objectbricks.php index 1320611843a..9718c14a10f 100644 --- a/models/DataObject/ClassDefinition/Data/Objectbricks.php +++ b/models/DataObject/ClassDefinition/Data/Objectbricks.php @@ -755,22 +755,20 @@ public function synchronizeWithMainDefinition(DataObject\ClassDefinition\Data $m */ public function classSaved(DataObject\ClassDefinition $class, array $params = []): void { - if (is_array($this->allowedTypes)) { - foreach ($this->allowedTypes as $allowedType) { - $definition = DataObject\Objectbrick\Definition::getByKey($allowedType); - if ($definition) { - $definition->getDao()->createUpdateTable($class); - $fieldDefinition = $definition->getFieldDefinitions(); - - foreach ($fieldDefinition as $fd) { - if ($fd instanceof ClassSavedInterface) { - // defer creation - $fd->classSaved($class, $params); - } + foreach ($this->allowedTypes as $allowedType) { + $definition = DataObject\Objectbrick\Definition::getByKey($allowedType); + if ($definition) { + $definition->getDao()->createUpdateTable($class); + $fieldDefinition = $definition->getFieldDefinitions(); + + foreach ($fieldDefinition as $fd) { + if ($fd instanceof ClassSavedInterface) { + // defer creation + $fd->classSaved($class, $params); } - - $definition->getDao()->classSaved($class); } + + $definition->getDao()->classSaved($class); } } } @@ -781,11 +779,9 @@ public function classSaved(DataObject\ClassDefinition $class, array $params = [] */ public static function collectCalculatedValueItems(array $container, array &$list = []): void { - if (is_array($container)) { - foreach ($container as $childDef) { - if ($childDef instanceof Model\DataObject\ClassDefinition\Data\CalculatedValue) { - $list[] = $childDef; - } + foreach ($container as $childDef) { + if ($childDef instanceof Model\DataObject\ClassDefinition\Data\CalculatedValue) { + $list[] = $childDef; } } } diff --git a/models/DataObject/ClassDefinition/Data/QuantityValueRange.php b/models/DataObject/ClassDefinition/Data/QuantityValueRange.php index 10d7853b113..c2620787975 100644 --- a/models/DataObject/ClassDefinition/Data/QuantityValueRange.php +++ b/models/DataObject/ClassDefinition/Data/QuantityValueRange.php @@ -303,7 +303,7 @@ public function checkValidity(mixed $data, bool $omitMandatoryCheck = false, arr $minimum = $data->getMinimum(); $maximum = $data->getMaximum(); - if ($minimum !== null && (!\is_numeric($minimum) || !\is_numeric($maximum))) { + if (!\is_numeric($minimum) || !\is_numeric($maximum)) { throw new ValidationException(sprintf('Invalid dimension unit data: %s', $fieldName)); } diff --git a/models/DataObject/ClassDefinition/Data/Relations/AbstractRelations.php b/models/DataObject/ClassDefinition/Data/Relations/AbstractRelations.php index 745a02aa353..be1b202111f 100644 --- a/models/DataObject/ClassDefinition/Data/Relations/AbstractRelations.php +++ b/models/DataObject/ClassDefinition/Data/Relations/AbstractRelations.php @@ -270,12 +270,10 @@ public function appendData(?array $existingData, array $additionalData): ?array $newData[] = $item; } - if (is_array($additionalData)) { - foreach ($additionalData as $item) { - $key = $this->buildUniqueKeyForAppending($item); - if (!isset($map[$key])) { - $newData[] = $item; - } + foreach ($additionalData as $item) { + $key = $this->buildUniqueKeyForAppending($item); + if (!isset($map[$key])) { + $newData[] = $item; } } diff --git a/models/DataObject/ClassDefinition/Data/UrlSlug.php b/models/DataObject/ClassDefinition/Data/UrlSlug.php index fa92694b0b4..9d9a22b9dc3 100644 --- a/models/DataObject/ClassDefinition/Data/UrlSlug.php +++ b/models/DataObject/ClassDefinition/Data/UrlSlug.php @@ -276,7 +276,7 @@ public function prepareDataForPersistence(mixed $data, Localizedfield|AbstractDa public function load(Localizedfield|AbstractData|\Pimcore\Model\DataObject\Objectbrick\Data\AbstractData|Concrete $object, array $params = []): array { - $rawResult = null; + $rawResult = []; if ($object instanceof Model\DataObject\Concrete) { $rawResult = $object->retrieveSlugData(['fieldname' => $this->getName(), 'ownertype' => 'object']); } elseif ($object instanceof Model\DataObject\Fieldcollection\Data\AbstractData) { @@ -300,11 +300,9 @@ public function load(Localizedfield|AbstractData|\Pimcore\Model\DataObject\Objec } $result = []; - if (is_array($rawResult)) { - foreach ($rawResult as $rawItem) { - $slug = Model\DataObject\Data\UrlSlug::createFromDataRow($rawItem); - $result[] = $slug; - } + foreach ($rawResult as $rawItem) { + $slug = Model\DataObject\Data\UrlSlug::createFromDataRow($rawItem); + $result[] = $slug; } return $result; diff --git a/models/DataObject/ClassDefinition/Data/User.php b/models/DataObject/ClassDefinition/Data/User.php index a9c3793ff08..a50cc20f758 100644 --- a/models/DataObject/ClassDefinition/Data/User.php +++ b/models/DataObject/ClassDefinition/Data/User.php @@ -94,20 +94,18 @@ public function configureOptions(): void $users = $list->load(); $options = []; - if (is_array($users) && count($users) > 0) { - foreach ($users as $user) { - if ($user instanceof Model\User) { - $value = $user->getName(); - $first = $user->getFirstname(); - $last = $user->getLastname(); - if (!empty($first) || !empty($last)) { - $value .= ' (' . $first . ' ' . $last . ')'; - } - $options[] = [ - 'value' => $user->getId(), - 'key' => $value, - ]; + foreach ($users as $user) { + if ($user instanceof Model\User) { + $value = $user->getName(); + $first = $user->getFirstname(); + $last = $user->getLastname(); + if (!empty($first) || !empty($last)) { + $value .= ' (' . $first . ' ' . $last . ')'; } + $options[] = [ + 'value' => $user->getId(), + 'key' => $value, + ]; } } $this->setOptions($options); diff --git a/models/DataObject/ClassDefinition/Data/Wysiwyg.php b/models/DataObject/ClassDefinition/Data/Wysiwyg.php index 52e5db90d79..55b7023cfbd 100644 --- a/models/DataObject/ClassDefinition/Data/Wysiwyg.php +++ b/models/DataObject/ClassDefinition/Data/Wysiwyg.php @@ -181,12 +181,10 @@ public function checkValidity(mixed $data, bool $omitMandatoryCheck = false, arr throw new Element\ValidationException('Empty mandatory field [ '.$this->getName().' ]'); } $dependencies = Text::getDependenciesOfWysiwygText($data); - if (is_array($dependencies)) { - foreach ($dependencies as $key => $value) { - $el = Element\Service::getElementById($value['type'], $value['id']); - if (!$el) { - throw new Element\ValidationException('Invalid dependency in wysiwyg text'); - } + foreach ($dependencies as $key => $value) { + $el = Element\Service::getElementById($value['type'], $value['id']); + if (!$el) { + throw new Element\ValidationException('Invalid dependency in wysiwyg text'); } } } diff --git a/models/DataObject/ClassDefinition/Helper/Dao.php b/models/DataObject/ClassDefinition/Helper/Dao.php index 88abad5aee2..16700420f6f 100644 --- a/models/DataObject/ClassDefinition/Helper/Dao.php +++ b/models/DataObject/ClassDefinition/Helper/Dao.php @@ -108,23 +108,28 @@ protected function addModifyColumn(string $table, string $colName, string $type, } } + /** + * @param string[] $columnsToRemove + * @param string[] $protectedColumns + */ protected function removeUnusedColumns(string $table, array $columnsToRemove, array $protectedColumns): void { - if (is_array($columnsToRemove) && count($columnsToRemove) > 0) { - $dropColumns = []; - foreach ($columnsToRemove as $value) { - //if (!in_array($value, $protectedColumns)) { - if (!in_array(strtolower($value), array_map('strtolower', $protectedColumns))) { - $dropColumns[] = 'DROP COLUMN `' . $value . '`'; - } - } - if ($dropColumns) { - $this->db->executeQuery('ALTER TABLE `' . $table . '` ' . implode(', ', $dropColumns) . ';'); - $this->resetValidTableColumnsCache($table); + $dropColumns = []; + foreach ($columnsToRemove as $value) { + //if (!in_array($value, $protectedColumns)) { + if (!in_array(strtolower($value), array_map('strtolower', $protectedColumns))) { + $dropColumns[] = 'DROP COLUMN `' . $value . '`'; } } + if ($dropColumns) { + $this->db->executeQuery('ALTER TABLE `' . $table . '` ' . implode(', ', $dropColumns) . ';'); + $this->resetValidTableColumnsCache($table); + } } + /** + * @param string[] $tables + */ protected function handleEncryption(DataObject\ClassDefinition $classDefinition, array $tables): void { if ($classDefinition->getEncryption()) { @@ -136,6 +141,9 @@ protected function handleEncryption(DataObject\ClassDefinition $classDefinition, } } + /** + * @param string[] $tables + */ protected function encryptTables(array $tables): void { foreach ($tables as $table) { @@ -143,6 +151,9 @@ protected function encryptTables(array $tables): void } } + /** + * @param string[] $tables + */ protected function decryptTables(DataObject\ClassDefinition $classDefinition, array $tables): void { foreach ($tables as $table) { @@ -152,9 +163,13 @@ protected function decryptTables(DataObject\ClassDefinition $classDefinition, ar } } + /** + * @param string[] $columnsToRemove + * @param string[] $protectedColumns + */ protected function removeIndices(string $table, array $columnsToRemove, array $protectedColumns): void { - if (is_array($columnsToRemove) && count($columnsToRemove) > 0) { + if ($columnsToRemove) { $lowerCaseColumns = array_map('strtolower', $protectedColumns); foreach ($columnsToRemove as $value) { if (!in_array(strtolower($value), $lowerCaseColumns)) { diff --git a/models/DataObject/ClassDefinition/Layout.php b/models/DataObject/ClassDefinition/Layout.php index d053300d3f1..714cf25ec4b 100644 --- a/models/DataObject/ClassDefinition/Layout.php +++ b/models/DataObject/ClassDefinition/Layout.php @@ -218,7 +218,7 @@ public function setChildren(array $children): static public function hasChildren(): bool { - if (is_array($this->children) && count($this->children) > 0) { + if (count($this->children) > 0) { return true; } diff --git a/models/DataObject/ClassDefinition/Service.php b/models/DataObject/ClassDefinition/Service.php index ea08718437b..376645db062 100644 --- a/models/DataObject/ClassDefinition/Service.php +++ b/models/DataObject/ClassDefinition/Service.php @@ -195,17 +195,15 @@ public static function generateObjectBrickJson(DataObject\Objectbrick\Definition // set classname attribute to the real class name not to the class ID // this will allow to import the brick on a different instance with identical class names but different class IDs - if (is_array($objectBrick->getClassDefinitions())) { - foreach ($objectBrick->getClassDefinitions() as &$cd) { - // for compatibility (upgraded pimcore4s that may deliver class ids in $cd['classname'] we need to - // get the class by id in order to be able to correctly set the classname for the generated json - if (!$class = DataObject\ClassDefinition::getByName($cd['classname'])) { - $class = DataObject\ClassDefinition::getById($cd['classname']); - } + foreach ($objectBrick->getClassDefinitions() as &$cd) { + // for compatibility (upgraded pimcore4s that may deliver class ids in $cd['classname'] we need to + // get the class by id in order to be able to correctly set the classname for the generated json + if (!$class = DataObject\ClassDefinition::getByName($cd['classname'])) { + $class = DataObject\ClassDefinition::getById($cd['classname']); + } - if ($class) { - $cd['classname'] = $class->getName(); - } + if ($class) { + $cd['classname'] = $class->getName(); } } @@ -293,7 +291,7 @@ public static function importObjectBrickFromJson(DataObject\Objectbrick\Definiti */ public static function generateLayoutTreeFromArray(array $array, bool $throwException = false, bool $insideLocalizedField = false): Data\EncryptedField|bool|Data|Layout { - if (is_array($array) && count($array) > 0) { + if ($array) { if ($title = $array['title'] ?? false) { if (preg_match('/<.+?>/', $title)) { throw new \Exception('not a valid title:' . htmlentities($title)); @@ -377,10 +375,6 @@ private static function removeDynamicOptionsFromArray(array &$data, array $block */ public static function updateTableDefinitions(array &$tableDefinitions, array $tableNames): void { - if (!is_array($tableDefinitions)) { - $tableDefinitions = []; - } - $db = \Pimcore\Db::get(); $tmp = []; foreach ($tableNames as $tableName) { @@ -463,10 +457,6 @@ public static function buildImplementsInterfacesCode(array $implementsParts, ?st */ public static function buildUseTraitsCode(array $useParts, ?string $newTraits): string { - if (!is_array($useParts)) { - $useParts = []; - } - if ($newTraits) { $customParts = explode(',', $newTraits); foreach ($customParts as $trait) { diff --git a/models/DataObject/Classificationstore/Dao.php b/models/DataObject/Classificationstore/Dao.php index 75ebea7e19d..706cd54f1a0 100644 --- a/models/DataObject/Classificationstore/Dao.php +++ b/models/DataObject/Classificationstore/Dao.php @@ -75,16 +75,14 @@ public function save(): void $this->db->delete($groupsTable, ['id' => $objectId, 'fieldname' => $fieldname]); } - if (is_array($activeGroups)) { - foreach ($activeGroups as $activeGroupId => $enabled) { - if ($enabled) { - $data = [ - 'id' => $objectId, - 'groupId' => $activeGroupId, - 'fieldname' => $fieldname, - ]; - Helper::upsert($this->db, $groupsTable, $data, $this->getPrimaryKey($groupsTable)); - } + foreach ($activeGroups as $activeGroupId => $enabled) { + if ($enabled) { + $data = [ + 'id' => $objectId, + 'groupId' => $activeGroupId, + 'fieldname' => $fieldname, + ]; + Helper::upsert($this->db, $groupsTable, $data, $this->getPrimaryKey($groupsTable)); } } diff --git a/models/DataObject/Classificationstore/Service.php b/models/DataObject/Classificationstore/Service.php index 69f43fd9916..d653f52bad7 100644 --- a/models/DataObject/Classificationstore/Service.php +++ b/models/DataObject/Classificationstore/Service.php @@ -85,9 +85,7 @@ public static function getFieldDefinitionFromJson(array $definition, string $typ $dataDefinition->setValues($definition); $className = get_class($dataDefinition); - if (method_exists($className, '__set_state')) { - $dataDefinition = $className::__set_state((array) $dataDefinition); - } + $dataDefinition = $className::__set_state((array) $dataDefinition); if ($dataDefinition instanceof DataObject\ClassDefinition\Data\EncryptedField) { $delegateDefinitionRaw = $dataDefinition->getDelegate(); diff --git a/models/DataObject/Concrete/Dao.php b/models/DataObject/Concrete/Dao.php index df46c8cc983..5d00f2aca6a 100644 --- a/models/DataObject/Concrete/Dao.php +++ b/models/DataObject/Concrete/Dao.php @@ -101,7 +101,7 @@ public function getRelationData(string $field, bool $forOwner, ?string $remoteCl $src = 'dest_id'; } - $relations = $this->db->fetchAllAssociative('SELECT r.' . $dest . ' as dest_id, r.' . $dest . ' as id, r.type, o.className as subtype, o.published as published, concat(o.path ,o.key) as `path` , r.index + return $this->db->fetchAllAssociative('SELECT r.' . $dest . ' as dest_id, r.' . $dest . ' as id, r.type, o.className as subtype, o.published as published, concat(o.path ,o.key) as `path` , r.index FROM objects o, object_relations_' . $classId . " r WHERE r.fieldname= ? AND r.ownertype = 'object' @@ -126,12 +126,6 @@ public function getRelationData(string $field, bool $forOwner, ?string $remoteCl AND r.type='document' ORDER BY `index` ASC", $params); - - if (is_array($relations) && count($relations) > 0) { - return $relations; - } else { - return []; - } } /** diff --git a/models/DataObject/Data/ElementMetadata.php b/models/DataObject/Data/ElementMetadata.php index 12f7eb5a0b2..7ffef2e054b 100644 --- a/models/DataObject/Data/ElementMetadata.php +++ b/models/DataObject/Data/ElementMetadata.php @@ -105,6 +105,9 @@ public function load(DataObject\Concrete $source, int $destinationId, string $fi return $return; } + /** + * @return $this + */ public function setFieldname(string $fieldname): static { $this->fieldname = $fieldname; @@ -118,6 +121,9 @@ public function getFieldname(): string return $this->fieldname; } + /** + * @return $this + */ public function setElement(?Model\Element\ElementInterface $element): static { $this->markMeDirty(); @@ -158,6 +164,9 @@ public function getElementId(): ?int return $this->elementId; } + /** + * @return $this + */ public function setColumns(array $columns): static { $this->columns = $columns; diff --git a/models/DataObject/Data/Hotspotimage.php b/models/DataObject/Data/Hotspotimage.php index 9722644e17c..3b7c9bba0cf 100644 --- a/models/DataObject/Data/Hotspotimage.php +++ b/models/DataObject/Data/Hotspotimage.php @@ -51,23 +51,17 @@ public function __construct(Asset\Image|int $image = null, array $hotspots = [], $this->image = Asset\Image::getById($image); } - if (is_array($hotspots)) { - $this->hotspots = []; - foreach ($hotspots as $h) { - $this->hotspots[] = $h; - } + $this->hotspots = []; + foreach ($hotspots as $h) { + $this->hotspots[] = $h; } - if (is_array($marker)) { - $this->marker = []; - foreach ($marker as $m) { - $this->marker[] = $m; - } + $this->marker = []; + foreach ($marker as $m) { + $this->marker[] = $m; } - if (is_array($crop)) { - $this->crop = $crop; - } + $this->crop = $crop; $this->markMeDirty(); } diff --git a/models/DataObject/Data/ImageGallery.php b/models/DataObject/Data/ImageGallery.php index a347ce47160..caf04d7574d 100644 --- a/models/DataObject/Data/ImageGallery.php +++ b/models/DataObject/Data/ImageGallery.php @@ -75,9 +75,6 @@ public function getItems(): array */ public function setItems(array $items): void { - if (!is_array($items)) { - $items = []; - } $this->items = $items; $this->rewind(); $this->markMeDirty(); diff --git a/models/DataObject/Data/Link.php b/models/DataObject/Data/Link.php index 216fa2bd3e9..3041ac3e740 100644 --- a/models/DataObject/Data/Link.php +++ b/models/DataObject/Data/Link.php @@ -64,6 +64,9 @@ public function getText(): string return $this->text; } + /** + * @return $this + */ public function setText(string $text): static { $this->text = $text; @@ -77,6 +80,9 @@ public function getInternalType(): ?string return $this->internalType; } + /** + * @return $this + */ public function setInternalType(?string $internalType): static { $this->internalType = $internalType; @@ -90,6 +96,9 @@ public function getInternal(): ?int return $this->internal; } + /** + * @return $this + */ public function setInternal(?int $internal): static { $this->internal = $internal; @@ -103,6 +112,9 @@ public function getDirect(): ?string return $this->direct; } + /** + * @return $this + */ public function setDirect(?string $direct): static { $this->direct = $direct; @@ -116,6 +128,9 @@ public function getLinktype(): ?string return $this->linktype; } + /** + * @return $this + */ public function setLinktype(?string $linktype): static { $this->linktype = $linktype; @@ -129,6 +144,9 @@ public function getTarget(): string return $this->target; } + /** + * @return $this + */ public function setTarget(string $target): static { $this->target = $target; @@ -142,6 +160,9 @@ public function getParameters(): string return $this->parameters; } + /** + * @return $this + */ public function setParameters(string $parameters): static { $this->parameters = $parameters; @@ -155,6 +176,9 @@ public function getAnchor(): string return $this->anchor; } + /** + * @return $this + */ public function setAnchor(string $anchor): static { $this->anchor = $anchor; @@ -168,6 +192,9 @@ public function getTitle(): string return $this->title; } + /** + * @return $this + */ public function setTitle(string $title): static { $this->title = $title; @@ -181,6 +208,9 @@ public function getAccesskey(): string return $this->accesskey; } + /** + * @return $this + */ public function setAccesskey(string $accesskey): static { $this->accesskey = $accesskey; @@ -194,6 +224,9 @@ public function getRel(): string return $this->rel; } + /** + * @return $this + */ public function setRel(string $rel): static { $this->rel = $rel; @@ -207,6 +240,9 @@ public function getTabindex(): string return $this->tabindex; } + /** + * @return $this + */ public function setTabindex(string $tabindex): static { $this->tabindex = $tabindex; @@ -237,6 +273,9 @@ public function getClass(): string return $this->class; } + /** + * @return $this + */ public function setPath(string $path): static { if (!empty($path)) { @@ -335,6 +374,9 @@ public function getElement(): DataObject|Asset|Document|null return $element; } + /** + * @return $this + */ public function setElement(ElementInterface $object): static { if ($object instanceof ElementInterface) { @@ -380,14 +422,15 @@ public function isEmpty(): bool return true; } + /** + * @return $this + */ public function setValues(array $data = []): static { - if (is_array($data) && count($data) > 0) { - foreach ($data as $key => $value) { - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } + foreach ($data as $key => $value) { + $method = 'set' . $key; + if (method_exists($this, $method)) { + $this->$method($value); } } $this->markMeDirty(); diff --git a/models/DataObject/Data/ObjectMetadata.php b/models/DataObject/Data/ObjectMetadata.php index af15bf3b473..9770009f9e5 100644 --- a/models/DataObject/Data/ObjectMetadata.php +++ b/models/DataObject/Data/ObjectMetadata.php @@ -48,6 +48,9 @@ public function __construct(?string $fieldname, array $columns = [], DataObject\ $this->setObject($object); } + /** + * @return $this + */ public function setObject(?DataObject\Concrete $object): static { $this->markMeDirty(); @@ -111,6 +114,9 @@ public function load(DataObject\Concrete $source, int $destinationId, string $fi return $return; } + /** + * @return $this + */ public function setFieldname(string $fieldname): static { $this->fieldname = $fieldname; @@ -138,6 +144,9 @@ public function getObject(): ?DataObject\Concrete return null; } + /** + * @return $this + */ public function setElement(DataObject\Concrete $element): static { $this->markMeDirty(); @@ -150,6 +159,9 @@ public function getElement(): ?DataObject\Concrete return $this->getObject(); } + /** + * @return $this + */ public function setColumns(array $columns): static { $this->columns = $columns; diff --git a/models/DataObject/Data/UrlSlug.php b/models/DataObject/Data/UrlSlug.php index 0e1018898e2..e5fd1fa920a 100644 --- a/models/DataObject/Data/UrlSlug.php +++ b/models/DataObject/Data/UrlSlug.php @@ -271,16 +271,14 @@ public function getAction(): string $objectFieldDef = $classDefinition->getFieldDefinition($objectFieldname); if ($objectFieldDef instanceof Objectbricks) { $allowedBricks = $objectFieldDef->getAllowedTypes(); - if (is_array($allowedBricks)) { - foreach ($allowedBricks as $allowedBrick) { - $brickDef = Definition::getByKey($allowedBrick); - if ($brickDef instanceof Definition) { - $lfDef = $brickDef->getFieldDefinition('localizedfields'); - if ($lfDef instanceof Localizedfields) { - $fd = $lfDef->getFieldDefinition($this->getFieldname()); - - break; - } + foreach ($allowedBricks as $allowedBrick) { + $brickDef = Definition::getByKey($allowedBrick); + if ($brickDef instanceof Definition) { + $lfDef = $brickDef->getFieldDefinition('localizedfields'); + if ($lfDef instanceof Localizedfields) { + $fd = $lfDef->getFieldDefinition($this->getFieldname()); + + break; } } } diff --git a/models/DataObject/Fieldcollection.php b/models/DataObject/Fieldcollection.php index c6b911582b5..0a849158ac7 100644 --- a/models/DataObject/Fieldcollection.php +++ b/models/DataObject/Fieldcollection.php @@ -122,21 +122,19 @@ public function save(Concrete $object, array $params = []): void $allowedTypes = $fieldDef->getAllowedTypes(); $collectionItems = $this->getItems(); - if (is_array($collectionItems)) { - $index = 0; - foreach ($collectionItems as $collection) { - if ($collection instanceof Fieldcollection\Data\AbstractData) { - if (in_array($collection->getType(), $allowedTypes)) { - $collection->setFieldname($this->getFieldname()); - $collection->setIndex($index++); - $params['owner'] = $collection; - - // set the current object again, this is necessary because the related object in $this->object can change (eg. clone & copy & paste, etc.) - $collection->setObject($object); - $collection->getDao()->save($object, $params, $saveRelationalData); - } else { - throw new \Exception('Fieldcollection of type ' . $collection->getType() . ' is not allowed in field: ' . $this->getFieldname()); - } + $index = 0; + foreach ($collectionItems as $collection) { + if ($collection instanceof Fieldcollection\Data\AbstractData) { + if (in_array($collection->getType(), $allowedTypes)) { + $collection->setFieldname($this->getFieldname()); + $collection->setIndex($index++); + $params['owner'] = $collection; + + // set the current object again, this is necessary because the related object in $this->object can change (eg. clone & copy & paste, etc.) + $collection->setObject($object); + $collection->getDao()->save($object, $params, $saveRelationalData); + } else { + throw new \Exception('Fieldcollection of type ' . $collection->getType() . ' is not allowed in field: ' . $this->getFieldname()); } } } @@ -180,11 +178,9 @@ private function getByOriginalIndex(?int $index): ?Fieldcollection\Data\Abstract return null; } - if (is_array($this->items)) { - foreach ($this->items as $item) { - if ($item->getIndex() === $index) { - return $item; - } + foreach ($this->items as $item) { + if ($item->getIndex() === $index) { + return $item; } } @@ -277,11 +273,9 @@ protected function getObject(): ?Concrete public function setObject(?Concrete $object): static { // update all items with the new $object - if (is_array($this->getItems())) { - foreach ($this->getItems() as $item) { - if ($item instanceof Model\DataObject\Fieldcollection\Data\AbstractData) { - $item->setObject($object); - } + foreach ($this->getItems() as $item) { + if ($item instanceof Model\DataObject\Fieldcollection\Data\AbstractData) { + $item->setObject($object); } } @@ -294,18 +288,16 @@ public function setObject(?Concrete $object): static public function loadLazyData(): void { $items = $this->getItems(); - if (is_array($items)) { - /** @var Model\DataObject\Fieldcollection\Data\AbstractData $item */ - foreach ($items as $item) { - $fcType = $item->getType(); - $fieldcolDef = Model\DataObject\Fieldcollection\Definition::getByKey($fcType); - $fds = $fieldcolDef->getFieldDefinitions(); - foreach ($fds as $fd) { - $fieldGetter = 'get' . ucfirst($fd->getName()); - $fieldValue = $item->$fieldGetter(); - if ($fieldValue instanceof Localizedfield) { - $fieldValue->loadLazyData(); - } + /** @var Model\DataObject\Fieldcollection\Data\AbstractData $item */ + foreach ($items as $item) { + $fcType = $item->getType(); + $fieldcolDef = Model\DataObject\Fieldcollection\Definition::getByKey($fcType); + $fds = $fieldcolDef->getFieldDefinitions(); + foreach ($fds as $fd) { + $fieldGetter = 'get' . ucfirst($fd->getName()); + $fieldValue = $item->$fieldGetter(); + if ($fieldValue instanceof Localizedfield) { + $fieldValue->loadLazyData(); } } } @@ -313,12 +305,10 @@ public function loadLazyData(): void public function __wakeup(): void { - if (is_array($this->items)) { - foreach ($this->items as $key => $item) { - if ($item instanceof \__PHP_Incomplete_Class) { - unset($this->items[$key]); - Logger::error('fieldcollection item ' . $key . ' does not exist anymore'); - } + foreach ($this->items as $key => $item) { + if ($item instanceof \__PHP_Incomplete_Class) { + unset($this->items[$key]); + Logger::error('fieldcollection item ' . $key . ' does not exist anymore'); } } } diff --git a/models/DataObject/Fieldcollection/Dao.php b/models/DataObject/Fieldcollection/Dao.php index ff78da2f15b..2f9fc84ba19 100644 --- a/models/DataObject/Fieldcollection/Dao.php +++ b/models/DataObject/Fieldcollection/Dao.php @@ -161,8 +161,7 @@ public function delete(DataObject\Concrete $object, bool $saveMode = false): arr $tableName = $definition->getTableName($object->getClass()); try { - $dataExists = $this->db->fetchOne('SELECT `id` FROM `'.$tableName."` WHERE - `id` = '".$object->getId()."' AND `fieldname` = '".$this->model->getFieldname()."' LIMIT 1"); + $dataExists = $this->db->fetchOne('SELECT `id` FROM `'.$tableName."` WHERE `id` = '".$object->getId()."' AND `fieldname` = '".$this->model->getFieldname()."' LIMIT 1"); if ($dataExists) { $this->db->delete($tableName, [ 'id' => $object->getId(), @@ -193,29 +192,27 @@ public function delete(DataObject\Concrete $object, bool $saveMode = false): arr $childDefinitions = $definition->getFieldDefinitions(['suppressEnrichment' => true]); - if (is_array($childDefinitions)) { - foreach ($childDefinitions as $fd) { - if (!DataObject::isDirtyDetectionDisabled() && $this->model instanceof Model\Element\DirtyIndicatorInterface) { - if ($fd instanceof DataObject\ClassDefinition\Data\Relations\AbstractRelations && !$this->model->isFieldDirty( - '_self' - )) { - continue; - } + foreach ($childDefinitions as $fd) { + if (!DataObject::isDirtyDetectionDisabled() && $this->model instanceof Model\Element\DirtyIndicatorInterface) { + if ($fd instanceof DataObject\ClassDefinition\Data\Relations\AbstractRelations && !$this->model->isFieldDirty( + '_self' + )) { + continue; } + } - if ($fd instanceof CustomResourcePersistingInterface) { - $fd->delete( - $object, - [ - 'isUpdate' => $saveMode, - 'context' => [ - 'containerType' => 'fieldcollection', - 'containerKey' => $type, - 'fieldname' => $this->model->getFieldname(), - ], - ] - ); - } + if ($fd instanceof CustomResourcePersistingInterface) { + $fd->delete( + $object, + [ + 'isUpdate' => $saveMode, + 'context' => [ + 'containerType' => 'fieldcollection', + 'containerKey' => $type, + 'fieldname' => $this->model->getFieldname(), + ], + ] + ); } } } diff --git a/models/DataObject/Fieldcollection/Definition.php b/models/DataObject/Fieldcollection/Definition.php index ffb2a005334..c3276960f86 100644 --- a/models/DataObject/Fieldcollection/Definition.php +++ b/models/DataObject/Fieldcollection/Definition.php @@ -152,15 +152,13 @@ public function save(bool $saveDefinitionFile = true): void // update classes $classList = new DataObject\ClassDefinition\Listing(); $classes = $classList->load(); - if (is_array($classes)) { - foreach ($classes as $class) { - foreach ($class->getFieldDefinitions() as $fieldDef) { - if ($fieldDef instanceof DataObject\ClassDefinition\Data\Fieldcollections) { - if (in_array($this->getKey(), $fieldDef->getAllowedTypes())) { - $this->getDao()->createUpdateTable($class); - - break; - } + foreach ($classes as $class) { + foreach ($class->getFieldDefinitions() as $fieldDef) { + if ($fieldDef instanceof DataObject\ClassDefinition\Data\Fieldcollections) { + if (in_array($this->getKey(), $fieldDef->getAllowedTypes())) { + $this->getDao()->createUpdateTable($class); + + break; } } } @@ -220,15 +218,13 @@ public function delete(): void // update classes $classList = new DataObject\ClassDefinition\Listing(); $classes = $classList->load(); - if (is_array($classes)) { - foreach ($classes as $class) { - foreach ($class->getFieldDefinitions() as $fieldDef) { - if ($fieldDef instanceof DataObject\ClassDefinition\Data\Fieldcollections) { - if (in_array($this->getKey(), $fieldDef->getAllowedTypes())) { - $this->getDao()->delete($class); - - break; - } + foreach ($classes as $class) { + foreach ($class->getFieldDefinitions() as $fieldDef) { + if ($fieldDef instanceof DataObject\ClassDefinition\Data\Fieldcollections) { + if (in_array($this->getKey(), $fieldDef->getAllowedTypes())) { + $this->getDao()->delete($class); + + break; } } } diff --git a/models/DataObject/Localizedfield/Dao.php b/models/DataObject/Localizedfield/Dao.php index 5dd4bf41255..64db29e5e7e 100644 --- a/models/DataObject/Localizedfield/Dao.php +++ b/models/DataObject/Localizedfield/Dao.php @@ -484,19 +484,17 @@ public function delete(bool $deleteQuery = true, bool $isUpdate = true): bool $fieldDefinition = $container->getFieldDefinition('localizedfields', ['suppressEnrichment' => true]); $childDefinitions = $fieldDefinition->getFieldDefinitions(['suppressEnrichment' => true]); - if (is_array($childDefinitions)) { - foreach ($childDefinitions as $fd) { - if ($fd instanceof CustomResourcePersistingInterface) { - $params = [ - 'context' => $this->model->getContext() ? $this->model->getContext() : [], - 'isUpdate' => $isUpdate, - ]; - if (isset($params['context']['containerType']) && ($params['context']['containerType'] === 'fieldcollection' || $params['context']['containerType'] === 'objectbrick')) { - $params['context']['subContainerType'] = 'localizedfield'; - } - - $fd->delete($object, $params); + foreach ($childDefinitions as $fd) { + if ($fd instanceof CustomResourcePersistingInterface) { + $params = [ + 'context' => $this->model->getContext() ? $this->model->getContext() : [], + 'isUpdate' => $isUpdate, + ]; + if (isset($params['context']['containerType']) && ($params['context']['containerType'] === 'fieldcollection' || $params['context']['containerType'] === 'objectbrick')) { + $params['context']['subContainerType'] = 'localizedfield'; } + + $fd->delete($object, $params); } } } catch (\Exception $e) { @@ -906,25 +904,23 @@ public function createUpdateTable(array $params = []): void } // add non existing columns in the table - if (is_array($fieldDefinitions) && count($fieldDefinitions)) { - foreach ($fieldDefinitions as $value) { - if ($value instanceof DataObject\ClassDefinition\Data\QueryResourcePersistenceAwareInterface) { - $key = $value->getName(); - - // if a datafield requires more than one column in the query table - if (is_array($value->getQueryColumnType())) { - foreach ($value->getQueryColumnType() as $fkey => $fvalue) { - $this->addModifyColumn($queryTable, $key.'__'.$fkey, $fvalue, '', 'NULL'); - $protectedColumns[] = $key.'__'.$fkey; - } - } elseif ($value->getQueryColumnType()) { - $this->addModifyColumn($queryTable, $key, $value->getQueryColumnType(), '', 'NULL'); - $protectedColumns[] = $key; - } + foreach ($fieldDefinitions as $value) { + if ($value instanceof DataObject\ClassDefinition\Data\QueryResourcePersistenceAwareInterface) { + $key = $value->getName(); - // add indices - $this->addIndexToField($value, $queryTable, 'getQueryColumnType'); + // if a datafield requires more than one column in the query table + if (is_array($value->getQueryColumnType())) { + foreach ($value->getQueryColumnType() as $fkey => $fvalue) { + $this->addModifyColumn($queryTable, $key.'__'.$fkey, $fvalue, '', 'NULL'); + $protectedColumns[] = $key.'__'.$fkey; + } + } elseif ($value->getQueryColumnType()) { + $this->addModifyColumn($queryTable, $key, $value->getQueryColumnType(), '', 'NULL'); + $protectedColumns[] = $key; } + + // add indices + $this->addIndexToField($value, $queryTable, 'getQueryColumnType'); } } diff --git a/models/DataObject/ObjectAwareFieldInterface.php b/models/DataObject/ObjectAwareFieldInterface.php index 7a7cfb72ba3..799c4f0c1e4 100644 --- a/models/DataObject/ObjectAwareFieldInterface.php +++ b/models/DataObject/ObjectAwareFieldInterface.php @@ -18,5 +18,8 @@ interface ObjectAwareFieldInterface { + /** + * @return $this + */ public function setObject(?Concrete $object): static; } diff --git a/models/DataObject/Objectbrick.php b/models/DataObject/Objectbrick.php index 58260f72959..944fc49f31c 100644 --- a/models/DataObject/Objectbrick.php +++ b/models/DataObject/Objectbrick.php @@ -199,11 +199,9 @@ public function setObject(?Concrete $object): static $this->object = $object; // update all items with the new $object - if (is_array($this->getItems())) { - foreach ($this->getItems() as $brick) { - if ($brick instanceof Objectbrick\Data\AbstractData) { - $brick->setObject($object); - } + foreach ($this->getItems() as $brick) { + if ($brick instanceof Objectbrick\Data\AbstractData) { + $brick->setObject($object); } } @@ -212,11 +210,9 @@ public function setObject(?Concrete $object): static public function delete(Concrete $object): void { - if (is_array($this->getItems())) { - foreach ($this->getItems() as $brick) { - if ($brick instanceof Objectbrick\Data\AbstractData) { - $brick->delete($object); - } + foreach ($this->getItems() as $brick) { + if ($brick instanceof Objectbrick\Data\AbstractData) { + $brick->delete($object); } } @@ -254,12 +250,10 @@ public function __wakeup(): void } } - if (is_array($this->items)) { - foreach ($this->items as $key => $item) { - if ($item instanceof \__PHP_Incomplete_Class) { - unset($this->items[$key]); - Logger::error('brick item ' . $key . ' does not exist anymore'); - } + foreach ($this->items as $key => $item) { + if ($item instanceof \__PHP_Incomplete_Class) { + unset($this->items[$key]); + Logger::error('brick item ' . $key . ' does not exist anymore'); } } } @@ -311,19 +305,17 @@ public function loadLazyField(string $brick, string $brickField, string $field): public function loadLazyData(): void { $allowedBrickTypes = $this->getAllowedBrickTypes(); - if (is_array($allowedBrickTypes)) { - foreach ($allowedBrickTypes as $allowedBrickType) { - $brickGetter = 'get' . ucfirst($allowedBrickType); - $brickData = $this->$brickGetter(); - if ($brickData) { - $brickDef = Model\DataObject\Objectbrick\Definition::getByKey($allowedBrickType); - $fds = $brickDef->getFieldDefinitions(); - foreach ($fds as $fd) { - $fieldGetter = 'get' . ucfirst($fd->getName()); - $fieldValue = $brickData->$fieldGetter(); - if ($fieldValue instanceof Localizedfield) { - $fieldValue->loadLazyData(); - } + foreach ($allowedBrickTypes as $allowedBrickType) { + $brickGetter = 'get' . ucfirst($allowedBrickType); + $brickData = $this->$brickGetter(); + if ($brickData) { + $brickDef = Model\DataObject\Objectbrick\Definition::getByKey($allowedBrickType); + $fds = $brickDef->getFieldDefinitions(); + foreach ($fds as $fd) { + $fieldGetter = 'get' . ucfirst($fd->getName()); + $fieldValue = $brickData->$fieldGetter(); + if ($fieldValue instanceof Localizedfield) { + $fieldValue->loadLazyData(); } } } diff --git a/models/DataObject/Objectbrick/Data/Dao.php b/models/DataObject/Objectbrick/Data/Dao.php index 45f7f1d217a..1e2a0cb8c41 100644 --- a/models/DataObject/Objectbrick/Data/Dao.php +++ b/models/DataObject/Objectbrick/Data/Dao.php @@ -380,7 +380,7 @@ public function getRelationData(string $field, bool $forOwner, ?string $remoteCl $src = 'dest_id'; } - $relations = $this->db->fetchAllAssociative('SELECT r.' . $dest . ' as dest_id, r.' . $dest . ' as id, r.type, o.className as subtype, concat(o.path ,o.key) as `path` , r.index, o.published + return $this->db->fetchAllAssociative('SELECT r.' . $dest . ' as dest_id, r.' . $dest . ' as id, r.type, o.className as subtype, concat(o.path ,o.key) as `path` , r.index, o.published FROM objects o, object_relations_' . $classId . " r WHERE r.fieldname= ? AND r.ownertype = 'objectbrick' @@ -407,11 +407,5 @@ public function getRelationData(string $field, bool $forOwner, ?string $remoteCl AND (position = '" . $this->model->getType() . "' OR position IS NULL OR position = '') AND r.type='document' ORDER BY `index` ASC", $params); - - if (is_array($relations) && count($relations) > 0) { - return $relations; - } else { - return []; - } } } diff --git a/models/DataObject/Objectbrick/Definition.php b/models/DataObject/Objectbrick/Definition.php index 18da41f3b3b..8508f252fdf 100644 --- a/models/DataObject/Objectbrick/Definition.php +++ b/models/DataObject/Objectbrick/Definition.php @@ -506,13 +506,11 @@ public function delete(): void // update classes $classList = new DataObject\ClassDefinition\Listing(); $classes = $classList->load(); - if (is_array($classes)) { - foreach ($classes as $class) { - foreach ($class->getFieldDefinitions() as $fieldDef) { - if ($fieldDef instanceof DataObject\ClassDefinition\Data\Objectbricks) { - if (in_array($this->getKey(), $fieldDef->getAllowedTypes())) { - break; - } + foreach ($classes as $class) { + foreach ($class->getFieldDefinitions() as $fieldDef) { + if ($fieldDef instanceof DataObject\ClassDefinition\Data\Objectbricks) { + if (in_array($this->getKey(), $fieldDef->getAllowedTypes())) { + break; } } } diff --git a/models/DataObject/Objectbrick/Definition/Dao.php b/models/DataObject/Objectbrick/Definition/Dao.php index d854bd575cb..ddd8ce07f02 100644 --- a/models/DataObject/Objectbrick/Definition/Dao.php +++ b/models/DataObject/Objectbrick/Definition/Dao.php @@ -157,7 +157,7 @@ public function classSaved(DataObject\ClassDefinition $classDefinition): void protected function removeIndices(string $table, array $columnsToRemove, array $protectedColumns): void { - if (is_array($columnsToRemove) && count($columnsToRemove) > 0) { + if ($columnsToRemove) { $indexPrefix = str_starts_with($table, 'object_brick_query_') ? 'p_index_' : 'u_index_'; foreach ($columnsToRemove as $value) { if (!in_array(strtolower($value), $protectedColumns)) { diff --git a/models/DataObject/Service.php b/models/DataObject/Service.php index 7f29d6b9d7d..196878cb1e4 100644 --- a/models/DataObject/Service.php +++ b/models/DataObject/Service.php @@ -90,14 +90,12 @@ public static function getObjectsReferencingUser(int $userId): array foreach ($classesList as $class) { $fieldDefinitions = $class->getFieldDefinitions(); $dataKeys = []; - if (is_array($fieldDefinitions)) { - foreach ($fieldDefinitions as $tag) { - if ($tag instanceof ClassDefinition\Data\User) { - $dataKeys[] = $tag->getName(); - } + foreach ($fieldDefinitions as $tag) { + if ($tag instanceof ClassDefinition\Data\User) { + $dataKeys[] = $tag->getName(); } } - if (is_array($dataKeys) && count($dataKeys) > 0) { + if ($dataKeys) { $classesToCheck[$class->getName()] = $dataKeys; } } @@ -772,16 +770,13 @@ public static function loadAllObjectFields(AbstractObject $object): void */ public static function getOptionsForSelectField(string|Concrete $object, ClassDefinition\Data\Multiselect|ClassDefinition\Data\Select|string $definition): array { - $class = null; $options = []; - if (is_object($object) && method_exists($object, 'getClass')) { - $class = $object->getClass(); - } elseif (is_string($object)) { + if (!$object instanceof Concrete) { $object = '\\' . ltrim($object, '\\'); $object = new $object(); - $class = $object->getClass(); } + $class = $object->getClass(); if ($class) { if (is_string($definition)) { diff --git a/models/Dependency/Dao.php b/models/Dependency/Dao.php index abfaccf51e5..c6f55bb2bfb 100644 --- a/models/Dependency/Dao.php +++ b/models/Dependency/Dao.php @@ -52,10 +52,8 @@ public function getBySourceId(int $id = null, string $type = null): void ORDER BY objects.path, objects.key, documents.path, documents.key, assets.path, assets.filename', [$this->model->getSourceId(), $this->model->getSourceType()]); - if (is_array($data) && count($data) > 0) { - foreach ($data as $d) { - $this->model->addRequirement($d['targetid'], $d['targettype']); - } + foreach ($data as $d) { + $this->model->addRequirement($d['targetid'], $d['targettype']); } } @@ -72,12 +70,10 @@ public function cleanAllForElement(Element\ElementInterface $element): void //schedule for sanity check $data = $this->db->fetchAllAssociative('SELECT `sourceid`, `sourcetype` FROM dependencies WHERE targettype = ? AND targetid = ?', [$type, $id]); - if (is_array($data)) { - foreach ($data as $row) { - \Pimcore::getContainer()->get('messenger.bus.pimcore-core')->dispatch( - new SanityCheckMessage($row['sourcetype'], $row['sourceid']) - ); - } + foreach ($data as $row) { + \Pimcore::getContainer()->get('messenger.bus.pimcore-core')->dispatch( + new SanityCheckMessage($row['sourcetype'], $row['sourceid']) + ); } Helper::selectAndDeleteWhere($this->db, 'dependencies', 'id', Helper::quoteInto($this->db, 'sourceid = ?', $id) . ' AND ' . Helper::quoteInto($this->db, 'sourcetype = ?', $type)); @@ -190,13 +186,11 @@ public function getRequiredBy(int $offset = null, int $limit = null): array $requiredBy = []; - if (is_array($data) && count($data) > 0) { - foreach ($data as $d) { - $requiredBy[] = [ - 'id' => $d['sourceid'], - 'type' => $d['sourcetype'], - ]; - } + foreach ($data as $d) { + $requiredBy[] = [ + 'id' => $d['sourceid'], + 'type' => $d['sourcetype'], + ]; } return $requiredBy; @@ -244,13 +238,7 @@ public function getRequiredByWithPath(int $offset = null, int $limit = null, str $query .= ' LIMIT ' . $offset . ', ' . $limit; } - $requiredBy = $this->db->fetchAllAssociative($query); - - if (is_array($requiredBy) && count($requiredBy) > 0) { - return $requiredBy; - } else { - return []; - } + return $this->db->fetchAllAssociative($query); } /** diff --git a/models/Document.php b/models/Document.php index 8c9fd9e2ca0..820b6deebab 100644 --- a/models/Document.php +++ b/models/Document.php @@ -358,7 +358,7 @@ static function (array $doc) use ($oldPath, $newPath): array { } $additionalTags = []; - if (isset($updatedChildren) && is_array($updatedChildren)) { + if (isset($updatedChildren)) { foreach ($updatedChildren as $updatedDocument) { $tag = self::getCacheKey($updatedDocument['id']); $additionalTags[] = $tag; @@ -470,15 +470,13 @@ protected function update(array $params = []): void // save properties $this->getProperties(); $this->getDao()->deleteAllProperties(); - if (is_array($this->getProperties()) && count($this->getProperties()) > 0) { - foreach ($this->getProperties() as $property) { - if (!$property->getInherited()) { - $property->setDao(null); - $property->setCid($this->getId()); - $property->setCtype('document'); - $property->setCpath($this->getRealFullPath()); - $property->save(); - } + foreach ($this->getProperties() as $property) { + if (!$property->getInherited()) { + $property->setDao(null); + $property->setCid($this->getId()); + $property->setCtype('document'); + $property->setCpath($this->getRealFullPath()); + $property->save(); } } diff --git a/models/Document/Dao.php b/models/Document/Dao.php index 116cf65ed04..e7c3eee7836 100644 --- a/models/Document/Dao.php +++ b/models/Document/Dao.php @@ -532,9 +532,9 @@ public function isAllowed(string $type, User $user): bool } /** + * @param string[] $columns * * @return array - * */ public function areAllowed(array $columns, User $user): array { diff --git a/models/Document/Editable.php b/models/Document/Editable.php index 0e6a2b7eaed..07e1770496b 100644 --- a/models/Document/Editable.php +++ b/models/Document/Editable.php @@ -325,10 +325,6 @@ public function setConfig(array $config): static */ public function addConfig(string $name, mixed $value): static { - if (!is_array($this->config)) { - $this->config = []; - } - $this->config[$name] = $value; return $this; @@ -561,10 +557,7 @@ private static function doBuildName(string $name, string $type, BlockState $bloc array_pop($tmpBlocks); array_pop($tmpIndexes); - $tmpName = $name; - if (is_array($tmpBlocks)) { - $tmpName = self::buildHierarchicalName($name, $tmpBlocks, $tmpIndexes); - } + $tmpName = self::buildHierarchicalName($name, $tmpBlocks, $tmpIndexes); $previousBlockName = $blocks[count($blocks) - 1]->getName(); if ($previousBlockName === $tmpName || ($targetGroupElementName && $previousBlockName === $targetGroupElementName)) { diff --git a/models/Document/Editable/Area.php b/models/Document/Editable/Area.php index c98df8fdab2..13612118011 100644 --- a/models/Document/Editable/Area.php +++ b/models/Document/Editable/Area.php @@ -95,7 +95,7 @@ private function renderDialogBoxEditables(array $config, EditableRenderer $edita $editable->setInDialogBox($dialogId); $editable->addConfig('dialogBoxConfig', $config); $this->outputEditmode($editable->render()); - } elseif (is_array($config) && isset($config[0])) { + } else { foreach ($config as $item) { $this->renderDialogBoxEditables($item, $editableRenderer, $dialogId); } diff --git a/models/Document/Editable/Areablock.php b/models/Document/Editable/Areablock.php index 36e1208cac5..41e0a31ee5f 100644 --- a/models/Document/Editable/Areablock.php +++ b/models/Document/Editable/Areablock.php @@ -81,9 +81,6 @@ public function admin(): void public function frontend(): void { - if (!is_array($this->indices)) { - $this->indices = []; - } reset($this->indices); while ($this->loop()); } @@ -439,7 +436,7 @@ protected function renderDialogBoxEditables(array $config, EditableRenderer $edi $editable->setInDialogBox($dialogId); $editable->addConfig('dialogBoxConfig', $config); $html .= $editable->render(); - } elseif (is_array($config) && isset($config[0])) { + } else { foreach ($config as $item) { $this->renderDialogBoxEditables($item, $editableRenderer, $dialogId, $html); } diff --git a/models/Document/Editable/Image.php b/models/Document/Editable/Image.php index af28188b14c..bb7793ce7a4 100644 --- a/models/Document/Editable/Image.php +++ b/models/Document/Editable/Image.php @@ -211,10 +211,6 @@ public function getConfig(): array public function frontend() { - if (!is_array($this->config)) { - $this->config = []; - } - $image = $this->getImage(); if ($image instanceof Asset\Image) { diff --git a/models/Document/Editable/Link.php b/models/Document/Editable/Link.php index 7b268c0aaa0..ad5c3cf9cad 100644 --- a/models/Document/Editable/Link.php +++ b/models/Document/Editable/Link.php @@ -73,10 +73,6 @@ public function frontend() $url = $this->getHref(); if (strlen($url) > 0) { - if (!is_array($this->config)) { - $this->config = []; - } - $prefix = ''; $suffix = ''; $noText = false; diff --git a/models/Document/Editable/Relations.php b/models/Document/Editable/Relations.php index d16d559110e..444ded531c6 100644 --- a/models/Document/Editable/Relations.php +++ b/models/Document/Editable/Relations.php @@ -82,17 +82,15 @@ public function getDataEditmode(): array $this->setElements(); $return = []; - if (is_array($this->elements) && count($this->elements) > 0) { - foreach ($this->elements as $element) { - if ($element instanceof DataObject\Concrete) { - $return[] = [$element->getId(), $element->getRealFullPath(), DataObject::OBJECT_TYPE_OBJECT, $element->getClassName()]; - } elseif ($element instanceof DataObject\AbstractObject) { - $return[] = [$element->getId(), $element->getRealFullPath(), DataObject::OBJECT_TYPE_OBJECT, DataObject::OBJECT_TYPE_VARIANT, DataObject::OBJECT_TYPE_FOLDER]; - } elseif ($element instanceof Asset) { - $return[] = [$element->getId(), $element->getRealFullPath(), 'asset', $element->getType()]; - } elseif ($element instanceof Document) { - $return[] = [$element->getId(), $element->getRealFullPath(), 'document', $element->getType()]; - } + foreach ($this->elements as $element) { + if ($element instanceof DataObject\Concrete) { + $return[] = [$element->getId(), $element->getRealFullPath(), DataObject::OBJECT_TYPE_OBJECT, $element->getClassName()]; + } elseif ($element instanceof DataObject\AbstractObject) { + $return[] = [$element->getId(), $element->getRealFullPath(), DataObject::OBJECT_TYPE_OBJECT, DataObject::OBJECT_TYPE_VARIANT, DataObject::OBJECT_TYPE_FOLDER]; + } elseif ($element instanceof Asset) { + $return[] = [$element->getId(), $element->getRealFullPath(), 'asset', $element->getType()]; + } elseif ($element instanceof Document) { + $return[] = [$element->getId(), $element->getRealFullPath(), 'document', $element->getType()]; } } @@ -166,17 +164,15 @@ public function resolveDependencies(): array $this->setElements(); $dependencies = []; - if (is_array($this->elements) && count($this->elements) > 0) { - foreach ($this->elements as $element) { - if ($element instanceof Element\ElementInterface) { - $elementType = Element\Service::getElementType($element); - $key = $elementType . '_' . $element->getId(); + foreach ($this->elements as $element) { + if ($element instanceof Element\ElementInterface) { + $elementType = Element\Service::getElementType($element); + $key = $elementType . '_' . $element->getId(); - $dependencies[$key] = [ - 'id' => $element->getId(), - 'type' => $elementType, - ]; - } + $dependencies[$key] = [ + 'id' => $element->getId(), + 'type' => $elementType, + ]; } } diff --git a/models/Document/Editable/Renderlet.php b/models/Document/Editable/Renderlet.php index a3c9c8a032f..d3d7e206968 100644 --- a/models/Document/Editable/Renderlet.php +++ b/models/Document/Editable/Renderlet.php @@ -95,10 +95,6 @@ public function frontend() $container = \Pimcore::getContainer(); $editableHandler = $container->get(EditableHandler::class); - if (!is_array($this->config)) { - $this->config = []; - } - if (empty($this->config['controller']) && !empty($this->config['template'])) { $this->config['controller'] = $container->getParameter('pimcore.documents.default_controller'); } diff --git a/models/Document/Editable/Table.php b/models/Document/Editable/Table.php index f465b87e244..908ccec6884 100644 --- a/models/Document/Editable/Table.php +++ b/models/Document/Editable/Table.php @@ -45,7 +45,7 @@ public function frontend() { $html = ''; - if (is_array($this->data) && count($this->data) > 0) { + if (count($this->data) > 0) { $html .= ''; foreach ($this->data as $row) { diff --git a/models/Document/PageSnippet.php b/models/Document/PageSnippet.php index 345d202009e..8bade65782e 100644 --- a/models/Document/PageSnippet.php +++ b/models/Document/PageSnippet.php @@ -142,13 +142,11 @@ protected function update(array $params = []): void parent::update($params); - if (is_array($editables) && count($editables)) { - foreach ($editables as $editable) { - if (!$editable->getInherited()) { - $editable->setDao(null); - $editable->setDocumentId($this->getId()); - $editable->save(); - } + foreach ($editables as $editable) { + if (!$editable->getInherited()) { + $editable->setDao(null); + $editable->setDocumentId($this->getId()); + $editable->save(); } } diff --git a/models/Element/AbstractElement.php b/models/Element/AbstractElement.php index d4601e8f21f..5143122808d 100644 --- a/models/Element/AbstractElement.php +++ b/models/Element/AbstractElement.php @@ -394,10 +394,8 @@ protected function resolveDependencies(): array $dependencies = [[]]; // check for properties - if (method_exists($this, 'getProperties')) { - foreach ($this->getProperties() as $property) { - $dependencies[] = $property->resolveDependencies(); - } + foreach ($this->getProperties() as $property) { + $dependencies[] = $property->resolveDependencies(); } return array_merge(...$dependencies); diff --git a/models/Element/Dao.php b/models/Element/Dao.php index 72ce496caaa..f20321f036a 100644 --- a/models/Element/Dao.php +++ b/models/Element/Dao.php @@ -94,6 +94,7 @@ public function InheritingPermission(string $type, array $userIds, string $table } /** + * @param string[] $columns * * @return array * diff --git a/models/Element/Recyclebin/Item.php b/models/Element/Recyclebin/Item.php index 18bf97e2689..774dfbf0a72 100644 --- a/models/Element/Recyclebin/Item.php +++ b/models/Element/Recyclebin/Item.php @@ -184,11 +184,9 @@ public function save(Model\User $user = null): void $storage->writeStream($scope->getStorageFileBinary($element), $element->getStream()); } - if (method_exists($element, 'getChildren')) { - $children = $element->getChildren(); - foreach ($children as $child) { - $rec($child, $rec, $scope); - } + $children = $element->getChildren(); + foreach ($children as $child) { + $rec($child, $rec, $scope); } } }; diff --git a/models/Element/Service.php b/models/Element/Service.php index e76e576146c..bfcac680eba 100644 --- a/models/Element/Service.php +++ b/models/Element/Service.php @@ -341,10 +341,8 @@ public static function getBaseClassNameForElement(string|ElementInterface $eleme { if ($element instanceof ElementInterface) { $elementType = self::getElementType($element); - } elseif (is_string($element)) { - $elementType = $element; } else { - throw new \Exception('Wrong type given for getBaseClassNameForElement(), ElementInterface and string are allowed'); + $elementType = $element; } $baseClass = ucfirst($elementType); @@ -995,7 +993,7 @@ public static function getUniqueKey(ElementInterface $element, int $nr = 0): ?st public static function fixAllowedTypes(array $data, string $type): array { // this is the new method with Ext.form.MultiSelect - if (is_array($data) && count($data)) { + if (count($data)) { $first = reset($data); if (!is_array($first)) { $parts = $data; @@ -1023,7 +1021,7 @@ public static function fixAllowedTypes(array $data, string $type): array } } - return $data ? $data : []; + return $data; } /** @@ -1036,36 +1034,34 @@ public static function getSafeVersionInfo(array $versions): array $indexMap = []; $result = []; - if (is_array($versions)) { - foreach ($versions as $versionObj) { - $version = [ - 'id' => $versionObj->getId(), - 'cid' => $versionObj->getCid(), - 'ctype' => $versionObj->getCtype(), - 'note' => $versionObj->getNote(), - 'date' => $versionObj->getDate(), - 'public' => $versionObj->getPublic(), - 'versionCount' => $versionObj->getVersionCount(), - 'autoSave' => $versionObj->isAutoSave(), - ]; - - $version['user'] = ['name' => '', 'id' => '']; - if ($user = $versionObj->getUser()) { - $version['user'] = [ - 'name' => $user->getName(), - 'id' => $user->getId(), - ]; - } + foreach ($versions as $versionObj) { + $version = [ + 'id' => $versionObj->getId(), + 'cid' => $versionObj->getCid(), + 'ctype' => $versionObj->getCtype(), + 'note' => $versionObj->getNote(), + 'date' => $versionObj->getDate(), + 'public' => $versionObj->getPublic(), + 'versionCount' => $versionObj->getVersionCount(), + 'autoSave' => $versionObj->isAutoSave(), + ]; - $versionKey = $versionObj->getDate() . '-' . $versionObj->getVersionCount(); - if (!isset($indexMap[$versionKey])) { - $indexMap[$versionKey] = 0; - } - $version['index'] = $indexMap[$versionKey]; - $indexMap[$versionKey] = $indexMap[$versionKey] + 1; + $version['user'] = ['name' => '', 'id' => '']; + if ($user = $versionObj->getUser()) { + $version['user'] = [ + 'name' => $user->getName(), + 'id' => $user->getId(), + ]; + } - $result[] = $version; + $versionKey = $versionObj->getDate() . '-' . $versionObj->getVersionCount(); + if (!isset($indexMap[$versionKey])) { + $indexMap[$versionKey] = 0; } + $version['index'] = $indexMap[$versionKey]; + $indexMap[$versionKey] = $indexMap[$versionKey] + 1; + + $result[] = $version; } return $result; @@ -1166,33 +1162,31 @@ public static function getNoteData(Note $note): array // prepare key-values $keyValues = []; - if (is_array($note->getData())) { - foreach ($note->getData() as $name => $d) { - $type = $d['type']; - $data = $d['data']; - - if ($type == 'document' || $type == 'object' || $type == 'asset') { - if ($d['data'] instanceof ElementInterface) { - $data = [ - 'id' => $d['data']->getId(), - 'path' => $d['data']->getRealFullPath(), - 'type' => $d['data']->getType(), - ]; - } - } elseif ($type == 'date') { - if (is_object($d['data'])) { - $data = $d['data']->getTimestamp(); - } + foreach ($note->getData() as $name => $d) { + $type = $d['type']; + $data = $d['data']; + + if ($type == 'document' || $type == 'object' || $type == 'asset') { + if ($d['data'] instanceof ElementInterface) { + $data = [ + 'id' => $d['data']->getId(), + 'path' => $d['data']->getRealFullPath(), + 'type' => $d['data']->getType(), + ]; } + } elseif ($type == 'date') { + if (is_object($d['data'])) { + $data = $d['data']->getTimestamp(); + } + } - $keyValue = [ - 'type' => $type, - 'name' => $name, - 'data' => $data, - ]; + $keyValue = [ + 'type' => $type, + 'name' => $name, + 'data' => $data, + ]; - $keyValues[] = $keyValue; - } + $keyValues[] = $keyValue; } $e['data'] = $keyValues; diff --git a/models/Element/ValidationException.php b/models/Element/ValidationException.php index 0ecadb0ec8f..e72684d370a 100644 --- a/models/Element/ValidationException.php +++ b/models/Element/ValidationException.php @@ -52,11 +52,9 @@ public function getContextStack(): array public function __toString(): string { $result = parent::__toString(); - if (is_array($this->subItems)) { - foreach ($this->subItems as $subItem) { - $result .= "\n\n"; - $result .= $subItem->__toString(); - } + foreach ($this->subItems as $subItem) { + $result .= "\n\n"; + $result .= $subItem->__toString(); } return $result; diff --git a/models/Translation.php b/models/Translation.php index 9e7c7329339..ce92d893220 100644 --- a/models/Translation.php +++ b/models/Translation.php @@ -185,7 +185,7 @@ public function setUserModification(?int $userModification): void /** * @internal * - * + * @return string[] */ public static function getValidLanguages(string $domain = self::DOMAIN_DEFAULT): array { @@ -360,6 +360,7 @@ public function delete(): void * The CSV file has to have the same format as an Pimcore translation-export-file * * @param string $file - path to the csv file + * @param string[]|null $languages * * @throws \Exception * @@ -370,7 +371,7 @@ public static function importTranslationsFromFile(string $file, string $domain = $delta = []; if (is_readable($file)) { - if (!$languages || !is_array($languages)) { + if (!$languages) { $languages = static::getValidLanguages($domain); } @@ -406,7 +407,7 @@ public static function importTranslationsFromFile(string $file, string $domain = } //process translations - if (is_array($data) && count($data) > 1) { + if (count($data) > 1) { $keys = $data[0]; // remove wrong quotes in some export/import constellations $keys = array_map(function ($value) { diff --git a/models/Translation/Dao.php b/models/Translation/Dao.php index 40f019d53f7..692fff26112 100644 --- a/models/Translation/Dao.php +++ b/models/Translation/Dao.php @@ -91,26 +91,24 @@ public function save(): void } if ($this->model->getKey() !== '') { - if (is_array($this->model->getTranslations())) { - foreach ($this->model->getTranslations() as $language => $text) { - if (count($editableLanguages) && !in_array($language, $editableLanguages)) { - Logger::warning(sprintf('User %s not allowed to edit %s translation', $user->getUsername(), $language)); // @phpstan-ignore-line - - continue; - } - - $data = [ - 'key' => $this->model->getKey(), - 'type' => $this->model->getType(), - 'language' => $language, - 'text' => $sanitizer->sanitize($text), - 'modificationDate' => $this->model->getModificationDate(), - 'creationDate' => $this->model->getCreationDate(), - 'userOwner' => $this->model->getUserOwner(), - 'userModification' => $this->model->getUserModification(), - ]; - Helper::upsert($this->db, $this->getDatabaseTableName(), $data, $this->getPrimaryKey($this->getDatabaseTableName())); + foreach ($this->model->getTranslations() as $language => $text) { + if (count($editableLanguages) && !in_array($language, $editableLanguages)) { + Logger::warning(sprintf('User %s not allowed to edit %s translation', $user->getUsername(), $language)); // @phpstan-ignore-line + + continue; } + + $data = [ + 'key' => $this->model->getKey(), + 'type' => $this->model->getType(), + 'language' => $language, + 'text' => $sanitizer->sanitize($text), + 'modificationDate' => $this->model->getModificationDate(), + 'creationDate' => $this->model->getCreationDate(), + 'userOwner' => $this->model->getUserOwner(), + 'userModification' => $this->model->getUserModification(), + ]; + Helper::upsert($this->db, $this->getDatabaseTableName(), $data, $this->getPrimaryKey($this->getDatabaseTableName())); } } } diff --git a/models/Translation/Listing/Dao.php b/models/Translation/Listing/Dao.php index 32612bdb5ab..d8488fa1380 100644 --- a/models/Translation/Listing/Dao.php +++ b/models/Translation/Listing/Dao.php @@ -153,7 +153,7 @@ public function cleanup(): void (SELECT count(*) FROM ' . $this->getDatabaseTableName() . " WHERE `key` = tbl1.`key` AND (`text` IS NULL OR `text` = '')) = (SELECT count(*) FROM " . $this->getDatabaseTableName() . ' WHERE `key` = tbl1.`key`) GROUP BY `key`;'); - if (is_array($keysToDelete) && !empty($keysToDelete)) { + if ($keysToDelete) { $preparedKeys = []; foreach ($keysToDelete as $value) { $preparedKeys[] = $this->db->quote($value); diff --git a/models/User/AbstractUser.php b/models/User/AbstractUser.php index 9b901a3e6b2..6d1d0b48310 100644 --- a/models/User/AbstractUser.php +++ b/models/User/AbstractUser.php @@ -39,7 +39,7 @@ abstract class AbstractUser extends Model\AbstractModel implements AbstractUserI public static function getById(int $id): static|null { - if (!is_numeric($id) || $id < 0) { + if ($id < 0) { return null; } @@ -238,13 +238,11 @@ private function cleanupUserRoleRelations(): void if (count($userRoleListing)) { foreach ($userRoleListing as $relatedUser) { $userRoles = $relatedUser->getRoles(); - if (is_array($userRoles)) { - $key = array_search($this->getId(), $userRoles); - if (false !== $key) { - unset($userRoles[$key]); - $relatedUser->setRoles($userRoles); - $relatedUser->save(); - } + $key = array_search($this->getId(), $userRoles); + if (false !== $key) { + unset($userRoles[$key]); + $relatedUser->setRoles($userRoles); + $relatedUser->save(); } } } diff --git a/models/User/Permission/Definition.php b/models/User/Permission/Definition.php index 72c819e8b0c..6dd9b6a2175 100644 --- a/models/User/Permission/Definition.php +++ b/models/User/Permission/Definition.php @@ -31,9 +31,7 @@ class Definition extends Model\AbstractModel public function __construct(array $data = []) { - if (is_array($data) && !empty($data)) { - $this->setValues($data); - } + $this->setValues($data); } public function getKey(): ?string diff --git a/models/User/UserRole/Folder.php b/models/User/UserRole/Folder.php index 5c6b11ebf4e..5795fff793f 100644 --- a/models/User/UserRole/Folder.php +++ b/models/User/UserRole/Folder.php @@ -65,12 +65,13 @@ public function getChildren(): array return $this->children; } + /** + * @return $this + */ public function setChildren(array $children): static { - if (is_array($children)) { - $this->children = $children; - $this->hasChildren = count($children) > 0; - } + $this->children = $children; + $this->hasChildren = count($children) > 0; return $this; } diff --git a/models/Version.php b/models/Version.php index b822851f8f4..20a8ed96eb2 100644 --- a/models/Version.php +++ b/models/Version.php @@ -354,6 +354,9 @@ public function getUserId(): int return $this->userId; } + /** + * @return $this + */ public function setCid(int $cid): static { $this->cid = $cid; @@ -361,6 +364,9 @@ public function setCid(int $cid): static return $this; } + /** + * @return $this + */ public function setDate(int $date): static { $this->date = $date; @@ -368,6 +374,9 @@ public function setDate(int $date): static return $this; } + /** + * @return $this + */ public function setId(int $id): static { $this->id = $id; @@ -375,6 +384,9 @@ public function setId(int $id): static return $this; } + /** + * @return $this + */ public function setNote(string $note): static { $this->note = $note; @@ -382,13 +394,14 @@ public function setNote(string $note): static return $this; } + /** + * @return $this + */ public function setUserId(int $userId): static { - if (is_numeric($userId)) { - if ($user = User::getById($userId)) { - $this->userId = (int) $userId; - $this->setUser($user); - } + if ($user = User::getById($userId)) { + $this->userId = $userId; + $this->setUser($user); } return $this; @@ -403,6 +416,9 @@ public function getData(): mixed return $this->data; } + /** + * @return $this + */ public function setData(mixed $data): static { $this->data = $data; @@ -415,6 +431,9 @@ public function getSerialized(): bool return $this->serialized; } + /** + * @return $this + */ public function setSerialized(bool $serialized): static { $this->serialized = $serialized; @@ -427,6 +446,9 @@ public function getCtype(): string return $this->ctype; } + /** + * @return $this + */ public function setCtype(string $ctype): static { $this->ctype = $ctype; @@ -439,6 +461,9 @@ public function getUser(): ?User return $this->user; } + /** + * @return $this + */ public function setUser(?User $user): static { $this->user = $user; @@ -456,6 +481,9 @@ public function isPublic(): bool return $this->public; } + /** + * @return $this + */ public function setPublic(bool $public): static { $this->public = $public; @@ -465,7 +493,7 @@ public function setPublic(bool $public): static public function getVersionCount(): int { - return $this->versionCount ? $this->versionCount : 0; + return $this->versionCount ?: 0; } public function setVersionCount(int $versionCount): void diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 6bf12daffd8..9516025bcf0 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -240,6 +240,11 @@ parameters: count: 1 path: bundles/XliffBundle/src/Event/Model/TranslationXliffEvent.php + - + message: "#^Call to function is_subclass_of\\(\\) with '\\\\\\\\App\\\\\\\\Kernel' and 'Pimcore\\\\\\\\Kernel' will always evaluate to true\\.$#" + count: 1 + path: lib/Bootstrap.php + - message: "#^File is missing a \"declare\\(strict_types\\=1\\)\" declaration\\.$#" count: 1 @@ -270,11 +275,6 @@ parameters: count: 1 path: lib/Image/Adapter/Imagick.php - - - message: "#^Result of \\|\\| is always true\\.$#" - count: 2 - path: lib/Mail.php - - message: "#^File is missing a \"declare\\(strict_types\\=1\\)\" declaration\\.$#" count: 1 @@ -335,6 +335,11 @@ parameters: count: 1 path: lib/Tool/Console.php + - + message: "#^Ternary operator condition is always true\\.$#" + count: 1 + path: lib/Tool/Requirements.php + - message: "#^Dead catch \\- Throwable is never thrown in the try block\\.$#" count: 1 @@ -550,6 +555,11 @@ parameters: count: 1 path: models/DataObject/Listing/Concrete/Dao.php + - + message: "#^Call to function method_exists\\(\\) with Pimcore\\\\Model\\\\DataObject\\\\Listing and 'addDistinct' will always evaluate to true\\.$#" + count: 1 + path: models/DataObject/Listing/Dao.php + - message: "#^File is missing a \"declare\\(strict_types\\=1\\)\" declaration\\.$#" count: 1 diff --git a/phpstan-parameters.neon b/phpstan-parameters.neon index 5c2f4121f19..b0390d48df6 100644 --- a/phpstan-parameters.neon +++ b/phpstan-parameters.neon @@ -27,6 +27,7 @@ parameters: checkGenericClassInNonGenericObjectType: false checkMissingIterableValueType: false + checkAlwaysTrueCheckTypeFunctionCall: true ergebnis: final: