From 16d0440f726aa72d6ce96be853781cd769bb1cc0 Mon Sep 17 00:00:00 2001 From: Alex Skrypnyk Date: Thu, 9 Nov 2023 10:38:27 +1100 Subject: [PATCH] Added srtict types. --- .ahoy.yml | 9 +- .circleci/config.yml | 3 + composer.json | 4 +- composer.lock | 158 +- docs/development.md | 4 +- phpstan.neon | 24 +- rector.php | 65 + scripts/drevops/build.sh | 1 + tests/behat/bootstrap/FeatureContext.php | 87 +- .../theme.settings.components.feature | 2 +- tests/phpunit/AddPhpcsExclusionsUnitTest.php | 4 +- ...CivicthemeCreateSubthemeScriptUnitTest.php | 38 +- tests/phpunit/Drupal/SettingsTestCase.php | 2 +- .../ExtractCssColorsToCsvScriptUnitTest.php | 12 +- tests/phpunit/ScriptUnitTestBase.php | 54 +- .../civictheme_admin/civictheme_admin.module | 2 +- .../civictheme_content.install | 14 +- .../civictheme_content.module | 6 +- .../civictheme_content_corporate.module | 4 +- ...victheme_content_corporate.post_update.php | 4 +- .../855f86ae-b6a9-477c-8827-6b13b5c8ff41.yml | 2 +- .../civictheme_content_default.module | 4 +- ...civictheme_content_default.post_update.php | 4 +- .../civictheme_content_government.module | 4 +- ...ictheme_content_government.post_update.php | 4 +- .../21d11ae0-2874-4663-9937-a48ce30a7ad7.yml | 2 +- .../civictheme_content_highereducation.module | 4 +- ...me_content_highereducation.post_update.php | 4 +- .../11575ae4-d804-4b68-a9e2-528dde78ca5e.yml | 2 +- .../custom/civictheme_content/src/Helper.php | 8 +- .../civictheme_dev/civictheme_dev.install | 6 +- .../civictheme_dev/civictheme_dev.module | 8 +- .../civictheme_dev.post_update.php | 36 +- .../CivicthemeDevConfigDevelSubscriber.php | 8 +- .../custom/civictheme_dev/src/Helper.php | 1399 ----------------- .../CivicthemeDevIgnoreFilter.php | 31 +- .../src/CivicthemeGovcmsManager.php | 37 +- .../src/Commands/CivicthemeGovcmsCommands.php | 6 +- .../cs_generated_content.install | 2 +- .../generated_content/file/file.inc | 9 +- .../media/civictheme_document.inc | 9 +- .../media/civictheme_icon.inc | 9 +- .../media/civictheme_image.inc | 10 +- .../media/civictheme_video.inc | 10 +- .../node/civictheme_event.inc | 20 +- .../01.helpers.inc | 17 +- .../02.general.inc | 7 +- .../component.attachment.inc | 7 +- .../component.map.inc | 7 +- .../node/civictheme_page.inc | 21 +- .../civictheme_page_variations/01.helpers.inc | 17 +- .../civictheme_page_variations/02.general.inc | 7 +- .../civictheme_page_variations/03.banner.inc | 8 +- .../component.accordion.inc | 8 +- .../component.attachment.inc | 7 +- .../component.automated_list.inc | 8 +- .../component.callout.inc | 7 +- .../component.campaign.inc | 7 +- .../component.cards.inc | 8 +- .../component.content.inc | 7 +- .../component.iframe.inc | 7 +- .../component.manual_list.inc | 8 +- .../component.map.inc | 7 +- .../component.next_step.inc | 7 +- .../component.promo.inc | 7 +- .../component.quote.inc | 7 +- .../component.slider.inc | 8 +- .../component.webform.inc | 7 +- .../civictheme_site_sections.inc | 9 +- .../taxonomy_term/civictheme_topics.inc | 9 +- .../generated_content/user/user.inc | 68 +- .../src/CsGeneratedContentAssetGenerator.php | 2 +- .../src/CsGeneratedContentCivicthemeTrait.php | 258 +-- .../src/CsGeneratedContentHelper.php | 25 +- .../src/CsGeneratedContentServiceProvider.php | 2 +- web/sites/default/default.settings.php | 4 +- .../contrib/civictheme/civictheme.api.php | 4 +- .../contrib/civictheme/civictheme.info.yml | 4 +- .../civictheme/civictheme.post_update.php | 54 +- .../contrib/civictheme/civictheme.theme | 30 +- .../civictheme/civictheme_create_subtheme.php | 146 +- .../scripts/extract_css_colors_to_csv.php | 54 +- .../civictheme_starter_kit.theme | 4 +- .../scripts/add_phpcs_exclusions.php | 18 +- web/themes/contrib/civictheme/composer.json | 2 +- .../contrib/civictheme/includes/accordion.inc | 2 +- .../contrib/civictheme/includes/alert.inc | 2 +- .../civictheme/includes/attachment.inc | 2 +- .../civictheme/includes/automated_list.inc | 5 +- .../contrib/civictheme/includes/banner.inc | 9 +- .../civictheme/includes/block_content.inc | 2 +- .../contrib/civictheme/includes/callout.inc | 2 +- .../contrib/civictheme/includes/campaign.inc | 2 +- .../contrib/civictheme/includes/cards.inc | 24 +- .../contrib/civictheme/includes/content.inc | 2 +- .../contrib/civictheme/includes/form.inc | 54 +- .../contrib/civictheme/includes/iframe.inc | 2 +- .../contrib/civictheme/includes/image.inc | 2 +- .../contrib/civictheme/includes/libraries.inc | 2 +- .../contrib/civictheme/includes/link.inc | 28 +- .../civictheme/includes/local_tasks.inc | 5 +- .../civictheme/includes/manual_list.inc | 3 +- .../contrib/civictheme/includes/map.inc | 2 +- .../contrib/civictheme/includes/media.inc | 65 +- .../contrib/civictheme/includes/menu.inc | 6 +- .../civictheme/includes/mobile_navigation.inc | 72 +- .../contrib/civictheme/includes/next_step.inc | 2 +- .../contrib/civictheme/includes/node.inc | 17 +- .../contrib/civictheme/includes/page.inc | 2 +- .../contrib/civictheme/includes/pager.inc | 19 +- .../civictheme/includes/paragraphs.inc | 58 +- .../includes/primary_navigation.inc | 2 +- .../contrib/civictheme/includes/process.inc | 4 +- .../contrib/civictheme/includes/promo.inc | 2 +- .../contrib/civictheme/includes/quote.inc | 2 +- .../contrib/civictheme/includes/search.inc | 2 +- .../includes/secondary_navigation.inc | 2 +- .../civictheme/includes/site_section.inc | 2 +- .../contrib/civictheme/includes/skip_link.inc | 2 +- .../contrib/civictheme/includes/slider.inc | 8 +- .../contrib/civictheme/includes/snippet.inc | 6 +- .../civictheme/includes/social_links.inc | 24 +- .../civictheme/includes/system_branding.inc | 2 +- .../civictheme/includes/system_main_block.inc | 2 +- .../contrib/civictheme/includes/table.inc | 4 +- .../contrib/civictheme/includes/utilities.inc | 209 +-- .../contrib/civictheme/includes/views.inc | 17 +- .../contrib/civictheme/includes/webform.inc | 5 +- .../contrib/civictheme/includes/wysiwyg.inc | 2 +- .../civictheme/src/CivicthemeColorManager.php | 99 +- .../src/CivicthemeConfigImporter.php | 78 +- .../src/CivicthemeConfigManager.php | 28 +- .../civictheme/src/CivicthemePluginLoader.php | 17 +- .../src/CivicthemeSettingsFormManager.php | 20 +- .../src/CivicthemeStylesheetGenerator.php | 47 +- .../src/CivicthemeStylesheetParser.php | 18 +- .../civictheme/src/CivicthemeUpdateHelper.php | 19 +- .../civictheme/src/CivicthemeUtility.php | 27 +- .../src/CivicthemeVersionManager.php | 66 +- .../civictheme/src/Color/CivicthemeColor.php | 16 +- .../src/Color/CivicthemeColorFilterBase.php | 14 +- .../src/Color/CivicthemeColorShadeFilter.php | 6 +- .../src/Color/CivicthemeColorTintFilter.php | 6 +- .../src/Color/CivicthemeColorUtility.php | 18 +- .../src/Drush/Commands/CivicthemeCommands.php | 6 +- .../CivicthemeSettingsFormSectionAttached.php | 4 +- .../CivicthemeSettingsFormSectionBase.php | 52 +- .../CivicthemeSettingsFormSectionColors.php | 22 +- ...ivicthemeSettingsFormSectionComponents.php | 44 +- ...victhemeSettingsFormSectionInformation.php | 10 +- .../CivicthemeSettingsFormSectionOptout.php | 8 +- ...CivicthemeSettingsFormSectionProvision.php | 4 +- .../CivicthemeSettingsFormSectionReset.php | 20 +- ...CivicthemeSettingsFormSectionStorybook.php | 5 +- .../CivicthemeSettingsFormSectionVersion.php | 23 +- .../Functional/CivicthemeBrowserTestBase.php | 2 + .../CivicthemeInstallOptionalTest.php | 3 +- .../CivicthemeInstallRequiredTest.php | 3 +- .../Update/CivicthemeUpdatePathBareTest.php | 6 +- .../Update/CivicthemeUpdatePathFilledTest.php | 6 +- .../src/Traits/CivicthemeTestHelperTrait.php | 33 +- .../Unit/CivicthemeColorUtilityUnitTest.php | 22 +- .../src/Unit/CivicthemeHtmlLinkUnitTest.php | 12 +- .../src/Unit/CivicthemeUtilityUnitTest.php | 22 +- .../contrib/civictheme/theme-settings.php | 2 +- .../civictheme/theme-settings.provision.inc | 110 +- 166 files changed, 1946 insertions(+), 2669 deletions(-) create mode 100644 rector.php delete mode 100644 web/modules/custom/civictheme_dev/src/Helper.php diff --git a/.ahoy.yml b/.ahoy.yml index 9ddec9cf6..99e572c6d 100644 --- a/.ahoy.yml +++ b/.ahoy.yml @@ -164,13 +164,14 @@ commands: cmd: | ahoy cli vendor/bin/phpcs ahoy cli vendor/bin/phpstan + ahoy cli vendor/bin/rector process --dry-run . ahoy cli vendor/bin/phpmd . text phpmd.xml lint-fe: usage: Lint front-end code. cmd: | ahoy cli vendor/bin/twigcs - ahoy cli "npm run --prefix \${DREVOPS_WEBROOT}/themes/custom/\${DRUPAL_THEME} lint" + ahoy cli "npm run --prefix \${DREVOPS_WEBROOT}/themes/contrib/\${DRUPAL_THEME} lint" lint-config: usage: Lint config @@ -178,6 +179,12 @@ commands: ahoy cli ./scripts/lint-theme-config.sh ahoy cli "./vendor/bin/drush inspect_config civictheme.settings --detail --only-error" + lint-fix: + usage: Fix lint issues of back-end and front-end code. + cmd: | + ahoy cli vendor/bin/phpcbf + ahoy cli vendor/bin/rector process . + test: usage: Run all tests. cmd: ahoy test-unit && ahoy test-kernel && ahoy test-functional && ahoy test-bdd diff --git a/.circleci/config.yml b/.circleci/config.yml index c9c2fcab1..d94b345dc 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -163,6 +163,9 @@ job-build: &job-build - run: name: Lint code with PHPStan command: docker compose exec -T cli vendor/bin/phpstan || [ "${DREVOPS_CI_PHPSTAN_IGNORE_FAILURE:-0}" -eq 1 ] + - run: + name: Lint code with Rector + command: docker compose exec -T cli vendor/bin/rector process --dry-run . || [ "${DREVOPS_CI_RECTOR_IGNORE_FAILURE:-0}" -eq 1 ] - run: name: Lint code with PHPMD command: docker compose exec -T cli vendor/bin/phpmd . text phpmd.xml || [ "${DREVOPS_CI_PHPMD_IGNORE_FAILURE:-0}" -eq 1 ] diff --git a/composer.json b/composer.json index b865d033a..4a5d2b163 100644 --- a/composer.json +++ b/composer.json @@ -28,11 +28,13 @@ "drupal/core-dev": "^10", "drupal/drupal-extension": "^5@rc", "friendsoftwig/twigcs": "^6.2", - "mglaman/phpstan-drupal": "^1.1", + "mglaman/phpstan-drupal": "^1.2", + "palantirnet/drupal-rector": "dev-main", "php-parallel-lint/php-parallel-lint": "^1.3", "phpcompatibility/php-compatibility": "^9.3", "phpmd/phpmd": "^2.13", "phpspec/prophecy-phpunit": "^2.0", + "phpstan/extension-installer": "^1.3", "pyrech/composer-changelogs": "^1.8" }, "autoload": { diff --git a/composer.lock b/composer.lock index 33bd66ae7..6fba41ae5 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "8544cd69d35924eab203a25674e31a20", + "content-hash": "f994b8b1314a70aa075d43a78edb82f2", "packages": [ { "name": "asm89/stack-cors", @@ -17702,16 +17702,16 @@ }, { "name": "mglaman/phpstan-drupal", - "version": "1.2.0", + "version": "1.2.1", "source": { "type": "git", "url": "https://github.com/mglaman/phpstan-drupal.git", - "reference": "d721420086f146640acecebb7a678661a66e97d5" + "reference": "920c6b972a832046327f66dc6ff7448e3b5d6e4c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/mglaman/phpstan-drupal/zipball/d721420086f146640acecebb7a678661a66e97d5", - "reference": "d721420086f146640acecebb7a678661a66e97d5", + "url": "https://api.github.com/repos/mglaman/phpstan-drupal/zipball/920c6b972a832046327f66dc6ff7448e3b5d6e4c", + "reference": "920c6b972a832046327f66dc6ff7448e3b5d6e4c", "shasum": "" }, "require": { @@ -17786,7 +17786,7 @@ "description": "Drupal extension and rules for PHPStan", "support": { "issues": "https://github.com/mglaman/phpstan-drupal/issues", - "source": "https://github.com/mglaman/phpstan-drupal/tree/1.2.0" + "source": "https://github.com/mglaman/phpstan-drupal/tree/1.2.1" }, "funding": [ { @@ -17802,7 +17802,7 @@ "type": "tidelift" } ], - "time": "2023-08-24T20:32:56+00:00" + "time": "2023-11-03T13:17:28+00:00" }, { "name": "mikey179/vfsstream", @@ -17914,6 +17914,83 @@ ], "time": "2023-03-08T13:26:56+00:00" }, + { + "name": "palantirnet/drupal-rector", + "version": "dev-main", + "source": { + "type": "git", + "url": "https://github.com/palantirnet/drupal-rector.git", + "reference": "0baf78cb691d959932a3168e172dc258a4010132" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/palantirnet/drupal-rector/zipball/0baf78cb691d959932a3168e172dc258a4010132", + "reference": "0baf78cb691d959932a3168e172dc258a4010132", + "shasum": "" + }, + "require": { + "rector/rector": "~0.18.0", + "webflo/drupal-finder": "^1.2" + }, + "replace": { + "drupal8-rector/drupal8-rector": "*", + "palantirnet/drupal8-rector": "*" + }, + "require-dev": { + "cweagans/composer-patches": "^1.7.2", + "php": "^8.1", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpunit/phpunit": "^10.0", + "symfony/yaml": "^5 || ^6", + "symplify/vendor-patches": "^11.0" + }, + "default-branch": true, + "type": "library", + "extra": { + "enable-patching": true + }, + "autoload": { + "psr-4": { + "DrupalRector\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dezső Biczó", + "email": "mxr576@gmail.com" + }, + { + "name": "Ofer Shaal", + "email": "shaal@palantir.net" + }, + { + "name": "Daniel Montgomery", + "email": "montgomery@palantir.net" + }, + { + "name": "Matt Glaman", + "email": "nmd.matt@gmail.com" + } + ], + "description": "Instant fixes for your Drupal code by using Rector.", + "keywords": [ + "Code style", + "Drupal 8", + "ast", + "drupal 9", + "rector" + ], + "support": { + "source": "https://github.com/palantirnet/drupal-rector/tree/main" + }, + "time": "2023-11-05T13:59:29+00:00" + }, { "name": "pdepend/pdepend", "version": "2.15.1", @@ -18672,16 +18749,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.10.40", + "version": "1.10.41", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "93c84b5bf7669920d823631e39904d69b9c7dc5d" + "reference": "c6174523c2a69231df55bdc65b61655e72876d76" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/93c84b5bf7669920d823631e39904d69b9c7dc5d", - "reference": "93c84b5bf7669920d823631e39904d69b9c7dc5d", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/c6174523c2a69231df55bdc65b61655e72876d76", + "reference": "c6174523c2a69231df55bdc65b61655e72876d76", "shasum": "" }, "require": { @@ -18730,7 +18807,7 @@ "type": "tidelift" } ], - "time": "2023-10-30T14:48:31+00:00" + "time": "2023-11-05T12:57:57+00:00" }, { "name": "phpstan/phpstan-deprecation-rules", @@ -19383,6 +19460,62 @@ ], "time": "2023-07-11T16:12:49+00:00" }, + { + "name": "rector/rector", + "version": "0.18.6", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "02041b220704b9cbe075f0310d0954b2fda5c40c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/02041b220704b9cbe075f0310d0954b2fda5c40c", + "reference": "02041b220704b9cbe075f0310d0954b2fda5c40c", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0", + "phpstan/phpstan": "^1.10.35" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "bin": [ + "bin/rector" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/0.18.6" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2023-10-24T15:00:59+00:00" + }, { "name": "sebastian/cli-parser", "version": "1.0.1", @@ -21410,6 +21543,7 @@ "minimum-stability": "dev", "stability-flags": { "drupal/drupal-extension": 5, + "palantirnet/drupal-rector": 20, "drupal/components": 10, "drupal/linkit": 10, "drupal/default_content": 15 diff --git a/docs/development.md b/docs/development.md index 395ee60ba..fa2d5e257 100644 --- a/docs/development.md +++ b/docs/development.md @@ -14,7 +14,7 @@ Before starting, ensure you have reviewed the documentation for The following steps outline the build process: -1. Construct a fresh Drupal 9 site from the GovCMS Drupal profile. Utilize +1. Construct a fresh Drupal 10 site from the GovCMS Drupal profile. Utilize `ahoy install-site` for a rebuild. 2. Activate additional modules needed for development by installing the `civictheme_dev` module. @@ -34,7 +34,7 @@ the profile, following the order of their numbering. By default, the site: -- Installs Drupal 9. +- Installs Drupal 10. - Installs the `govcms` profile. - Installs the CivicTheme Drupal theme. - Creates and installs the CivicTheme Demo sub-theme. diff --git a/phpstan.neon b/phpstan.neon index c1aa12bcc..05b400118 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -28,6 +28,10 @@ parameters: drupal: drupal_root: web + # Do not report on ignored errors that do not occur in the results. This is + # required to allow code generated by a sub-theme to be ignored. + reportUnmatchedIgnoredErrors: false + ignoreErrors: - # Since tests and data providers do not have to have parameter docblocks, @@ -35,9 +39,7 @@ parameters: # this error. message: '#.*no value type specified in iterable type array.#' paths: - - web/modules/custom/*/tests/* - - web/themes/custom/*/tests/* - - web/themes/contrib/civictheme/*/tests/* + - web/themes/contrib/civictheme/tests/* - tests/phpunit/* - # Hook implementations do not provide docblocks for parameters, so there @@ -52,3 +54,19 @@ parameters: message: '#Variable .* might not be defined.#' paths: - web/sites/default/includes + - + # Allow using Drupal::service() in tests and Drush commands. + message: '#\Drupal calls should be avoided in classes, use dependency injection instead#' + paths: + - web/themes/contrib/civictheme/src/Drush/Commands + - tests/behat + - + # Allow using direct callable calls for generated content. + message: '#Parameter \#1 \$callback of function call_user_func expects callable.*#' + paths: + - web/modules/custom/cs_generated_content/src/CsGeneratedContentCivicthemeTrait.php + - + # Allow using direct assignment to fields. + message: '#Property.*does not accept.*#' + paths: + - web/themes/contrib/civictheme/ diff --git a/rector.php b/rector.php new file mode 100644 index 000000000..6c53dfe4a --- /dev/null +++ b/rector.php @@ -0,0 +1,65 @@ +sets([ + // Provided by Rector. + SetList::TYPE_DECLARATION, + // Provided by Drupal Rector. + Drupal8SetList::DRUPAL_8, + Drupal9SetList::DRUPAL_9, + ]); + + $drupalFinder = new DrupalFinder(); + $drupalFinder->locateRoot(__DIR__); + $drupalRoot = $drupalFinder->getDrupalRoot(); + $rectorConfig->autoloadPaths([ + $drupalRoot . '/core', + $drupalRoot . '/modules', + $drupalRoot . '/themes', + $drupalRoot . '/profiles', + ]); + + $rectorConfig->skip([ + // Dependencies. + '*/vendor/*', + '*/node_modules/*', + // Core and contribs. + '*/core/*', + '*/modules/contrib/*', + '*/profiles/contrib/*', + '*/sites/simpletest/*', + '*/sites/default/files/*', + // Composer scripts. + '*/scripts/composer/*', + ]); + + $rectorConfig->fileExtensions([ + 'engine', + 'inc', + 'install', + 'module', + 'php', + 'profile', + 'theme', + ]); + + $rectorConfig->importNames(TRUE, FALSE); + $rectorConfig->importShortClasses(FALSE); +}; diff --git a/scripts/drevops/build.sh b/scripts/drevops/build.sh index bdc664a72..fc1457a73 100755 --- a/scripts/drevops/build.sh +++ b/scripts/drevops/build.sh @@ -130,6 +130,7 @@ docker compose cp -L phpcs.xml cli:/app/ 2>"${composer_verbose_output}" docker compose cp -L phpmd.xml cli:/app/ 2>"${composer_verbose_output}" docker compose cp -L phpstan.neon cli:/app/ 2>"${composer_verbose_output}" docker compose cp -L phpunit.xml cli:/app/ 2>"${composer_verbose_output}" +docker compose cp -L rector.php cli:/app/ 2>"${composer_verbose_output}" docker compose cp -L tests cli:/app/ 2>"${composer_verbose_output}" docker compose cp -L .circleci cli:/app/ 2>"${composer_verbose_output}" diff --git a/tests/behat/bootstrap/FeatureContext.php b/tests/behat/bootstrap/FeatureContext.php index 4d4b8c2f1..62046147d 100644 --- a/tests/behat/bootstrap/FeatureContext.php +++ b/tests/behat/bootstrap/FeatureContext.php @@ -7,6 +7,8 @@ use Behat\Gherkin\Node\TableNode; use Behat\Mink\Driver\Selenium2Driver; +use Behat\Mink\Element\DocumentElement; +use Behat\Mink\Element\NodeElement; use Behat\Mink\Exception\ElementNotFoundException; use DrevOps\BehatSteps\ContentTrait; use DrevOps\BehatSteps\DateTrait; @@ -35,6 +37,9 @@ /** * Defines application features from the specific context. + * + * @SuppressWarnings(PHPMD.TooManyPublicMethods) + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ class FeatureContext extends DrupalContext { @@ -63,7 +68,7 @@ class FeatureContext extends DrupalContext { * * @Then I see content in iframe with id :id */ - public function iSeeContentInIframe($id) { + public function iSeeContentInIframe(string $id): void { $driver = $this->getSession()->getDriver(); if (!$driver instanceof Selenium2Driver) { throw new \RuntimeException('Unsupported driver for this step'); @@ -85,7 +90,8 @@ public function iSeeContentInIframe($id) { throw new ElementNotFoundException($driver, 'iFrame', $id); } - $driver->switchToIFrame($index); + // @phpstan-ignore-next-line + $driver->switchToIFrame((int) $index); if (!$driver->find('//body')) { throw new \Exception(sprintf('The contents of the iFrame with id "%s" was not loaded', $id)); @@ -100,14 +106,14 @@ public function iSeeContentInIframe($id) { * * @When I select the filter chip :label */ - public function iSelectFilterChip($label) { + public function iSelectFilterChip(string $label): void { $element = $this->getSession()->getPage(); $filter_chip = $element->find('named', [ 'radio', - $this->getSession()->getSelectorsHandler()->xpathLiteral($label), + $label, ]); if ($filter_chip === NULL) { - throw new \Exception(sprintf('The filter chip with "%s" was not found on the page %s', $label, $this->getSession()->getCurrentUrl())); + throw new \Exception(sprintf('The filter chip with "%s" was not found on the page %s.', $label, $this->getSession()->getCurrentUrl())); } $this->clickFilterChip($label, $filter_chip, $element); @@ -118,23 +124,22 @@ public function iSelectFilterChip($label) { * * @Given I check the filter chip :label */ - public function assertCheckFilterChip($label) { + public function assertCheckFilterChip(string $label): void { $element = $this->getSession()->getPage(); $filter_chip = $element->find('named', [ 'checkbox', - $this->getSession()->getSelectorsHandler()->xpathLiteral($label), + $label, ]); if ($filter_chip === NULL) { - throw new \Exception(sprintf('The filter chip with "%s" was not found on the page %s', $label, $this->getSession()->getCurrentUrl())); + throw new \Exception(sprintf('The filter chip with "%s" was not found on the page %s.', $label, $this->getSession()->getCurrentUrl())); } if ($filter_chip->isChecked()) { - throw new \Exception(sprintf('Cannot check filter chip with "%s" because it already checked', $label, $this->getSession()->getCurrentUrl())); + throw new \Exception(sprintf('Cannot check filter chip with "%s" because it already checked on the page %s.', $label, $this->getSession()->getCurrentUrl())); } $this->clickFilterChip($label, $filter_chip, $element); - } /** @@ -142,33 +147,33 @@ public function assertCheckFilterChip($label) { * * @Given I uncheck the filter chip :checkbox */ - public function assertUncheckFilterChip($label) { - $element = $this->getSession()->getPage(); - $filter_chip = $element->find('named', [ + public function assertUncheckFilterChip(string $label): void { + $page = $this->getSession()->getPage(); + $filter_chip = $page->find('named', [ 'checkbox', - $this->getSession()->getSelectorsHandler()->xpathLiteral($label), + $label, ]); if ($filter_chip === NULL) { - throw new \Exception(sprintf('The filter chip with "%s" was not found on the page %s', $label, $this->getSession()->getCurrentUrl())); + throw new \Exception(sprintf('The filter chip with "%s" was not found on the page %s.', $label, $this->getSession()->getCurrentUrl())); } if (!$filter_chip->isChecked()) { - throw new \Exception(sprintf('Cannot uncheck filter chip with "%s" because it not checked', $label, $this->getSession()->getCurrentUrl())); + throw new \Exception(sprintf('Cannot uncheck filter chip with "%s" because it not checked on the page %s.', $label, $this->getSession()->getCurrentUrl())); } - $this->clickFilterChip($label, $filter_chip, $element); + $this->clickFilterChip($label, $filter_chip, $page); } /** * Helper to get the filter chip label element which is then clicked. */ - protected function clickFilterChip($label, $filter_chip, $element) { + protected function clickFilterChip(string $label, NodeElement $filter_chip, DocumentElement $page): void { $filter_chip_id = $filter_chip->getAttribute('id'); - $label_element = $element->find('css', "label[for='$filter_chip_id']"); - $labelonpage = $label_element->getText(); - if ($label != $labelonpage) { - throw new \Exception(sprintf("Filter chip with id '%s' has label '%s' instead of '%s' on the page %s", $filter_chip_id, $labelonpage, $label, $this->getSession()->getCurrentUrl())); + $label_element = $page->find('css', "label[for='$filter_chip_id']"); + $label_on_page = $label_element->getText(); + if ($label != $label_on_page) { + throw new \Exception(sprintf("Filter chip with id '%s' has label '%s' instead of '%s' on the page %s", $filter_chip_id, $label_on_page, $label, $this->getSession()->getCurrentUrl())); } $label_element->click(); @@ -184,8 +189,10 @@ protected function clickFilterChip($label, $filter_chip, $element) { * | ... | ... | * * @When :field_name in :bundle :entity_type parent :parent_entity_field in :parent_entity_bundle :parent_entity_type with :parent_entity_field_name of :parent_entity_field_identifer delta :delta has :paragraph_type paragraph: + * + * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ - public function paragraphsAddToParentEntityWithFields($field_name, $bundle, $entity_type, $parent_entity_field, $parent_entity_bundle, $parent_entity_type, $parent_entity_field_name, $parent_entity_field_identifer, $delta, $paragraph_type, TableNode $fields) { + public function paragraphsAddToParentEntityWithFields(string $field_name, string $bundle, string $entity_type, string $parent_entity_field, string $parent_entity_bundle, string $parent_entity_type, string $parent_entity_field_name, string $parent_entity_field_identifer, int $delta, string $paragraph_type, TableNode $fields): void { // Get paragraph field name for this entity type. $paragraph_node_field_name = $this->paragraphsCheckEntityFieldName($entity_type, $bundle, $field_name); @@ -221,7 +228,7 @@ public function paragraphsAddToParentEntityWithFields($field_name, $bundle, $ent * * @Then /^I scroll to an? element with id "([^"]*)"$/ */ - public function iScrollToElementWithId($id) { + public function iScrollToElementWithId(string $id): void { $this->getSession()->executeScript(" var element = document.getElementById('" . $id . "'); element.scrollIntoView( true ); @@ -244,19 +251,17 @@ public function iScrollToElementWithId($id) { * * @todo Remove with next behat-steps release. */ - public function linkAssertTextHrefNotExists($text, $href, $locator = NULL) { + public function linkAssertTextHrefNotExists(string $text, string $href, string $locator = NULL): void { /** @var \Behat\Mink\Element\DocumentElement $page */ $page = $this->getSession()->getPage(); + $element = $page; if ($locator) { $element = $page->find('css', $locator); if (!$element) { return; } } - else { - $element = $page; - } $link = $element->findLink($text); if (!$link) { @@ -284,7 +289,7 @@ public function linkAssertTextHrefNotExists($text, $href, $locator = NULL) { * @When /^(?:|I )fill color in "(?P(?:[^"]|\\")*)" with:$/ * @When /^(?:|I )fill color in "(?P(?:[^"]|\\")*)" for "(?P(?:[^"]|\\")*)"$/ */ - public function fillColorField($field, $value) { + public function fillColorField(string $field, string $value): mixed { $js = sprintf( 'jQuery("%s").val("%s").change();', $field, @@ -299,7 +304,7 @@ public function fillColorField($field, $value) { * * @Then /^color field "(?P(?:[^"]|\\")*)" value is "(?P(?:[^"]|\\")*)"$/ */ - public function assertColorFieldHasValue($field, $value) { + public function assertColorFieldHasValue(string $field, string $value): void { $js = sprintf('jQuery("%s").val();', $field); $actual = $this->getSession()->evaluateScript($js); @@ -314,7 +319,7 @@ public function assertColorFieldHasValue($field, $value) { * * @When I install :name theme */ - public function installTheme($name) { + public function installTheme(string $name): void { \Drupal::service('theme_installer')->install([$name]); } @@ -323,7 +328,7 @@ public function installTheme($name) { * * @When I uninstall :name theme */ - public function uninstallTheme($name) { + public function uninstallTheme(string $name): void { try { \Drupal::service('theme_installer')->uninstall([$name]); } @@ -337,7 +342,7 @@ public function uninstallTheme($name) { * * @When I set :name theme as default */ - public function setThemeAsDefault($name) { + public function setThemeAsDefault(string $name): void { \Drupal::service('config.factory')->getEditable('system.theme') ->set('default', $name) ->save(); @@ -347,8 +352,10 @@ public function setThemeAsDefault($name) { * Visit a settings page of the theme. * * @When I visit :name theme settings page + * + * @SuppressWarnings(PHPMD.StaticAccess) */ - public function themeVisitSettings($name = NULL) { + public function themeVisitSettings(string $name = NULL): void { if (!$name || $name == 'current') { $name = \Drupal::theme()->getActiveTheme()->getName(); } @@ -373,7 +380,7 @@ public function themeVisitSettings($name = NULL) { * * @Given no :menu_name menu_links: */ - public function menuLinksDelete($menu_name, TableNode $table) { + public function menuLinksDelete(string $menu_name, TableNode $table): void { foreach ($table->getColumn(0) as $title) { try { $menu_link = $this->loadMenuLinkByTitle($title, $menu_name); @@ -397,7 +404,7 @@ public function menuLinksDelete($menu_name, TableNode $table) { * * @Given no blocks: */ - public function blockDelete(TableNode $table) { + public function blockDelete(TableNode $table): void { foreach ($table->getColumn(0) as $id) { try { $block = \Drupal::entityTypeManager() @@ -426,7 +433,7 @@ public function blockDelete(TableNode $table) { * * @Given no content blocks: */ - public function contentBlockDelete(TableNode $table) { + public function contentBlockDelete(TableNode $table): void { foreach ($table->getColumn(0) as $info) { try { $entities = \Drupal::entityTypeManager() @@ -450,8 +457,10 @@ public function contentBlockDelete(TableNode $table) { * Index a node with all Search API indices. * * @When I index :type :title for search + * + * @SuppressWarnings(PHPMD.StaticAccess) */ - public function searchApiIndexContent($type, $title) { + public function searchApiIndexContent(string $type, string $title): void { $nids = $this->contentNodeLoadMultiple($type, [ 'title' => $title, ]); @@ -487,7 +496,7 @@ public function searchApiIndexContent($type, $title) { * * @When /^(?:|I )fill in WYSIWYG "(?P(?:[^"]|\\")*)" with "(?P(?:[^"]|\\")*)"$/ */ - public function wysiwygFillField($field, $value) { + public function wysiwygFillField(string $field, string $value): void { $field = $this->wysiwygFixStepArgument($field); $value = $this->wysiwygFixStepArgument($value); diff --git a/tests/behat/features/theme.settings.components.feature b/tests/behat/features/theme.settings.components.feature index 2d62a8046..46cdccdb2 100644 --- a/tests/behat/features/theme.settings.components.feature +++ b/tests/behat/features/theme.settings.components.feature @@ -217,7 +217,7 @@ Feature: Components settings are available in the theme settings And I check the box "Confirm settings reset" And I press "reset_to_defaults" Then I should see the text "Theme configuration was reset to defaults." - + @api Scenario: The CivicTheme theme settings verify custom logo configuration with SVG image upload Given I am logged in as a user with the "Site Administrator" role diff --git a/tests/phpunit/AddPhpcsExclusionsUnitTest.php b/tests/phpunit/AddPhpcsExclusionsUnitTest.php index 82bea635b..709bbe2ad 100644 --- a/tests/phpunit/AddPhpcsExclusionsUnitTest.php +++ b/tests/phpunit/AddPhpcsExclusionsUnitTest.php @@ -22,7 +22,7 @@ class AddPhpcsExclusionsUnitTest extends ScriptUnitTestBase { * @dataProvider dataProviderMain * @runInSeparateProcess */ - public function testMain($args, $expected_code, $expected_output) { + public function testMain(string|array $args, int $expected_code, string $expected_output): void { $args = is_array($args) ? $args : [$args]; $result = $this->runScript($args, TRUE); @@ -30,7 +30,7 @@ public function testMain($args, $expected_code, $expected_output) { $this->assertStringContainsString($expected_output, $result['output']); } - public function dataProviderMain() { + public function dataProviderMain(): array { return [ [ '--help', diff --git a/tests/phpunit/CivicthemeCreateSubthemeScriptUnitTest.php b/tests/phpunit/CivicthemeCreateSubthemeScriptUnitTest.php index eae57cefa..71a7aafaa 100644 --- a/tests/phpunit/CivicthemeCreateSubthemeScriptUnitTest.php +++ b/tests/phpunit/CivicthemeCreateSubthemeScriptUnitTest.php @@ -29,14 +29,14 @@ class CivicthemeCreateSubthemeScriptUnitTest extends ScriptUnitTestBase { * @dataProvider dataProviderMain * @runInSeparateProcess */ - public function testMain($args, $expected_code, $expected_output) { + public function testMain(string|array $args, int $expected_code, string $expected_output): void { $args = is_array($args) ? $args : [$args]; $result = $this->runScript($args, TRUE); $this->assertEquals($expected_code, $result['code']); $this->assertStringContainsString($expected_output, $result['output']); } - public function dataProviderMain() { + public function dataProviderMain(): array { return [ [ '--help', @@ -80,13 +80,13 @@ public function dataProviderMain() { * @dataProvider dataProviderTestLocation * @runInSeparateProcess */ - public function testLocation($civictheme_dir, $newtheme_rel_dir, $expected_newtheme_dir, $expected_rel_path) { + public function testLocation(string $civictheme_dir, string $newtheme_rel_dir, string $expected_newtheme_dir, string $expected_rel_path): void { $newtheme_name = 'new_theme'; $sut_dir = $this->prepareSut($civictheme_dir); $composerjson_file = $sut_dir . '/composer.json'; - $composerjson = json_decode(file_get_contents($composerjson_file), TRUE); + $composerjson = json_decode((string) file_get_contents($composerjson_file), TRUE); $composerjson['version'] = '9.8.7'; $composerjson['homepage'] = 'https://example.com/composer'; $composerjson['support']['issues'] = 'https://example.com/composer/issues'; @@ -94,7 +94,7 @@ public function testLocation($civictheme_dir, $newtheme_rel_dir, $expected_newth file_put_contents($composerjson_file, json_encode($composerjson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); $packagejson_file = $sut_dir . '/package.json'; - $packagejson = json_decode(file_get_contents($packagejson_file), TRUE); + $packagejson = json_decode((string) file_get_contents($packagejson_file), TRUE); $packagejson['version'] = '6.5.4'; $packagejson['homepage'] = 'https://example.com/package'; $packagejson['bugs'] = 'https://example.com/package/issues'; @@ -135,18 +135,18 @@ public function testLocation($civictheme_dir, $newtheme_rel_dir, $expected_newth $this->assertFileExists($expected_new_theme_dir_full . 'README.md'); $this->assertFileExists($expected_new_theme_dir_full . 'screenshot.png'); - $this->assertStringContainsString($expected_rel_path, file_get_contents($expected_new_theme_dir_full . 'gulpfile.js')); - $this->assertStringContainsString($expected_rel_path, file_get_contents($expected_new_theme_dir_full . 'webpack/webpack.common.js')); - $this->assertStringContainsString($expected_rel_path, file_get_contents($expected_new_theme_dir_full . 'webpack/theme_js.js')); - $this->assertStringContainsString($expected_rel_path, file_get_contents($expected_new_theme_dir_full . 'package.json')); + $this->assertStringContainsString($expected_rel_path, (string) file_get_contents($expected_new_theme_dir_full . 'gulpfile.js')); + $this->assertStringContainsString($expected_rel_path, (string) file_get_contents($expected_new_theme_dir_full . 'webpack/webpack.common.js')); + $this->assertStringContainsString($expected_rel_path, (string) file_get_contents($expected_new_theme_dir_full . 'webpack/theme_js.js')); + $this->assertStringContainsString($expected_rel_path, (string) file_get_contents($expected_new_theme_dir_full . 'package.json')); - $composerjson_actual = json_decode(file_get_contents($expected_new_theme_dir_full . 'composer.json'), TRUE); + $composerjson_actual = json_decode((string) file_get_contents($expected_new_theme_dir_full . 'composer.json'), TRUE); $this->assertStringContainsString($composerjson['version'], $composerjson_actual['extra']['civictheme']['version']); $this->assertStringContainsString($composerjson['homepage'], $composerjson_actual['extra']['civictheme']['homepage']); $this->assertStringContainsString($composerjson['support']['issues'], $composerjson_actual['extra']['civictheme']['support']['issues']); $this->assertStringContainsString($composerjson['support']['source'], $composerjson_actual['extra']['civictheme']['support']['source']); - $packagejson_actual = json_decode(file_get_contents($expected_new_theme_dir_full . 'package.json'), TRUE); + $packagejson_actual = json_decode((string) file_get_contents($expected_new_theme_dir_full . 'package.json'), TRUE); $this->assertStringContainsString($packagejson['version'], $packagejson_actual['civictheme']['version']); $this->assertStringContainsString($packagejson['homepage'], $packagejson_actual['civictheme']['homepage']); $this->assertStringContainsString($packagejson['bugs'], $packagejson_actual['civictheme']['bugs']); @@ -158,7 +158,7 @@ public function testLocation($civictheme_dir, $newtheme_rel_dir, $expected_newth $this->assertDirectoryExists($expected_new_theme_dir_full . 'components/03-organisms/header'); } - public function dataProviderTestLocation() { + public function dataProviderTestLocation(): array { return [ // CivicTheme in 'contrib', new theme in 'custom' dir. // No new_theme_directory specified - use default one. @@ -209,7 +209,7 @@ public function dataProviderTestLocation() { /** * @runInSeparateProcess */ - public function testExamplesRemoval() { + public function testExamplesRemoval(): void { $civictheme_dir = 'web/themes/contrib/civictheme'; $newtheme_rel_dir = ''; $newtheme_name = 'new_theme'; @@ -252,7 +252,7 @@ public function testExamplesRemoval() { $this->assertFileExists($expected_new_theme_dir_full . 'README.md'); $this->assertFileExists($expected_new_theme_dir_full . 'screenshot.png'); - $this->assertStringContainsString($expected_rel_path, file_get_contents($expected_new_theme_dir_full . 'gulpfile.js')); + $this->assertStringContainsString($expected_rel_path, (string) file_get_contents($expected_new_theme_dir_full . 'gulpfile.js')); // Examples assertions. $this->assertDirectoryDoesNotExist($expected_new_theme_dir_full . 'components/01-atoms/demo-button'); @@ -269,7 +269,7 @@ public function testExamplesRemoval() { * @return string * Path to created SUT codebase. */ - protected function prepareSut($path = NULL) { + protected function prepareSut($path = NULL): string { $sut_dir = $this->tmpDir . (!empty($path) ? '/' . $path : ''); mkdir($sut_dir, 0755, TRUE); @@ -289,11 +289,11 @@ protected function prepareSut($path = NULL) { * @dataProvider dataProviderFileGetRelativeDir * @runInSeparateProcess */ - public function testFileGetRelativeDir($from, $to, $expected) { + public function testFileGetRelativeDir(string $from, string $to, string $expected): void { $this->assertEquals($expected, file_get_relative_dir($from, $to)); } - public function dataProviderFileGetRelativeDir() { + public function dataProviderFileGetRelativeDir(): array { return [ ['/a/b/c/d', '/a/b/c/d', './'], ['/a/b/c/d', '/a/b/c', '../'], @@ -319,11 +319,11 @@ public function dataProviderFileGetRelativeDir() { * @dataProvider dataProviderFilePathCanonicalize * @runInSeparateProcess */ - public function testFilePathCanonicalize($path, $expected) { + public function testFilePathCanonicalize(string $path, string $expected): void { $this->assertEquals($expected, file_path_canonicalize($path)); } - public function dataProviderFilePathCanonicalize() { + public function dataProviderFilePathCanonicalize(): array { return [ ['', ''], ['a', 'a'], diff --git a/tests/phpunit/Drupal/SettingsTestCase.php b/tests/phpunit/Drupal/SettingsTestCase.php index 6b84c4cee..44d3060a7 100644 --- a/tests/phpunit/Drupal/SettingsTestCase.php +++ b/tests/phpunit/Drupal/SettingsTestCase.php @@ -161,7 +161,7 @@ protected function setEnvVars(array $vars): void { protected static function getRealEnvVarsFilteredNoValues(array $prefixes = []): array { $vars = getenv(); - $vars = array_filter(array_keys($vars), function ($key) use ($prefixes) { + $vars = array_filter(array_keys($vars), function ($key) use ($prefixes): bool { foreach ($prefixes as $prefix) { if (str_starts_with($key, $prefix)) { return TRUE; diff --git a/tests/phpunit/ExtractCssColorsToCsvScriptUnitTest.php b/tests/phpunit/ExtractCssColorsToCsvScriptUnitTest.php index da41a7e80..d915d51c3 100644 --- a/tests/phpunit/ExtractCssColorsToCsvScriptUnitTest.php +++ b/tests/phpunit/ExtractCssColorsToCsvScriptUnitTest.php @@ -22,14 +22,14 @@ class ExtractCssColorsToCsvScriptUnitTest extends ScriptUnitTestBase { * @dataProvider dataProviderMain * @runInSeparateProcess */ - public function testMain($args, $expected_code, $expected_output) { + public function testMain(string|array $args, int $expected_code, string $expected_output): void { $args = is_array($args) ? $args : [$args]; $result = $this->runScript($args, TRUE); $this->assertEquals($expected_code, $result['code']); $this->assertStringContainsString($expected_output, $result['output']); } - public function dataProviderMain() { + public function dataProviderMain(): array { return [ [ '--help', @@ -75,11 +75,11 @@ public function dataProviderMain() { * @dataProvider dataProviderCollectVariables * @runInSeparateProcess */ - public function testCollectVariables($content, $expected) { + public function testCollectVariables(string $content, array $expected): void { $this->assertEquals($expected, collect_variables($content)); } - public function dataProviderCollectVariables() { + public function dataProviderCollectVariables(): array { return [ ['', []], // Valid - single. @@ -193,7 +193,7 @@ public function dataProviderCollectVariables() { * @dataProvider dataProviderParseVariableName * @runInSeparateProcess */ - public function testParseVariableName($name, $prefix, $expected, $expectExceptionMessage = FALSE) { + public function testParseVariableName(string $name, string $prefix, string|array $expected, string $expectExceptionMessage = NULL): void { if ($expectExceptionMessage) { $this->expectException(\Exception::class); $this->expectExceptionMessage($expectExceptionMessage); @@ -202,7 +202,7 @@ public function testParseVariableName($name, $prefix, $expected, $expectExceptio $this->assertEquals($expected, parse_variable_name($name, $prefix)); } - public function dataProviderParseVariableName() { + public function dataProviderParseVariableName(): array { return [ ['', '', '', 'Empty name provided.'], diff --git a/tests/phpunit/ScriptUnitTestBase.php b/tests/phpunit/ScriptUnitTestBase.php index f80f5fdda..bdc46294f 100644 --- a/tests/phpunit/ScriptUnitTestBase.php +++ b/tests/phpunit/ScriptUnitTestBase.php @@ -8,6 +8,8 @@ * Base class to unit tests scripts. * * @group scripts + * + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) */ abstract class ScriptUnitTestBase extends TestCase { @@ -43,10 +45,12 @@ protected function setUp(): void { /** * {@inheritdoc} + * + * @SuppressWarnings(PHPMD.ErrorControlOperator) */ protected function tearDown(): void { parent::tearDown(); - if (!empty($this->tmpDir)) { + if (!empty($this->tmpDir) && is_dir($this->tmpDir)) { @unlink($this->tmpDir); } } @@ -63,6 +67,8 @@ protected function tearDown(): void { * Array with the following keys: * - code: (int) Exit code. * - output: (string) Output. + * + * @SuppressWarnings(PHPMD.BooleanArgumentFlag) */ protected function runScript(array $args = [], $verbose = FALSE) { putenv('SCRIPT_RUN_SKIP=0'); @@ -83,7 +89,7 @@ protected function runScript(array $args = [], $verbose = FALSE) { /** * Replace path to a fixture file. */ - protected function fixtureFile($filename) { + protected function fixtureFile(string $filename): string { $path = 'tests/phpunit/fixtures/drupal_configs/' . $filename; if (!is_readable($path)) { throw new \RuntimeException(sprintf('Unable to find fixture file %s.', $path)); @@ -95,14 +101,14 @@ protected function fixtureFile($filename) { /** * Path to a temporary file. */ - protected function toTmpPath($filename, $prefix = NULL) { + protected function toTmpPath(string $filename, string $prefix = NULL): string { return $prefix ? $this->tmpDir . DIRECTORY_SEPARATOR . $prefix . DIRECTORY_SEPARATOR . $filename : $this->tmpDir . DIRECTORY_SEPARATOR . $filename; } /** * Print the contents of the temporary directory. */ - protected function printTempDir() { + protected function printTempDir(): void { $it = new RecursiveTreeIterator(new RecursiveDirectoryIterator($this->tmpDir, RecursiveDirectoryIterator::SKIP_DOTS)); print PHP_EOL; foreach ($it as $value) { @@ -113,7 +119,7 @@ protected function printTempDir() { /** * Create a random unique temporary directory. */ - protected function tempdir($dir = NULL, $prefix = 'tmp_', $mode = 0700, $max_attempts = 1000) { + protected function tempdir(string $dir = NULL, string $prefix = 'tmp_', int $mode = 0700, int $max_attempts = 1000): string { if (is_null($dir)) { $dir = sys_get_temp_dir(); } @@ -121,11 +127,11 @@ protected function tempdir($dir = NULL, $prefix = 'tmp_', $mode = 0700, $max_att $dir = rtrim($dir, DIRECTORY_SEPARATOR); if (!is_dir($dir) || !is_writable($dir)) { - return FALSE; + throw new \RuntimeException(sprintf('Temporary directory "%s" does not exist or is not writable.', $dir)); } if (strpbrk($prefix, '\\/:*?"<>|') !== FALSE) { - return FALSE; + throw new \RuntimeException(sprintf('Prefix "%s" contains invalid characters.', $prefix)); } $attempts = 0; @@ -143,12 +149,12 @@ protected function tempdir($dir = NULL, $prefix = 'tmp_', $mode = 0700, $max_att /** * Recursively replace a value in the array using provided callback. */ - protected function arrayReplaceValue($array, $cb) { + protected function arrayReplaceValue(array $array, callable|array $cb): array { foreach ($array as $k => $item) { if (is_array($item)) { $array[$k] = $this->arrayReplaceValue($item, $cb); } - else { + elseif (is_callable($cb)) { $array[$k] = $cb($item); } } @@ -171,7 +177,7 @@ protected function arrayReplaceValue($array, $cb) { * - key: (string) Source path (the key from $file_structure). * - value: (string) Path to a fixture file to use. */ - protected function createTmpFilesFromFixtures(array $fixture_map, $prefix = NULL) { + protected function createTmpFilesFromFixtures(array $fixture_map, string $prefix = NULL): array { $files = []; foreach ($fixture_map as $path => $fixture_file) { $tmp_path = $this->toTmpPath($path, $prefix); @@ -217,8 +223,10 @@ protected function createTmpFilesFromFixtures(array $fixture_map, $prefix = NULL * Array of created files with the following structure: * - key: (string) Source path (the key from $file_structure). * - value: (string) Path to a fixture file to use. + * + * @SuppressWarnings(PHPMD.ElseExpression) */ - protected function replaceFixturePaths(array $fixture_map, $prefix = NULL) { + protected function replaceFixturePaths(array $fixture_map, string $prefix = NULL): array { foreach ($fixture_map as $k => $v) { if (is_array($v)) { $fixture_map[$k] = $this->replaceFixturePaths($v, $prefix); @@ -273,8 +281,12 @@ protected function replaceFixturePaths(array $fixture_map, $prefix = NULL) { * * @return bool * TRUE if the result of copy was successful, FALSE otherwise. + * + * @SuppressWarnings(PHPMD.BooleanArgumentFlag) + * @SuppressWarnings(PHPMD.NPathComplexity) + * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ - public function fileCopyRecursively($src, $dst, array $exclude = [], $permissions = 0755, $copy_empty_dirs = FALSE) { + public function fileCopyRecursively(string $src, string $dst, array $exclude = [], $permissions = 0755, $copy_empty_dirs = FALSE): bool { $parent = dirname($dst); if (!is_dir($parent)) { @@ -286,9 +298,13 @@ public function fileCopyRecursively($src, $dst, array $exclude = [], $permission // Changing dir symlink will be relevant to the current destination's file // directory. $cur_dir = getcwd(); + if (!$cur_dir) { + throw new \RuntimeException('Unable to get current working directory.'); + } + chdir($parent); $ret = TRUE; - if (!is_readable(basename($dst))) { + if (!is_readable(basename($dst)) && !empty(readlink($src))) { $ret = symlink(readlink($src), basename($dst)); } chdir($cur_dir); @@ -299,7 +315,11 @@ public function fileCopyRecursively($src, $dst, array $exclude = [], $permission if (is_file($src)) { $ret = copy($src, $dst); if ($ret) { - chmod($dst, fileperms($src)); + $perms = fileperms($src); + if ($perms === FALSE) { + throw new \RuntimeException(sprintf('Unable to get permissions for %s.', $src)); + } + chmod($dst, $perms); } return $ret; @@ -310,14 +330,16 @@ public function fileCopyRecursively($src, $dst, array $exclude = [], $permission } $dir = dir($src); - while (FALSE !== $entry = $dir->read()) { + while ($dir && FALSE !== $entry = $dir->read()) { if ($entry == '.' || $entry == '..' || in_array($entry, $exclude)) { continue; } $this->fileCopyRecursively($src . DIRECTORY_SEPARATOR . $entry, $dst . DIRECTORY_SEPARATOR . $entry, $exclude, $permissions, $copy_empty_dirs); } - $dir->close(); + if ($dir) { + $dir->close(); + } return TRUE; } diff --git a/web/modules/custom/civictheme_admin/civictheme_admin.module b/web/modules/custom/civictheme_admin/civictheme_admin.module index 042024b39..5119b9b44 100644 --- a/web/modules/custom/civictheme_admin/civictheme_admin.module +++ b/web/modules/custom/civictheme_admin/civictheme_admin.module @@ -10,7 +10,7 @@ use Drupal\Core\Form\FormStateInterface; /** * Implements hook_form_BASE_FORM_ID_alter(). */ -function civictheme_admin_form_node_form_alter(&$form, FormStateInterface $form_state) { +function civictheme_admin_form_node_form_alter(array &$form, FormStateInterface $form_state): void { // @see https://www.drupal.org/project/drupal/issues/3184667 // @see https://www.drupal.org/project/drupal/issues/3332416 $form['#attached']['library'][] = 'civictheme_admin/claro-node-form-overrides'; diff --git a/web/modules/custom/civictheme_content/civictheme_content.install b/web/modules/custom/civictheme_content/civictheme_content.install index dd7159d0f..2a1e63b17 100644 --- a/web/modules/custom/civictheme_content/civictheme_content.install +++ b/web/modules/custom/civictheme_content/civictheme_content.install @@ -29,10 +29,10 @@ use Drupal\Core\Installer\Exception\InstallerException; * * If 'none' is specified - none of the sub-modules will be enabled. */ -function civictheme_content_install() { +function civictheme_content_install(): void { $content_profile = 'default'; - if (!empty(trim(getenv('CIVICTHEME_CONTENT_PROFILE')))) { - $content_profile = strtolower(trim(getenv('CIVICTHEME_CONTENT_PROFILE'))); + if (!empty(trim((string) getenv('CIVICTHEME_CONTENT_PROFILE')))) { + $content_profile = strtolower(trim((string) getenv('CIVICTHEME_CONTENT_PROFILE'))); $content_profile = preg_replace('/[^a-z0-9_]/', '', $content_profile); } @@ -42,9 +42,9 @@ function civictheme_content_install() { return; } - $existing_content_profiles = array_map(function ($value) { + $existing_content_profiles = array_map(function ($value): string { return substr($value, strlen('civictheme_content_')); - }, array_diff(scandir(__DIR__ . DIRECTORY_SEPARATOR . 'modules'), ['..', '.'])); + }, array_diff(scandir(__DIR__ . DIRECTORY_SEPARATOR . 'modules') ?: [], ['..', '.'])); if (!in_array($content_profile, $existing_content_profiles)) { // Show as a warning message, but do not fail the installation. @@ -71,7 +71,7 @@ function civictheme_content_install() { /** * Install submodule of this module. */ -function _civictheme_content_install_submodule($module) { +function _civictheme_content_install_submodule(string $module): void { $active_theme = \Drupal::theme()->getActiveTheme(); // Only proceed if current theme is CivicTheme, or it's sub-theme so that // content could be applied only to expected configurations. @@ -96,7 +96,7 @@ function _civictheme_content_install_submodule($module) { /** * Common updates to be run by all content modules. */ -function civictheme_content_post_update_common() { +function civictheme_content_post_update_common(): void { // Site site slogan. \Drupal::service('config.factory')->getEditable('system.site') ->set('slogan', 'A design system by Salsa Digital') diff --git a/web/modules/custom/civictheme_content/civictheme_content.module b/web/modules/custom/civictheme_content/civictheme_content.module index 31bd36d71..84b9bc37c 100644 --- a/web/modules/custom/civictheme_content/civictheme_content.module +++ b/web/modules/custom/civictheme_content/civictheme_content.module @@ -8,7 +8,7 @@ /** * Helper for implementations of hook_module_implements_alter(). */ -function _civictheme_content_module_implements_alter($module, &$implementations, $hook) { +function _civictheme_content_module_implements_alter(string $module, array &$implementations, string $hook): void { if ($hook == 'modules_installed') { $group = $implementations[$module]; unset($implementations[$module]); @@ -19,9 +19,9 @@ function _civictheme_content_module_implements_alter($module, &$implementations, /** * Helper for implementations of hook_modules_installed(). */ -function _civictheme_content_modules_installed($module, $modules) { +function _civictheme_content_modules_installed(string $module, array $modules): void { if (in_array($module, $modules)) { - module_load_include('php', $module, $module . '.post_update'); + \Drupal::moduleHandler()->loadInclude($module, 'php', $module . '.post_update'); // Run all post-update functions when installing this module. $key_value = \Drupal::keyValue('post_update'); $executed_updates = $key_value->get('existing_updates', []); diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.module b/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.module index e40ad521c..9c4912892 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.module +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.module @@ -8,13 +8,13 @@ /** * Implements hook_module_implements_alter(). */ -function civictheme_content_corporate_module_implements_alter(&$implementations, $hook) { +function civictheme_content_corporate_module_implements_alter(array &$implementations, string $hook): void { _civictheme_content_module_implements_alter('civictheme_content_corporate', $implementations, $hook); } /** * Implements hook_modules_installed(). */ -function civictheme_content_corporate_modules_installed($modules, $is_syncing) { +function civictheme_content_corporate_modules_installed(array $modules, bool $is_syncing): void { _civictheme_content_modules_installed('civictheme_content_corporate', $modules); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.post_update.php b/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.post_update.php index 0a8566e03..105e2e050 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.post_update.php +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/civictheme_content_corporate.post_update.php @@ -11,7 +11,7 @@ /** * Common updates. */ -function civictheme_content_corporate_post_update_common() { +function civictheme_content_corporate_post_update_common(): void { \Drupal::moduleHandler()->loadInclude('civictheme_content', 'install'); civictheme_content_post_update_common(); } @@ -21,7 +21,7 @@ function civictheme_content_corporate_post_update_common() { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_content_corporate_post_update_set_homepage() { +function civictheme_content_corporate_post_update_set_homepage(): void { try { Helper::setHomepageFromNode('Protecting the environment'); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/content/node/855f86ae-b6a9-477c-8827-6b13b5c8ff41.yml b/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/content/node/855f86ae-b6a9-477c-8827-6b13b5c8ff41.yml index 005a66e54..aa6c609e3 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/content/node/855f86ae-b6a9-477c-8827-6b13b5c8ff41.yml +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_corporate/content/node/855f86ae-b6a9-477c-8827-6b13b5c8ff41.yml @@ -73,7 +73,7 @@ default: value: false field_c_p_content: - - value: "

What is CivicTheme?

\r\n\r\n

CivicTheme is a government-grade design system with a theme and component library to provide a consistent, high-quality digital experience out-of-the-box.

\r\n\r\n

The CivicTheme design system is a framework for Drupal 9 sites to build website pages using components like menus, hero banners, navigation cards, body text, tables and accordions. 

\r\n\r\n

CivicTheme.io - Learn more about CivicTheme

\r\n\r\n

See how CivicTheme works with Storybook

\r\n\r\n

CivicTheme is based on a modular, ‘atomic design’ system.  Each of the components and elements can be viewed individually in Storybook — a user interface (UI) tool that allows individual web page components to be viewed in isolation.

\r\n\r\n

CivicTheme storybook - Visit the CivicTheme storybook 

\r\n\r\n

CivicTheme supporting documentation 

\r\n\r\n

Find out more about how to use CivicTheme in the supporting documentation.

\r\n\r\n

CivicTheme documentation - Visit the documentation

\r\n" + value: "

What is CivicTheme?

\r\n\r\n

CivicTheme is a government-grade design system with a theme and component library to provide a consistent, high-quality digital experience out-of-the-box.

\r\n\r\n

The CivicTheme design system is a framework for Drupal 10 sites to build website pages using components like menus, hero banners, navigation cards, body text, tables and accordions. 

\r\n\r\n

CivicTheme.io - Learn more about CivicTheme

\r\n\r\n

See how CivicTheme works with Storybook

\r\n\r\n

CivicTheme is based on a modular, ‘atomic design’ system.  Each of the components and elements can be viewed individually in Storybook — a user interface (UI) tool that allows individual web page components to be viewed in isolation.

\r\n\r\n

CivicTheme storybook - Visit the CivicTheme storybook 

\r\n\r\n

CivicTheme supporting documentation 

\r\n\r\n

Find out more about how to use CivicTheme in the supporting documentation.

\r\n\r\n

CivicTheme documentation - Visit the documentation

\r\n" format: civictheme_rich_text field_c_p_theme: - diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.module b/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.module index 28d05c20b..1f1f523b9 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.module +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.module @@ -8,13 +8,13 @@ /** * Implements hook_module_implements_alter(). */ -function civictheme_content_default_module_implements_alter(&$implementations, $hook) { +function civictheme_content_default_module_implements_alter(array &$implementations, string $hook): void { _civictheme_content_module_implements_alter('civictheme_content_default', $implementations, $hook); } /** * Implements hook_modules_installed(). */ -function civictheme_content_default_modules_installed($modules, $is_syncing) { +function civictheme_content_default_modules_installed(array $modules, bool $is_syncing): void { _civictheme_content_modules_installed('civictheme_content_default', $modules); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.post_update.php b/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.post_update.php index b2744e43c..d4df5200e 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.post_update.php +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_default/civictheme_content_default.post_update.php @@ -11,7 +11,7 @@ /** * Common updates. */ -function civictheme_content_default_post_update_common() { +function civictheme_content_default_post_update_common(): void { \Drupal::moduleHandler()->loadInclude('civictheme_content', 'install'); civictheme_content_post_update_common(); } @@ -21,7 +21,7 @@ function civictheme_content_default_post_update_common() { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_content_default_post_update_set_homepage() { +function civictheme_content_default_post_update_set_homepage(): void { try { Helper::setHomepageFromNode("Your organisation's tagline"); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.module b/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.module index 369c2b701..6729e4175 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.module +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.module @@ -8,13 +8,13 @@ /** * Implements hook_module_implements_alter(). */ -function civictheme_content_government_module_implements_alter(&$implementations, $hook) { +function civictheme_content_government_module_implements_alter(array &$implementations, string $hook): void { _civictheme_content_module_implements_alter('civictheme_content_government', $implementations, $hook); } /** * Implements hook_modules_installed(). */ -function civictheme_content_government_modules_installed($modules, $is_syncing) { +function civictheme_content_government_modules_installed(array $modules, bool $is_syncing): void { _civictheme_content_modules_installed('civictheme_content_government', $modules); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.post_update.php b/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.post_update.php index 365d8790d..f25c79141 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.post_update.php +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_government/civictheme_content_government.post_update.php @@ -11,7 +11,7 @@ /** * Common updates. */ -function civictheme_content_government_post_update_common() { +function civictheme_content_government_post_update_common(): void { \Drupal::moduleHandler()->loadInclude('civictheme_content', 'install'); civictheme_content_post_update_common(); } @@ -21,7 +21,7 @@ function civictheme_content_government_post_update_common() { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_content_government_post_update_set_homepage() { +function civictheme_content_government_post_update_set_homepage(): void { try { Helper::setHomepageFromNode('Home'); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_government/content/node/21d11ae0-2874-4663-9937-a48ce30a7ad7.yml b/web/modules/custom/civictheme_content/modules/civictheme_content_government/content/node/21d11ae0-2874-4663-9937-a48ce30a7ad7.yml index 2824e24b1..9c96d89a4 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_government/content/node/21d11ae0-2874-4663-9937-a48ce30a7ad7.yml +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_government/content/node/21d11ae0-2874-4663-9937-a48ce30a7ad7.yml @@ -73,7 +73,7 @@ default: value: false field_c_p_content: - - value: "

About this template website

\r\n\r\n

This is a template website with dummy content. All content is for demonstration purposes only. This website has been created to show how CivicTheme can be used out-of-the-box to quickly and easily create a government website.

\r\n\r\n

This site contains \"dummy\" content for a fictitious government department, the Department of Citizens. All links lead to either:

\r\n\r\n
    \r\n\t
  • Dummy content created for this site
  • \r\n\t
  • This page, which contains information about the website
  • \r\n\t
  • Link to a dummy document
  • \r\n
\r\n\r\n

About CivicTheme

\r\n\r\n

CivicTheme is a new, open source component-based design system and Drupal 9 theme. It provides a quick, easy and cost-efficient solution to build new websites. Web publishers and administrators can create and manage pages and layout designs without any coding.

\r\n\r\n

It was developed with a strong user experience.

\r\n\r\n

More about CivicTheme

\r\n" + value: "

About this template website

\r\n\r\n

This is a template website with dummy content. All content is for demonstration purposes only. This website has been created to show how CivicTheme can be used out-of-the-box to quickly and easily create a government website.

\r\n\r\n

This site contains \"dummy\" content for a fictitious government department, the Department of Citizens. All links lead to either:

\r\n\r\n
    \r\n\t
  • Dummy content created for this site
  • \r\n\t
  • This page, which contains information about the website
  • \r\n\t
  • Link to a dummy document
  • \r\n
\r\n\r\n

About CivicTheme

\r\n\r\n

CivicTheme is a new, open source component-based design system and Drupal 10 theme. It provides a quick, easy and cost-efficient solution to build new websites. Web publishers and administrators can create and manage pages and layout designs without any coding.

\r\n\r\n

It was developed with a strong user experience.

\r\n\r\n

More about CivicTheme

\r\n" format: civictheme_rich_text field_c_p_theme: - diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.module b/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.module index 4e598ed13..14d8c64d5 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.module +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.module @@ -8,13 +8,13 @@ /** * Implements hook_module_implements_alter(). */ -function civictheme_content_highereducation_module_implements_alter(&$implementations, $hook) { +function civictheme_content_highereducation_module_implements_alter(array &$implementations, string $hook): void { _civictheme_content_module_implements_alter('civictheme_content_highereducation', $implementations, $hook); } /** * Implements hook_modules_installed(). */ -function civictheme_content_highereducation_modules_installed($modules, $is_syncing) { +function civictheme_content_highereducation_modules_installed(array $modules, bool $is_syncing): void { _civictheme_content_modules_installed('civictheme_content_highereducation', $modules); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.post_update.php b/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.post_update.php index d455e1e9c..462ba050c 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.post_update.php +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/civictheme_content_highereducation.post_update.php @@ -11,7 +11,7 @@ /** * Common updates. */ -function civictheme_content_highereducation_post_update_common() { +function civictheme_content_highereducation_post_update_common(): void { \Drupal::moduleHandler()->loadInclude('civictheme_content', 'install'); civictheme_content_post_update_common(); } @@ -21,7 +21,7 @@ function civictheme_content_highereducation_post_update_common() { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_content_highereducation_post_update_set_homepage() { +function civictheme_content_highereducation_post_update_set_homepage(): void { try { Helper::setHomepageFromNode('Home'); } diff --git a/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/content/node/11575ae4-d804-4b68-a9e2-528dde78ca5e.yml b/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/content/node/11575ae4-d804-4b68-a9e2-528dde78ca5e.yml index 67925a7c6..359f82391 100644 --- a/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/content/node/11575ae4-d804-4b68-a9e2-528dde78ca5e.yml +++ b/web/modules/custom/civictheme_content/modules/civictheme_content_highereducation/content/node/11575ae4-d804-4b68-a9e2-528dde78ca5e.yml @@ -73,7 +73,7 @@ default: value: false field_c_p_content: - - value: "

This is a template website with dummy content. All content is for demonstration purposes only. This website has been created to show how CivicTheme can be used out-of-the-box to quickly and easily create a university website. 

\r\n\r\n

This site contains ‘dummy’ content for a fictitious university, My University. All links lead to either:

\r\n\r\n
    \r\n\t
  • Content created for this site
  • \r\n\t
  • This page, which contains information about the website
  • \r\n
\r\n\r\n

About CivicTheme

\r\n\r\n

CivicTheme is a new, open source component-based design system and Drupal 9 theme. It provides a quick, easy and cost-efficient solution to build new websites. Web publishers and administrators can create and manage pages and layout designs without any coding. 

\r\n\r\n

It was developed with a strong user experience.

\r\n\r\n

More about CivicTheme

\r\n" + value: "

This is a template website with dummy content. All content is for demonstration purposes only. This website has been created to show how CivicTheme can be used out-of-the-box to quickly and easily create a university website. 

\r\n\r\n

This site contains ‘dummy’ content for a fictitious university, My University. All links lead to either:

\r\n\r\n
    \r\n\t
  • Content created for this site
  • \r\n\t
  • This page, which contains information about the website
  • \r\n
\r\n\r\n

About CivicTheme

\r\n\r\n

CivicTheme is a new, open source component-based design system and Drupal 10 theme. It provides a quick, easy and cost-efficient solution to build new websites. Web publishers and administrators can create and manage pages and layout designs without any coding. 

\r\n\r\n

It was developed with a strong user experience.

\r\n\r\n

More about CivicTheme

\r\n" format: civictheme_rich_text field_c_p_theme: - diff --git a/web/modules/custom/civictheme_content/src/Helper.php b/web/modules/custom/civictheme_content/src/Helper.php index 1e1721e58..22b0c8295 100644 --- a/web/modules/custom/civictheme_content/src/Helper.php +++ b/web/modules/custom/civictheme_content/src/Helper.php @@ -24,8 +24,10 @@ class Helper { * * @param string $message * String containing message. + * + * @SuppressWarnings(PHPMD.ElseExpression) */ - public static function log($message) { + public static function log(string $message): void { if (PHP_SAPI === 'cli') { $message = strip_tags(html_entity_decode($message)); if (class_exists('\Drush\Drush')) { @@ -53,7 +55,7 @@ public static function log($message) { * * @SuppressWarnings(PHPMD.StaticAccess) */ - public static function loadNodeByTitle($title, $type = NULL) { + public static function loadNodeByTitle(string $title, string $type = NULL): ?Node { $query = \Drupal::entityQuery('node')->accessCheck(FALSE); $query->condition('title', $title); if ($type) { @@ -78,7 +80,7 @@ public static function loadNodeByTitle($title, $type = NULL) { * * @SuppressWarnings(PHPMD.MissingImport) */ - public static function setHomepageFromNode($title) { + public static function setHomepageFromNode(string $title): void { $node = static::loadNodeByTitle($title, 'civictheme_page'); if (!$node) { diff --git a/web/modules/custom/civictheme_dev/civictheme_dev.install b/web/modules/custom/civictheme_dev/civictheme_dev.install index 19961d382..e06069d85 100644 --- a/web/modules/custom/civictheme_dev/civictheme_dev.install +++ b/web/modules/custom/civictheme_dev/civictheme_dev.install @@ -10,14 +10,14 @@ use Drupal\user\Entity\User; /** * Implements hook_install(). */ -function civictheme_dev_install() { +function civictheme_dev_install(): void { // Assign user 1 the "administrator" role. /** @var \Drupal\user\Entity\User $user */ $user = User::load(1); - $user->roles[] = 'administrator'; + $user->addRole('administrator'); $user->save(); - module_load_include('php', 'civictheme_dev', 'civictheme_dev.post_update'); + \Drupal::moduleHandler()->loadInclude('civictheme_dev', 'php', 'civictheme_dev.post_update'); $functions = get_defined_functions(); // Run all update functions when installing this module. diff --git a/web/modules/custom/civictheme_dev/civictheme_dev.module b/web/modules/custom/civictheme_dev/civictheme_dev.module index a1c9b0fd7..e76f7fef6 100644 --- a/web/modules/custom/civictheme_dev/civictheme_dev.module +++ b/web/modules/custom/civictheme_dev/civictheme_dev.module @@ -5,14 +5,13 @@ * Core module for Cs. */ -use Drupal\civictheme\CivicthemeConstants; use Drupal\civictheme\CivicthemeVersionManager; use Drupal\Core\Site\Settings; /** * Implements hook_mail_alter(). */ -function civictheme_dev_mail_alter(&$message) { +function civictheme_dev_mail_alter(array &$message): void { // Allow to stop any mail send out through settings. Note if email // functionality needs to be tested, this code should be removed and // replaced with a dev mail system. @@ -24,9 +23,8 @@ function civictheme_dev_mail_alter(&$message) { /** * Implements hook_preprocess_html(). */ -function civictheme_dev_preprocess_html(&$variables) { +function civictheme_dev_preprocess_html(array &$variables): void { /** @var \Drupal\civictheme\CivicthemeVersionManager $version_manager */ $version_manager = \Drupal::classResolver(CivicthemeVersionManager::class); - $color = (theme_get_setting('components.footer.theme') ?? CivicthemeConstants::FOOTER_THEME_DEFAULT) == CivicthemeConstants::THEME_LIGHT ? '#000000' : '#ffffff'; - $variables['page_bottom']['civictheme_version'] = $version_manager->render('.ct-footer__logo', $color); + $variables['page_bottom']['civictheme_version'] = $version_manager->render('body'); } diff --git a/web/modules/custom/civictheme_dev/civictheme_dev.post_update.php b/web/modules/custom/civictheme_dev/civictheme_dev.post_update.php index 14e595088..37fe75844 100644 --- a/web/modules/custom/civictheme_dev/civictheme_dev.post_update.php +++ b/web/modules/custom/civictheme_dev/civictheme_dev.post_update.php @@ -12,8 +12,10 @@ /** * Creates administrator users. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_dev_post_update_provision_users() { +function civictheme_dev_post_update_provision_users(): string { $emails = [ 'akhil.bhandari@salsa.digital', 'alan.rako@salsa.digital', @@ -40,12 +42,16 @@ function civictheme_dev_post_update_provision_users() { $user->enforceIsNew(); $user->save(); } + + return 'Created ' . count($emails) . ' users.'; } /** * Creates storybook redirects. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_dev_post_update_provision_storybook_redirects() { +function civictheme_dev_post_update_provision_storybook_redirects(): string { $map = [ [ 'src' => '/storybook', @@ -67,12 +73,16 @@ function civictheme_dev_post_update_provision_storybook_redirects() { $redirect->setStatusCode(301); $redirect->save(); } + + return 'Created ' . count($map) . ' redirects.'; } /** * Updates Side Navigation block visibility settings. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_dev_post_update_update_side_navigation_block() { +function civictheme_dev_post_update_update_side_navigation_block(): string { $entity_type_manager = \Drupal::entityTypeManager(); $blocks = $entity_type_manager->getStorage('block')->loadByProperties([ 'region' => 'sidebar', @@ -90,24 +100,29 @@ function civictheme_dev_post_update_update_side_navigation_block() { 'pages' => "/search\n\r/news-and-events\n\r*civictheme-no-sidebar*", ]); $block->save(); + + return 'Updated Side Navigation block visibility settings.'; } /** * Updates Testmode module settings. */ -function civictheme_dev_post_update_update_testmode_settings() { +function civictheme_dev_post_update_update_testmode_settings(): string { + /** @var \Drupal\Core\Config\Config $config */ $config = \Drupal::service('config.factory')->getEditable('testmode.settings'); - $views_list = $config->get('views_node', []); + $views_list = $config->get('views_node') ?: []; $views_list[] = 'civictheme_automated_list'; $views_list[] = 'civictheme_automated_list_examples'; $views_list[] = 'civictheme_automated_list_test'; $config->set('views_node', $views_list)->save(); + + return 'Updated Testmode module settings.'; } /** * Updates Simple Sitemap configuration to include nodes and views. */ -function civictheme_dev_post_update_update_simplesitemap() { +function civictheme_dev_post_update_update_simplesitemap(): string { if (!\Drupal::moduleHandler()->moduleExists('simple_sitemap')) { \Drupal::service('module_installer')->install(['simple_sitemap']); } @@ -131,6 +146,7 @@ function civictheme_dev_post_update_update_simplesitemap() { $type = $type_storage->load('default_hreflang'); if ($type) { + // @phpstan-ignore-next-line $type->url_generators = [ 'custom', 'entity', @@ -141,12 +157,16 @@ function civictheme_dev_post_update_update_simplesitemap() { $type->save(); } + + return 'Updated Simple Sitemap configuration to include nodes and views.'; } /** * Places Listing example view blocks the current theme's regions. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_dev_post_update_place_listing_example_blocks_into_regions() { +function civictheme_dev_post_update_place_listing_example_blocks_into_regions(): string { $theme_name = \Drupal::configFactory()->get('system.theme')->get('default'); if ($theme_name == 'civictheme') { return 'Skipping update for the CivicTheme as blocks already exist.'; @@ -164,4 +184,6 @@ function civictheme_dev_post_update_place_listing_example_blocks_into_regions() $child_block = $parent_block->createDuplicateBlock($new_id, $theme_name); $child_block->save(); } + + return 'Placed Listing example view blocks into the current theme\'s regions.'; } diff --git a/web/modules/custom/civictheme_dev/src/EventSubscriber/CivicthemeDevConfigDevelSubscriber.php b/web/modules/custom/civictheme_dev/src/EventSubscriber/CivicthemeDevConfigDevelSubscriber.php index 742461848..c7558cb85 100644 --- a/web/modules/custom/civictheme_dev/src/EventSubscriber/CivicthemeDevConfigDevelSubscriber.php +++ b/web/modules/custom/civictheme_dev/src/EventSubscriber/CivicthemeDevConfigDevelSubscriber.php @@ -23,10 +23,8 @@ class CivicthemeDevConfigDevelSubscriber extends ConfigDevelSubscriberBase imple /** * The config ignore plugin manager. - * - * @var \Drupal\config_filter\Plugin\ConfigFilterPluginManager */ - protected $configFilterPluginManager; + protected ConfigFilterPluginManager $configFilterPluginManager; /** * Constructs the ConfigDevelAutoExportSubscriber object. @@ -51,7 +49,7 @@ public function __construct(ConfigFactoryInterface $config_factory, ConfigManage * @param \Drupal\config_devel\Event\ConfigDevelSaveEvent $event * The event to process. */ - public function onConfigDevelSave(ConfigDevelSaveEvent $event) { + public function onConfigDevelSave(ConfigDevelSaveEvent $event): void { $filenames = $event->getFileNames(); if (empty($filenames)) { @@ -74,6 +72,8 @@ public function onConfigDevelSave(ConfigDevelSaveEvent $event) { * {@inheritdoc} */ public static function getSubscribedEvents() { + $events = []; + $events[ConfigDevelEvents::SAVE][] = ['onConfigDevelSave', 10]; return $events; diff --git a/web/modules/custom/civictheme_dev/src/Helper.php b/web/modules/custom/civictheme_dev/src/Helper.php deleted file mode 100644 index ad770c3fa..000000000 --- a/web/modules/custom/civictheme_dev/src/Helper.php +++ /dev/null @@ -1,1399 +0,0 @@ -getStorage('taxonomy_term')->loadTree($vid, 0, $depth + 1, $load_entities); - - foreach ($tree as $k => $leaf) { - if ($leaf->depth != $depth) { - unset($tree[$k]); - } - } - - return $tree; - } - - /** - * Save terms, specified as simplified term tree. - * - * @param string $vid - * Vocabulary machine name. - * @param array $tree - * Array of tree items, where keys with array values are considered parent - * terms. - * @param bool|int $parent_tid - * Internal parameter used for recursive calls. - * - * @return array - * Array of saved terms, keyed by term id. - */ - public static function saveTermTree($vid, array $tree, $parent_tid = FALSE) { - $terms = []; - $weight = 0; - - foreach ($tree as $parent => $subtree) { - $term = Term::create([ - 'name' => is_array($subtree) ? $parent : $subtree, - 'vid' => $vid, - 'weight' => $weight, - 'parent' => $parent_tid !== FALSE ? $parent_tid : 0, - ]); - - $term->save(); - $terms[$term->id()] = $term; - - if (is_array($subtree)) { - $terms += self::saveTermTree($vid, $subtree, $term->id()); - } - - $weight++; - } - - return $terms; - } - - /** - * Clear all terms in vocabulary. - * - * @param string $vid - * Vocabulary machine name. - */ - public static function clearVocabulary($vid) { - $result = \Drupal::entityQuery('taxonomy_term') - ->condition('vid', $vid) - ->execute(); - - $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term'); - $entities = $controller->loadMultiple($result); - $controller->delete($entities); - } - - /** - * Clear all items in the menu. - * - * @param string $menu_name - * String machine menu name. - */ - public static function clearMenu($menu_name) { - /** @var \Drupal\menu_link_content\MenuLinkContentStorage $storage */ - $storage = \Drupal::entityTypeManager()->getStorage('menu_link_content'); - - $menu_items = $storage->loadByProperties([ - 'menu_name' => $menu_name, - ]); - - foreach ($menu_items as $menu_item) { - $menu_item->delete(); - } - } - - /** - * Import links from the provided tree. - * - * @code - * $tree = [ - * 'Item1' => [ - * 'link' => '/path-to-item1', - * 'children' => [ - * 'Subitem 1' => '/path-to-subitem1', - * 'Subitem 2' => '/path-to-subitem2', - * ], - * 'Item2' => '/path-to-item2', - * ]; - * Menu::import('main-menu', $tree); - * @endcode - * - * @param string $menu_name - * String machine menu name. - * @param array $tree - * Array of links with keys as titles and values as paths or full link - * item array definitions. 'children' key is used to specify children menu - * levels. - * @param \Drupal\menu_link_content\Entity\MenuLinkContent $parent_menu_link - * Internal. Parent menu link item. - * - * @return array - * Array of created mlids. - * - * @SuppressWarnings(PHPMD.MissingImport) - */ - public static function saveMenuTree($menu_name, array $tree, MenuLinkContent $parent_menu_link = NULL) { - $created_mlids = []; - $weight = 0; - foreach ($tree as $title => $leaf) { - $leaf = is_array($leaf) ? $leaf : ['link' => $leaf]; - - if (!isset($leaf['link'])) { - throw new \InvalidArgumentException('Menu item does not contain "link" element'); - } - - if (is_array($leaf['link']) && !isset($leaf['link']['uri'])) { - throw new \InvalidArgumentException('Menu item contains "link" element which does not contain "uri" value'); - } - - if (!is_array($leaf['link'])) { - $leaf['link'] = ['uri' => $leaf['link']]; - } - - // Try to convert scalar link to Drupal Url object. - if (is_string($leaf['link']['uri'])) { - $leaf['link']['uri'] = Url::fromUserInput($leaf['link']['uri'])->toUriString(); - } - - $leaf_defaults = [ - 'menu_name' => $menu_name, - 'title' => $title, - 'weight' => $weight, - ]; - if ($parent_menu_link) { - $leaf_defaults['parent'] = 'menu_link_content:' . $parent_menu_link->uuid(); - } - - $leaf += $leaf_defaults; - - $children = $leaf['children'] ?? []; - unset($leaf['children']); - if ($children) { - $leaf += ['expanded' => TRUE]; - } - - $menu_link = MenuLinkContent::create($leaf); - $menu_link->save(); - $mlid = $menu_link->id(); - if (!$mlid) { - continue; - } - $created_mlids[] = $mlid; - $weight++; - if ($children) { - $created_mlids = array_merge($created_mlids, self::saveMenuTree($menu_name, $children, $menu_link)); - } - } - - return $created_mlids; - } - - /** - * Updated menu item link. - * - * @param string $menu - * The menu name. - * @param string $existing_link - * The existing link to search for. - * @param string $new_link - * The new link to update to. - */ - public static function updateMenuItemLink($menu, $existing_link, $new_link) { - $menu_item = self::findMenuItemByLink($menu, $existing_link); - - if (!$menu_item) { - return FALSE; - } - - $menu_item->set('link', $new_link); - $menu_item->save(); - } - - /** - * Find menu item by link. - * - * @param string $menu - * The menu name. - * @param string $link - * The link to search for. - * - * @return bool|\Drupal\menu_link_content\MenuLinkContentInterface - * Found menu item or FALSE. - */ - public static function findMenuItemByLink($menu, $link) { - /** @var \Drupal\menu_link_content\MenuLinkContentStorage $storage */ - $storage = \Drupal::entityTypeManager()->getStorage('menu_link_content'); - - $menu_items = $storage->loadByProperties([ - 'menu_name' => $menu, - 'link__uri' => $link, - ]); - - if (empty($menu_items)) { - return FALSE; - } - - // Only support the very first found item. - $menu_item = array_shift($menu_items); - - return $menu_item; - } - - /** - * Find menu item by link. - * - * @param string $menu - * The menu name. - * @param string $title - * The title to search for. - * @param int $idx - * The index of the result to return. Defaults to NULL. If specified, but - * an item with this index does not exist - FALSE is returned. If not - * specified - a first item from the match is returned. - * - * @return bool|\Drupal\menu_link_content\MenuLinkContentInterface - * Found menu item or FALSE. - */ - public static function findMenuItemByTitle($menu, $title, $idx = NULL) { - /** @var \Drupal\menu_link_content\MenuLinkContentStorage $storage */ - $storage = \Drupal::entityTypeManager()->getStorage('menu_link_content'); - - $menu_items = $storage->loadByProperties([ - 'menu_name' => $menu, - 'title' => $title, - ]); - - if (empty($menu_items)) { - return FALSE; - } - - if (!is_null($idx)) { - $menu_item = $menu_items[$idx] ?? FALSE; - } - else { - // Return the first item. - $menu_item = array_shift($menu_items); - } - - return $menu_item; - } - - /** - * Recursively flatten previously loaded menu tree. - */ - public static function flattenMenuTree($tree) { - $list = []; - - foreach ($tree as $id => $leaf) { - $list[$id] = $leaf; - if (!empty($leaf->subtree)) { - $list = array_merge($list, self::flattenMenuTree($leaf->subtree)); - } - } - - return $list; - } - - /** - * Check if menu item has children. - * - * @param \Drupal\menu_link_content\Entity\MenuLinkContent $menu_item - * Menu items to check. - * - * @return bool|null - * TRUE if menu item has children, FALSE otherwise. NULL if the menu item - * was not found. - */ - public static function menuItemHasChildren(MenuLinkContent $menu_item) { - $menu_tree = \Drupal::menuTree(); - $menu_name = $menu_item->getMenuName(); - - $parameters = new MenuTreeParameters(); - $tree = $menu_tree->load($menu_name, $parameters); - $tree = static::flattenMenuTree($tree); - - foreach ($tree as $leaf) { - if ( - $leaf->link->getMenuName() === $menu_item->getMenuName() && - $leaf->link->getTitle() === $menu_item->getTitle() && - $leaf->link->getUrlObject()->toString() === $menu_item->getUrlObject()->toString() - ) { - return !empty($leaf->subtree); - } - } - - return NULL; - } - - /** - * Intersect arrays by column. - * - * @param string $column - * Column name. - * @param ... - * Variable number of arrays. - * - * @return array - * Array of intersected values. - * - * @throws \Exception - * - * @SuppressWarnings(PHPMD.MissingImport) - */ - public static function arrayIntersectColumn($column) { - $arrays = func_get_args(); - array_shift($arrays); - - if (count($arrays) < 1) { - throw new \Exception('At least one array argument is required'); - } - - foreach ($arrays as $k => $array) { - if (!is_array($array)) { - throw new \Exception(sprintf('Argument %s is not an array', $k + 1)); - } - } - - $carry = array_shift($arrays); - foreach ($arrays as $k => $array) { - $carry_column = self::arrayColumn($carry, $column); - $array_column = self::arrayColumn($array, $column); - $column_values = array_intersect($carry_column, $array_column); - - $carry = array_filter($array, function ($item) use ($column, $column_values) { - $value = self::extractProperty($item, $column); - - return $value && in_array($value, $column_values); - }); - } - - return $carry; - } - - /** - * Portable array_column with support for methods. - * - * @SuppressWarnings(PHPMD.MissingImport) - */ - public static function arrayColumn(array $array, $key) { - if (!is_scalar($key)) { - throw new \Exception('Specified key is not scalar'); - } - - return array_map(function ($item) use ($key) { - return self::extractProperty($item, $key); - }, $array); - } - - /** - * Helper to extract property. - * - * Note that this helper supports extracting values from simple methods. - * - * @param mixed $item - * Array or object. - * @param string $key - * Array key or object property or method. - * - * @return mixed|null - * For arrays - value at specified key. - * For objects - value of the specified property or returned value of the - * method. - * - * @throws \Exception - * If key is not scalar. - * If item is not an array or an object. - * If item is an object, but does not have a property or a method with - * specified name. - * If item is an array and does not have an element with specified key. - * - * @SuppressWarnings(PHPMD.MissingImport) - */ - protected static function extractProperty($item, $key) { - if (!is_scalar($key)) { - throw new \Exception('Specified key is not scalar'); - } - - if (!is_object($item) && !is_array($item)) { - throw new \Exception(sprintf('Item with key "%s" must be an object or an array', $key)); - } - - if (is_object($item)) { - if (method_exists($item, $key)) { - return $item->{$key}(); - } - elseif (property_exists($item, $key)) { - return $item->{$key}; - } - throw new \Exception(sprintf('Key "%s" is not a property or a method of an object', $key)); - } - elseif (is_array($item)) { - if (isset($item[$key])) { - return $item[$key]; - } - throw new \Exception(sprintf('Key "%s" does not exist in array', $key)); - } - - return NULL; - } - - /** - * Helper to load media entity by name. - * - * @param string $name - * The media name. - * @param string $bundle - * (optional) The media bundle name. - * - * @return \Drupal\Core\Entity\EntityInterface|\Drupal\media\Entity\Media - * The media instance or NULL. - */ - public static function loadMediaByName($name, $bundle = NULL) { - $query = \Drupal::entityQuery('media'); - $query->condition('name', $name); - if ($bundle) { - $query->condition('bundle', $bundle); - } - $ids = $query->execute(); - - if (empty($ids)) { - return NULL; - } - - $id = array_shift($ids); - - return Media::load($id); - } - - /** - * Create Image media from provided image. - * - * @param string $filepath - * The full path to the file on the disk. - * @param bool $alt - * (optional) Alternative text for the file. - * @param string $bundle - * (optional) The image media bundle name. Defaults to 'image'. - * - * @return \Drupal\Core\Entity\EntityInterface|\Drupal\media\Entity\Media - * Created media object. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function createMediaImage($filepath, $alt = FALSE, $bundle = 'image') { - if (!is_readable($filepath)) { - throw new \Exception(sprintf('Unable to find file "%s"', $filepath)); - } - - $file_name = pathinfo($filepath, PATHINFO_FILENAME); - $file_ext = pathinfo($filepath, PATHINFO_EXTENSION); - $file_full_name = $file_name . (!empty($file_ext) ? '.' . $file_ext : ''); - - $alt = $alt ? $alt : sprintf('Alt for %s', $file_full_name); - - $uri = 'public://' . $file_full_name; - - $file = file_save_data(file_get_contents($filepath), $uri); - - $media = Media::create([ - 'bundle' => $bundle, - 'name' => $file_full_name, - ]); - - $media->field_m_image->setValue($file->id()); - $media->field_m_image->alt = $alt; - $media->save(); - - return $media; - } - - /** - * Helper to create or load a media image by the file name. - */ - public static function createOrLoadMediaImage($filepath, $alt = FALSE) { - $file_name = pathinfo($filepath, PATHINFO_FILENAME); - $file_ext = pathinfo($filepath, PATHINFO_EXTENSION); - $file_full_name = $file_name . (!empty($file_ext) ? '.' . $file_ext : ''); - - $media = Helper::loadMediaByName($file_full_name, 'image'); - if (!$media) { - $media = Helper::createMediaImage($filepath, $alt); - } - - if (!$media) { - throw new \Exception(sprintf('Unable to create or load and image "%s"', $filepath)); - } - - return $media; - } - - /** - * Helper to print messages. - * - * Prints to stdout if using drush, or drupal_set_message() if the web UI. - * - * It is important to note that using \Drupal::messenger() when running Drush - * commands have side effects where messages are displayed only after the - * command has finished rather then during the command run. - * - * @param string $message - * String containing message. - * @param string $prefix - * Prefix to be used for messages when called through CLI. - * Defaults to '-- '. - * @param int $indent - * Indent for messages. Defaults to 2. - */ - public static function log($message, $prefix = '-- ', $indent = 2) { - if (class_exists('\Drush\Drush')) { - /** @var \Drush\Log\Logger $logger */ - $logger = Drush::getContainer()->get('logger'); - $logger->log(LogLevel::INFO, str_pad(((string) $prefix) . html_entity_decode($message), $indent, ' ', STR_PAD_LEFT)); - } - elseif (PHP_SAPI === 'cli') { - print str_pad(((string) $prefix) . html_entity_decode($message), $indent, ' ', STR_PAD_LEFT) . PHP_EOL; - } - else { - $messenger = \Drupal::messenger(); - if (isset($message)) { - $messenger->addMessage($message); - } - } - } - - /** - * Load block_content entity by UUID. - * - * @param string $uuid - * Block content UUID. - * - * @return \Drupal\block_content\Entity\BlockContent|\Drupal\Core\Entity\EntityInterface|null - * Loaded block or NULL if block cannot be found. - */ - public static function loadBlockContentByUuid($uuid) { - $query = \Drupal::entityQuery('block_content') - ->condition('uuid', $uuid); - $ids = $query->execute(); - - if (empty($ids)) { - return NULL; - } - - $id = array_shift($ids); - - return BlockContent::load($id); - } - - /** - * Helper to read configuration from provided locations. - * - * Drupal\Core\Site\Settings::get('config_sync_directory') - * is prepended to the beginning of the locations list to perform lookup in - * active configuration. - * - * @param string $id - * Configuration id. - * @param array $locations - * Array of paths to lookup configuration files. - * @param bool $prioritise_sync - * Whether to prioritise the same config in CONFIG_SYNC. - * - * @return mixed - * Configuration value. - * - * @throws \Exception - * If configuration file was not found in any specified location. - */ - public static function readConfig($id, array $locations = [], $prioritise_sync = TRUE) { - static $storages; - - global $config_directories; - - if (!$prioritise_sync) { - // CONFIG_SYNC has lower priority. - array_push($locations, $config_directories[Settings::get('config_sync_directory')]); - } - else { - // CONFIG_SYNC has top priority. - array_unshift($locations, $config_directories[Settings::get('config_sync_directory')]); - } - - foreach ($locations as $path) { - if (file_exists($path . DIRECTORY_SEPARATOR . $id . '.yml')) { - $storages[$path] = new FileStorage($path); - break; - } - } - - if (!isset($storages[$path])) { - throw new \Exception('Configuration does not exist in any provided locations'); - } - - return $storages[$path]->read($id); - } - - /** - * Helper to ensure that specified configuration is present. - * - * Used in install and update hooks to automatically install required - * configuration from active configuration or, if does not exist, from - * provided locations (usually, 'config/install' in module's directory). - * - * Helpful to avoid cases when configuration import may remove and add back - * entities, because install/update hook does not use the same config items - * as already exported. - * - * @param string $id - * Configuration id. - * @param array $locations - * Array of paths to lookup configuration files. - */ - public static function ensureConfig($id, array $locations = []) { - $config_data = self::readConfig($id, $locations); - \Drupal::service('config.storage')->write($id, $config_data); - } - - /** - * Helper to reload default configuration provided by a module. - * - * @param string $module - * Module name. - */ - public static function reloadDefaultConfig($module) { - /** @var \Drupal\Core\Config\ConfigInstaller $config_installer */ - $config_installer = \Drupal::service('config.installer'); - $config_installer->installDefaultConfig('module', $module); - } - - /** - * Helper to import a single config item (in a quick and dirty way). - * - * @param string $config_name - * Config name. - * @param array $locations - * Array of Locations. - * @param bool $prioritise_sync - * Whether to prioritise the same config in CONFIG_SYNC. - * - * @throws \Exception - */ - public static function importSingleConfig($config_name, array $locations = [], $prioritise_sync = TRUE) { - $config_data = self::readConfig($config_name, $locations, $prioritise_sync); - unset($config_data['uuid']); - $config_storage = \Drupal::service('config.storage'); - $event_dispatcher = \Drupal::service('event_dispatcher'); - $config_manager = \Drupal::service('config.manager'); - $lock_persistent = \Drupal::service('lock.persistent'); - $config_typed = \Drupal::service('config.typed'); - $module_handler = \Drupal::service('module_handler'); - $module_installer = \Drupal::service('module_installer'); - $theme_handler = \Drupal::service('theme_handler'); - $string_translation = \Drupal::service('string_translation'); - $extension_list_module = \Drupal::service('extension.list.module'); - \Drupal::config($config_name); - - $source_storage = new StorageReplaceDataWrapper($config_storage); - $source_storage->replaceData($config_name, $config_data); - - $storage_comparer = new StorageComparer( - $source_storage, - $config_storage, - $config_manager - ); - - $storage_comparer->createChangelist(); - - $config_importer = new ConfigImporter( - $storage_comparer, - $event_dispatcher, - $config_manager, - $lock_persistent, - $config_typed, - $module_handler, - $module_installer, - $theme_handler, - $string_translation, - $extension_list_module - ); - - try { - $config_importer->import(); - \Drupal::cache('config')->delete($config_name); - } - catch (\Exception $exception) { - foreach ($config_importer->getErrors() as $error) { - \Drupal::logger('civictheme_dev')->error($error); - \Drupal::messenger()->addError($error); - } - throw $exception; - } - } - - /** - * Get short file type; image, video, audio, document etc. - * - * @param \Drupal\file\Entity\File $file - * The file to find the type. - * - * @return string - * The short file type. - */ - public static function fileShortType(File $file) { - return substr($file->getMimeType(), 0, strpos($file->getMimeType(), '/')); - } - - /** - * Load node by title. - * - * @param string $title - * Title to search for. - * @param string $type - * Optional bundle name to limit the search. Defaults to NULL. - * - * @return \Drupal\node\Entity\Node - * Found node object or NULL if the node was not found. - */ - public static function loadNodeByTitle($title, $type = NULL) { - $query = \Drupal::entityQuery('node'); - $query->condition('title', $title); - if ($type) { - $query->condition('type', $type); - } - $ids = $query->execute(); - - if (empty($ids)) { - return NULL; - } - - $id = array_shift($ids); - - return Node::load($id); - } - - /** - * Find node by alias. - * - * @param string $alias - * Node alias. - * @param bool $load_node - * (optional) Flag to load node. Defaults to TRUE. - * - * @return \Drupal\node\Entity\Node|int|null - * Found node if $load_node is TRUE, or found node id, or NULL. - */ - public static function findNodeByAlias($alias, $load_node = TRUE) { - $path = \Drupal::service('path.alias_manager')->getPathByAlias($alias); - - try { - $params = Url::fromUri('internal:' . $path)->getRouteParameters(); - } - catch (\Exception $exception) { - return NULL; - } - - $entity_type = key($params); - - if ($entity_type != 'node') { - return NULL; - } - - $nid = $params[$entity_type]; - - if (!$load_node) { - return $nid; - } - - $node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($nid); - - return $node; - } - - /** - * Check if node field has a value. - * - * @param \Drupal\node\Entity\Node $node - * The entity to get the values from. - * @param string $field_name - * The field name. - * @param string $value - * The value to check. - * @param string $key - * (optional) The value key. Defaults to 'value'. - * - * @return bool - * TRUE if the value is present, FALSE otherwise. - */ - public static function nodeFieldHasValue(Node $node, $field_name, $value, $key = 'value') { - $field_values = $node->{$field_name}->getValue(); - - foreach ($field_values as $field_value) { - if (isset($field_value[$key]) && $field_value[$key] == $value) { - return TRUE; - } - } - - return FALSE; - } - - /** - * Convert alias to source. - */ - public static function aliasToSource($alias) { - $path = \Drupal::service('path.alias_manager')->getPathByAlias($alias); - - return $path != $alias ? 'internal:' . $path : NULL; - } - - /** - * Download a file from URL. - */ - public static function downloadFile($url, $dst) { - $ch = curl_init($url); - - $fp = fopen($dst, 'wb'); - - curl_setopt($ch, CURLOPT_FILE, $fp); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_FAILONERROR, 1); - - if (curl_exec($ch) === FALSE) { - $curl_error = curl_error($ch); - curl_close($ch); - fclose($fp); - throw new \Exception(sprintf('Curl error: %s', $curl_error)); - } - - curl_close($ch); - fclose($fp); - } - - /** - * Replaces file. - */ - public static function replaceFile($existing_file_uri, $new_file_uri, $create_non_existent = TRUE) { - if (!is_readable($new_file_uri)) { - throw new \Exception(sprintf('Unable to find replacement file "%s"', $new_file_uri)); - } - - /** @var \Drupal\file\FileInterface[] $files */ - $existing_files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => $existing_file_uri]); - - $basename = \Drupal::service('file_system')->basename($new_file_uri); - - if (!empty($existing_files)) { - // Replace all existing files. - foreach ($existing_files as $existing_file) { - $existing_file->setFileUri($new_file_uri); - $existing_file->setFilename($basename); - $existing_file->save(); - } - - return self::FILE_REPLACED; - } - elseif ($create_non_existent) { - $new_file = File::create([ - 'filename' => $basename, - 'uri' => $new_file_uri, - ]); - $new_file->save(); - - return self::FILE_CREATED; - } - - return self::FILE_UNCHANGED; - } - - /** - * Updates Paragraph Link text. - */ - public static function updateNodeParagraphLinkText($node, $partial_file_name, $new_text) { - foreach ($node->field_components as $item) { - if ($item->entity->bundle() != 'content') { - continue; - } - - $html = $item->entity->field_body->value; - $crawler = new Crawler($html); - - $html = $crawler->filter('body')->html(); - - $crawler->filter('a')->each(function ($node) use ($partial_file_name, $new_text) { - $link_node = $node->getNode(0); - - $href = $link_node->getAttribute('href'); - - if (strpos($href, $partial_file_name) !== FALSE) { - $link_node->removeChild($link_node->firstChild); - $new_text_node = new \DOMText($new_text); - $link_node->appendChild($new_text_node); - } - }); - - $updated_html = $crawler->filter('body')->html(); - - if ($html != $updated_html) { - $item->entity->set('field_body', [ - 'value' => $updated_html, - 'format' => 'filtered_html', - ]); - $item->entity->save(); - } - } - } - - /** - * Create paragraph entity. - * - * @param string $bundle - * The paragraph bundle name. - * @param array $fields - * Fields to be added to the paragraph. - * - * @return \Drupal\Core\Entity\EntityInterface|Paragraph - * The paragraph entity. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function createParagraph(string $bundle, array $fields = []) { - $paragraph = Paragraph::create([ - 'type' => $bundle, - ]); - foreach ($fields as $field => $value) { - $paragraph->set($field, $value); - } - $paragraph->save(); - - return $paragraph; - } - - /** - * Create block entity. - * - * @param array $block_content - * The block to be created. - * - * @return \Drupal\Core\Entity\Block - * The block entity. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function createBlock(array $block_content = []) { - $block = BlockContent::create($block_content); - $block->save(); - - return $block; - } - - /** - * Create page stub node. - * - * @param string $title - * The stub node title. - * @param string $alias - * The alias for the stub node (prepended by /stub automatically). - * - * @return string - * Created stub page alias. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function createPageStub(string $title, string $alias) { - if (!UrlHelper::isExternal($alias)) { - // Ensure the URL is flat without any extra elements (such as query). - $alias = '/stub' . Url::fromUserInput($alias)->setOptions([])->toString(); - } - - // Attempt to load an existing node instead of creating a duplicate. - $node = self::findNodeByAlias($alias); - - if (empty($node)) { - $node = Node::create([ - 'type' => 'page', - 'title' => $title, - 'status' => Node::PUBLISHED, - 'moderation_state' => 'published', - 'path' => [ - 'alias' => $alias, - 'pathauto' => FALSE, - ], - ]); - $node->setOwnerId(1); - $node->save(); - } - - return $alias; - } - - /** - * Create tile paragraph entity. - * - * @param array $values - * An array of tile details. - * - * @return \Drupal\Core\Entity\EntityInterface|Paragraph - * The tile paragraph entity. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function createTileParagraph(array $values) { - $defaults = [ - 'heading' => NULL, - 'summary' => NULL, - 'image' => NULL, - 'cta' => NULL, - ]; - - $values += $defaults; - - if (empty($values['heading']) || empty($values['summary'])) { - return NULL; - } - - $content = []; - - if (!empty($values['heading'])) { - $content['field_p_t_heading'] = $values['heading']; - } - - if (!empty($values['summary'])) { - $content['field_p_t_summary'] = [ - 'value' => $values['summary'], - 'format' => 'rich_text', - ]; - } - - if (!empty($values['cta'])) { - $content['field_p_t_cta'] = $values['cta']; - } - - if (!empty($values['image'])) { - $content['field_p_t_media'] = self::loadMediaByName($values['image'], 'image'); - } - - return self::createParagraph('tile', $content); - } - - /** - * Create file entity. - * - * @param string $filepath - * The filepath for the file. - * - * @return bool|\Drupal\file\FileInterface|false - * The file entity or FALSE. - */ - public static function createFileEntity(string $filepath) { - if (is_scalar($filepath) - && strpos(strtolower($filepath), 'http') === 0 - && !empty(pathinfo(parse_url($filepath, PHP_URL_PATH), PATHINFO_EXTENSION)) - ) { - $destination = 'public://' . basename(parse_url($filepath, PHP_URL_PATH)); - - if (@file_get_contents($filepath)) { - return file_save_data(file_get_contents($filepath), $destination, FileSystemInterface::EXISTS_REPLACE); - } - else { - throw new UpdateException(sprintf('Unable to create file entity from %s.', $filepath)); - } - } - - return FALSE; - } - - /** - * Create a media entity. - * - * @param \Drupal\file\FileInterface $file - * The file to create the media entity. - * @param string $bundle - * The bundle of the media entity. - * - * @return bool|\Drupal\media\MediaInterface - * The media entity or FALSE. - */ - public static function createMediaEntity(FileInterface $file, string $bundle) { - if ($file) { - $media_helper = \Drupal::getContainer()->get('govcms_media.media_helper'); - $media_entity = $media_helper->createFromInput($file, [$bundle]); - - if ($media_entity) { - $media_entity->save(); - - return $media_entity; - } - else { - throw new UpdateException(sprintf('Unable to create media entity %s.', $file->getFilename())); - } - } - - return FALSE; - } - - /** - * Attach a body field to the node. - * - * @param \Drupal\node\Entity\Node $node - * The node to attach the content to. Passed in as a reference. - * @param string $value - * The value of the body field. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function nodeAttachFieldBody(Node &$node, string $value) { - $body_values = [ - 'field_body' => [ - 'value' => $value, - 'format' => 'rich_text', - ], - ]; - - $paragraph = self::createParagraph('content', $body_values); - $node->field_components->appendItem($paragraph); - } - - /** - * Attach tile list to the node. - * - * @param \Drupal\node\Entity\Node $node - * The node to attach the content to. Passed in as a reference. - * @param array $component - * An array of $component details. - * @param bool $use_stub - * Whether or not stubs should be created as part of this. - * - * @SuppressWarnings(PHPMD.MissingImport) - */ - public static function nodeAttachTileList(Node &$node, array $component, bool $use_stub = FALSE) { - $defaults = [ - 'field_p_tl_layout' => 'single_row', - 'field_p_tl_show_tile_as' => 'default', - 'items' => [], - 'field_p_tl_cta' => NULL, - 'field_p_tl_bg_left' => NULL, - 'field_p_tl_bg_right' => NULL, - 'field_p_tl_fill_parent_width' => NULL, - 'field_p_tl_title' => NULL, - 'field_p_tl_industry' => NULL, - ]; - - $component += $defaults; - - if (empty($component['items'])) { - return; - } - - foreach ($component['items'] as $tile) { - if (!empty($tile['cta']['uri']) && !UrlHelper::isExternal($tile['cta']['uri'])) { - $found_node = self::findNodeByAlias($tile['cta']['uri']); - if ($found_node) { - $tile['cta']['uri'] = 'internal:' . $tile['cta']['uri']; - } - elseif ($use_stub) { - $tile['cta']['uri'] = 'internal:' . self::createPageStub($tile['heading'], $tile['cta']['uri']); - } - else { - throw new \Exception(sprintf('Unable to find a non-stubbed node with alias "%s".', $tile['cta']['uri'])); - } - } - - $tile_paragraph = self::createTileParagraph($tile); - if ($tile_paragraph) { - $tile_paragraphs[] = $tile_paragraph; - } - } - - if (empty($tile_paragraphs)) { - return; - } - - $content = [ - 'field_p_tl_items' => $tile_paragraphs, - 'field_p_tl_layout' => $component['field_p_tl_layout'], - 'field_p_tl_show_tile_as' => $component['field_p_tl_show_tile_as'], - ]; - - if (!empty($component['field_p_tl_bg_left'])) { - $content['field_p_tl_bg_left'] = self::loadMediaByName($component['field_p_tl_bg_left'], 'image'); - } - - if (!empty($component['field_p_tl_bg_right'])) { - $content['field_p_tl_bg_right'] = self::loadMediaByName($component['field_p_tl_bg_right'], 'image'); - } - - if (!empty($component['field_p_tl_fill_parent_width'])) { - $content['field_p_tl_fill_parent_width'] = $component['field_p_tl_fill_parent_width']; - } - - if (!empty($component['field_p_tl_title'])) { - $content['field_p_tl_title'] = $component['field_p_tl_title']; - } - - if (!empty($component['field_p_tl_industry'])) { - $content['field_p_tl_industry'] = self::getTermByName('industries', $component['field_p_tl_industry']); - } - - if (!empty($component['field_p_tl_cta'])) { - if (!UrlHelper::isExternal($component['field_p_tl_cta']['uri'])) { - $component['field_p_tl_cta']['uri'] = 'internal:' . $component['field_p_tl_cta']['uri']; - } - $content['field_p_tl_cta'] = $component['field_p_tl_cta']; - } - - $tile_list_paragraph = self::createParagraph('tile_list', $content); - - $node->field_components->appendItem($tile_list_paragraph); - } - - /** - * Attach listing to the node. - * - * @param \Drupal\node\Entity\Node $node - * The node to attach the listing to. Passed in as a reference. - * @param array $listing_details - * An array of listing details to be created as a listing paragraph. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function nodeAttachListing(Node &$node, array $listing_details) { - if (!empty($listing_details['field_p_l_read_more']['uri']) && !UrlHelper::isExternal($listing_details['field_p_l_read_more']['uri'])) { - $listing_details['field_p_l_read_more']['uri'] = 'internal:' . $listing_details['field_p_l_read_more']['uri']; - } - - if (!empty($listing_details['field_p_l_industry'])) { - foreach ($listing_details['field_p_l_industry'] as &$industry) { - $term = self::getTermByName('industries', $industry); - if (!empty($term)) { - $industry = $term->id(); - } - } - } - - $listing_paragraph = self::createParagraph('listing', $listing_details); - $node->field_components->appendItem($listing_paragraph); - } - - /** - * Attach promo to the node. - * - * @param \Drupal\node\Entity\Node $node - * The node to attach the promo to. Passed in as a reference. - * @param array $values - * An array of promo details to be created as a promo paragraph. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function nodeAttachPromo(Node &$node, array $values) { - if (!empty($values['field_p_pr_cta']['uri']) && !UrlHelper::isExternal($values['field_p_pr_cta']['uri'])) { - $values['field_p_pr_cta']['uri'] = 'internal:' . $values['field_p_pr_cta']['uri']; - } - if (!empty($values['field_p_pr_image'])) { - $values['field_p_pr_image'] = self::loadMediaByName($values['field_p_pr_image'], 'image'); - } - - if (!empty($values['field_p_pr_icon'])) { - $values['field_p_pr_icon'] = self::loadMediaByName($values['field_p_pr_icon'], 'image'); - } - - if (empty($values['field_p_pr_style'])) { - $values['field_p_pr_style'] = 'light'; - } - - $promo_paragraph = self::createParagraph('promo', $values); - $node->field_components->appendItem($promo_paragraph); - } - - /** - * Attach block placement to the node. - * - * @param \Drupal\node\Entity\Node $node - * The node to attach the block to. Passed in as a reference. - * @param string $block_name - * The name of the block to attach. - * - * @throws \Drupal\Core\Entity\EntityStorageException - */ - public static function nodeAttachBlockPlacement(Node &$node, string $block_name) { - $block = self::loadBlockContentByName($block_name); - if (!empty($block)) { - $block_paragraph = self::createParagraph('block_placement', ['field_bp_block' => $block]); - $node->field_components->appendItem($block_paragraph); - } - } - - /** - * Load block_content entity ID by name. - * - * @param string $block_name - * Block content name. - * - * @return array|int - * Block ID or FALSE if block content cannot be found. - */ - public static function loadBlockContentByName($block_name) { - return \Drupal::entityQuery('block_content') - ->condition('info', $block_name) - ->execute(); - } - -} diff --git a/web/modules/custom/civictheme_dev/src/Plugin/ConfigFilter/CivicthemeDevIgnoreFilter.php b/web/modules/custom/civictheme_dev/src/Plugin/ConfigFilter/CivicthemeDevIgnoreFilter.php index d62388681..68e64d915 100644 --- a/web/modules/custom/civictheme_dev/src/Plugin/ConfigFilter/CivicthemeDevIgnoreFilter.php +++ b/web/modules/custom/civictheme_dev/src/Plugin/ConfigFilter/CivicthemeDevIgnoreFilter.php @@ -25,10 +25,15 @@ class CivicthemeDevIgnoreFilter extends IgnoreFilter implements ContainerFactory /** * {@inheritdoc} + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) */ - public function filterWrite($name, array $data) { + public function filterWrite($name, array $data): array { // Exclude permissions and dependencies for user roles. // phpcs:disable Drupal.Functions.DiscouragedFunctions.Discouraged + // @phpstan-ignore-next-line if (fnmatch('user.role.*', $name)) { $role_name = substr($name, strlen('user.role.')); @@ -54,11 +59,13 @@ public function filterWrite($name, array $data) { } // Exclude hidden fields added by the optional modules. + // @phpstan-ignore-next-line if (fnmatch('core.entity_view_display.*', $name)) { unset($data['hidden']['search_api_excerpt']); } // Exclude processing for some properties of the blocks. + // @phpstan-ignore-next-line if (fnmatch('block.block.civictheme_*', $name)) { // Unset dependencies. unset($data['dependencies']['content']); @@ -76,12 +83,13 @@ public function filterWrite($name, array $data) { } // Exclude processing for some properties of the views. + // @phpstan-ignore-next-line if (fnmatch('views.view.civictheme_*', $name) && !str_contains($name, 'example') && !str_contains($name, 'test')) { if (!empty($data['display'])) { foreach (array_keys($data['display']) as $display_name) { if (!empty($data['display'][$display_name]['display_options']['display_extenders'])) { foreach (array_keys($data['display'][$display_name]['display_options']['display_extenders']) as $extender_name) { - if (str_starts_with($extender_name, 'simple_sitemap')) { + if (str_starts_with((string) $extender_name, 'simple_sitemap')) { unset($data['display'][$display_name]['display_options']['display_extenders'][$extender_name]); } } @@ -102,10 +110,10 @@ public function filterWrite($name, array $data) { * @param string $role_name * Role machine name. * - * @return array + * @return array * Array of excluded permissions. */ - protected function getExcludedRolePermissions($role_name) { + protected function getExcludedRolePermissions(string $role_name): array { $permissions = []; $map = $this->getRolePermissionsMap(); @@ -127,10 +135,10 @@ protected function getExcludedRolePermissions($role_name) { * @param string $role_name * Role machine name. * - * @return array + * @return array. * Array of excluded dependency modules. */ - protected function getExcludedRoleDependencyModules($role_name) { + protected function getExcludedRoleDependencyModules(string $role_name): array { $modules = []; $map = $this->getRolePermissionsMap(); @@ -150,12 +158,13 @@ protected function getExcludedRoleDependencyModules($role_name) { * @param array $permissions * Array of permissions. * - * @return array + * @return array * Array of providers. */ - protected function getPermissionsProviders(array $permissions) { + protected function getPermissionsProviders(array $permissions): array { $modules = []; + // @phpstan-ignore-next-line $permissions_data = \Drupal::service('user.permissions')->getPermissions(); foreach ($permissions as $permission) { @@ -174,8 +183,12 @@ protected function getPermissionsProviders(array $permissions) { * * This allows to centrally manage additional permissions that may be * optionally provisioned for specific roles. + * + * @return array>> + * Array of excluded dependency modules. */ - protected function getRolePermissionsMap() { + protected function getRolePermissionsMap(): array { + // @phpstan-ignore-next-line $civictheme_path = \Drupal::service('extension.list.theme')->getPath('civictheme'); $provision_file = $civictheme_path . DIRECTORY_SEPARATOR . 'theme-settings.provision.inc'; if (!file_exists($provision_file)) { diff --git a/web/modules/custom/civictheme_govcms/src/CivicthemeGovcmsManager.php b/web/modules/custom/civictheme_govcms/src/CivicthemeGovcmsManager.php index 993739031..e9c5a18cb 100644 --- a/web/modules/custom/civictheme_govcms/src/CivicthemeGovcmsManager.php +++ b/web/modules/custom/civictheme_govcms/src/CivicthemeGovcmsManager.php @@ -10,21 +10,19 @@ /** * Defines a civictheme_govcms govcms manager. */ -class CivicthemeGovcmsManager { +final class CivicthemeGovcmsManager { /** * The list of removal configurations(methods). * - * @var array + * @var array */ - protected $removalList; + protected array $removalList; /** * The entity type manager. - * - * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ - protected $entityTypeManager; + protected EntityTypeManagerInterface $entityTypeManager; /** * Constructs a GovcmsManager Manager object. @@ -53,8 +51,8 @@ public function __construct( /** * {@inheritdoc} */ - public static function create(ContainerInterface $container) { - return new static( + public static function create(ContainerInterface $container): self { + return new self( $container->get('entity_type.manager') ); } @@ -65,7 +63,7 @@ public static function create(ContainerInterface $container) { * @param string $preserve * The list of config types to preserve. */ - public function civicthemeGovcmsRemoveConfig(string $preserve = '') { + public function civicthemeGovcmsRemoveConfig(string $preserve = ''): void { $preserve_list = []; if (!empty($preserve)) { $preserve_list = explode(',', $preserve); @@ -80,7 +78,7 @@ public function civicthemeGovcmsRemoveConfig(string $preserve = '') { /** * Removes vanilla media types. */ - protected function removeGovcmsMediaTypes() { + protected function removeGovcmsMediaTypes(): void { $names = [ 'audio', 'document', @@ -100,7 +98,7 @@ protected function removeGovcmsMediaTypes() { /** * Removes vanilla text formats. */ - protected function removeGovcmsTextFormat() { + protected function removeGovcmsTextFormat(): void { $names = [ 'plain_text', 'rich_text', @@ -116,8 +114,11 @@ protected function removeGovcmsTextFormat() { /** * Removes GovCMS fields. + * + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.StaticAccess) */ - protected function removeGovcmsFields() { + protected function removeGovcmsFields(): void { // A list of shared fields that should be deleted before deleting // types. Non-shared fields will be removed when content types are removed. // @@ -184,7 +185,7 @@ protected function removeGovcmsFields() { /** * Removes GovCMS content types. */ - protected function removeGovcmsContentTypes() { + protected function removeGovcmsContentTypes(): void { $names = [ 'govcms_blog_article', 'govcms_event', @@ -204,7 +205,7 @@ protected function removeGovcmsContentTypes() { /** * Removes GovCMS vocabularies. */ - protected function removeGovcmsVocabularies() { + protected function removeGovcmsVocabularies(): void { $names = [ 'govcms_blog_article_categories', 'govcms_event_categories', @@ -223,7 +224,7 @@ protected function removeGovcmsVocabularies() { /** * Removes GovCMS user roles. */ - protected function removeGovcmsUserRoles() { + protected function removeGovcmsUserRoles(): void { $names = [ 'govcms_site_administrator', 'govcms_content_approver', @@ -241,7 +242,7 @@ protected function removeGovcmsUserRoles() { /** * Removes GovCMS menus. */ - protected function removeGovcmsMenus() { + protected function removeGovcmsMenus(): void { $names = [ 'govcms-about', 'govcms-community', @@ -260,7 +261,7 @@ protected function removeGovcmsMenus() { /** * Removes GovCMS Pathauto patterns. */ - protected function removeGovcmsPathautoPatterns() { + protected function removeGovcmsPathautoPatterns(): void { $names = [ 'blog_article', 'event', @@ -280,7 +281,7 @@ protected function removeGovcmsPathautoPatterns() { /** * Removes GovCMS Workflows patterns. */ - protected function removeGovcmsWorkflows() { + protected function removeGovcmsWorkflows(): void { $names = [ 'editorial', ]; diff --git a/web/modules/custom/civictheme_govcms/src/Commands/CivicthemeGovcmsCommands.php b/web/modules/custom/civictheme_govcms/src/Commands/CivicthemeGovcmsCommands.php index 595911f8a..a676ba52c 100644 --- a/web/modules/custom/civictheme_govcms/src/Commands/CivicthemeGovcmsCommands.php +++ b/web/modules/custom/civictheme_govcms/src/Commands/CivicthemeGovcmsCommands.php @@ -15,10 +15,8 @@ class CivicthemeGovcmsCommands extends DrushCommands { /** * The Govcms Manager service. - * - * @var \Drupal\civictheme_govcms\CivicthemeGovcmsManager */ - protected $govcmsManager; + protected CivicthemeGovcmsManager $govcmsManager; /** * Migration commands constructor. @@ -54,7 +52,7 @@ public function __construct(CivicthemeGovcmsManager $govcms_manager) { */ public function drushCivicthemeGovcmsRemoveConfig(array $options = [ 'preserve' => '', - ]) { + ]): void { // Removing configs will lead to showing warnings about missing bundles, // which are only shown due to dependencies resolution concurrency issues. // We are suppressing them as they do not have any valuable information diff --git a/web/modules/custom/cs_generated_content/cs_generated_content.install b/web/modules/custom/cs_generated_content/cs_generated_content.install index 536eb9fd7..9335b79c8 100644 --- a/web/modules/custom/cs_generated_content/cs_generated_content.install +++ b/web/modules/custom/cs_generated_content/cs_generated_content.install @@ -12,7 +12,7 @@ use Drupal\redirect\Entity\Redirect; /** * Implements hook_install(). */ -function cs_generated_content_install() { +function cs_generated_content_install(): void { // Create menu item. $menu_link = MenuLinkContent::create([ 'menu_name' => 'civictheme-secondary-navigation', diff --git a/web/modules/custom/cs_generated_content/generated_content/file/file.inc b/web/modules/custom/cs_generated_content/generated_content/file/file.inc index 0833c3797..471ca9531 100644 --- a/web/modules/custom/cs_generated_content/generated_content/file/file.inc +++ b/web/modules/custom/cs_generated_content/generated_content/file/file.inc @@ -13,21 +13,24 @@ use Drupal\generated_content\Helpers\GeneratedContentHelper; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_file_file_weight() { +function cs_generated_content_generated_content_create_file_file_weight(): int { return -10; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_file_file_tracking() { +function cs_generated_content_generated_content_create_file_file_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_file_file() { +function cs_generated_content_generated_content_create_file_file(): array { /** @var \Drupal\generated_content\Helpers\GeneratedContentHelper $helper */ $helper = GeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_document.inc b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_document.inc index dcc4720d3..3e4afe661 100644 --- a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_document.inc +++ b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_document.inc @@ -13,21 +13,24 @@ use Drupal\media\Entity\Media; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_media_civictheme_document_weight() { +function cs_generated_content_generated_content_create_media_civictheme_document_weight(): int { return 10; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_media_civictheme_document_tracking() { +function cs_generated_content_generated_content_create_media_civictheme_document_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_media_civictheme_document() { +function cs_generated_content_generated_content_create_media_civictheme_document(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_icon.inc b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_icon.inc index 3b2e1fd48..fca172f37 100644 --- a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_icon.inc +++ b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_icon.inc @@ -13,21 +13,24 @@ use Drupal\media\Entity\Media; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_media_civictheme_icon_weight() { +function cs_generated_content_generated_content_create_media_civictheme_icon_weight(): int { return 11; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_media_civictheme_icon_tracking() { +function cs_generated_content_generated_content_create_media_civictheme_icon_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_media_civictheme_icon() { +function cs_generated_content_generated_content_create_media_civictheme_icon(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_image.inc b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_image.inc index 2e37e8778..d0cd26ce1 100644 --- a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_image.inc +++ b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_image.inc @@ -13,21 +13,24 @@ use Drupal\media\Entity\Media; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_media_civictheme_image_weight() { +function cs_generated_content_generated_content_create_media_civictheme_image_weight(): int { return 12; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_media_civictheme_image_tracking() { +function cs_generated_content_generated_content_create_media_civictheme_image_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_media_civictheme_image() { +function cs_generated_content_generated_content_create_media_civictheme_image(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); @@ -51,6 +54,7 @@ function cs_generated_content_generated_content_create_media_civictheme_image() 'target_id' => $file->id(), 'alt' => sprintf('Alt for %s', $name), ]); + // @phpstan-ignore-next-line $media->field_c_m_caption = $helper::staticSentence(2); $media->save(); diff --git a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_video.inc b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_video.inc index 3c9399b9b..e9e661f22 100644 --- a/web/modules/custom/cs_generated_content/generated_content/media/civictheme_video.inc +++ b/web/modules/custom/cs_generated_content/generated_content/media/civictheme_video.inc @@ -13,21 +13,24 @@ use Drupal\media\Entity\Media; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_media_civictheme_video_weight() { +function cs_generated_content_generated_content_create_media_civictheme_video_weight(): int { return 13; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_media_civictheme_video_tracking() { +function cs_generated_content_generated_content_create_media_civictheme_video_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_media_civictheme_video() { +function cs_generated_content_generated_content_create_media_civictheme_video(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); @@ -51,6 +54,7 @@ function cs_generated_content_generated_content_create_media_civictheme_video() 'target_id' => $file->id(), 'alt' => sprintf('Alt for %s', $name), ]); + // @phpstan-ignore-next-line $media->field_c_m_transcript = $helper::staticSentence(2); $media->save(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event.inc index aeff0ca26..676a4f443 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event.inc @@ -7,25 +7,30 @@ use Drupal\Core\Link; use Drupal\cs_generated_content\CsGeneratedContentHelper; +use Drupal\node\NodeInterface; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_node_civictheme_event_weight() { +function cs_generated_content_generated_content_create_node_civictheme_event_weight(): int { return 31; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_node_civictheme_event_tracking() { +function cs_generated_content_generated_content_create_node_civictheme_event_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ElseExpression) */ -function cs_generated_content_generated_content_create_node_civictheme_event() { +function cs_generated_content_generated_content_create_node_civictheme_event(): array { $nodes = []; /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ @@ -40,7 +45,7 @@ function cs_generated_content_generated_content_create_node_civictheme_event() { require_once __DIR__ . DIRECTORY_SEPARATOR . 'civictheme_event_variations/01.helpers.inc'; for ($i = 0; $i < 20; $i++) { $variations[] = [ - 'title' => sprintf('Event %s. %s', str_pad($i + 1, 2, '0', STR_PAD_LEFT), $helper::staticSentence(3)), + 'title' => sprintf('Event %s. %s', str_pad((string) ($i + 1), 2, '0', STR_PAD_LEFT), $helper::staticSentence(3)), 'thumbnail' => $helper::staticMediaItem('civictheme_image'), 'summary' => 'Summary ' . $helper::staticSentence(20), 'topics' => $helper::staticTerms('civictheme_topics', 1), @@ -80,6 +85,7 @@ function cs_generated_content_generated_content_create_node_civictheme_event() { $node = $helper::variationCreateNode('civictheme_event', $variation, $i, '_cs_generated_content_create_node_civictheme_event__variation_to_fields'); $variation_info = $helper::variationFormatInfo($variation); + // @phpstan-ignore-next-line $node->revision_log = 'Generated content. ' . $variation_info; $node->save(); @@ -105,8 +111,12 @@ function cs_generated_content_generated_content_create_node_civictheme_event() { /** * Processor to convert variation values to 'civictheme_event' node fields. + * + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_event__variation_to_fields($node, $variation) { +function _cs_generated_content_create_node_civictheme_event__variation_to_fields(NodeInterface $node, array $variation): void { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/01.helpers.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/01.helpers.inc index c46d74ee8..501c060c6 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/01.helpers.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/01.helpers.inc @@ -9,8 +9,16 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Variations post-process callback. + * + * @param array $variations + * Variations to post-process. + * + * @return array + * Post-processed variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_event__variations__post_process($variations) { +function _cs_generated_content_create_node_civictheme_event__variations__post_process(array $variations): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); @@ -29,8 +37,13 @@ function _cs_generated_content_create_node_civictheme_event__variations__post_pr /** * Default values for Content component to use in variations. + * + * @return array> + * Default values for Content component. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_event__variations_components_content_default() { +function _cs_generated_content_create_node_civictheme_event__variations_components_content_default(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/02.general.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/02.general.inc index 95d6ab46d..c4334c5d4 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/02.general.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/02.general.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Event, General. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_event__variations__general() { +function _cs_generated_content_create_node_civictheme_event__variations__general(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.attachment.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.attachment.inc index 87d64e7a0..eb883c92d 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.attachment.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.attachment.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Event, Attachments - Attachment. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_event__variations__component_attachment() { +function _cs_generated_content_create_node_civictheme_event__variations__component_attachment(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.map.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.map.inc index 9dd83ad51..dba5b4d95 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.map.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_event_variations/component.map.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Event, Location - Map. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_event__variations__component_map() { +function _cs_generated_content_create_node_civictheme_event__variations__component_map(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page.inc index 774e72067..94e4f4adf 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page.inc @@ -7,25 +7,30 @@ use Drupal\Core\Link; use Drupal\cs_generated_content\CsGeneratedContentHelper; +use Drupal\node\NodeInterface; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_node_civictheme_page_weight() { +function cs_generated_content_generated_content_create_node_civictheme_page_weight(): int { return 32; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_node_civictheme_page_tracking() { +function cs_generated_content_generated_content_create_node_civictheme_page_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ElseExpression) */ -function cs_generated_content_generated_content_create_node_civictheme_page() { +function cs_generated_content_generated_content_create_node_civictheme_page(): array { $nodes = []; /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ @@ -40,7 +45,7 @@ function cs_generated_content_generated_content_create_node_civictheme_page() { require_once __DIR__ . DIRECTORY_SEPARATOR . 'civictheme_page_variations/01.helpers.inc'; for ($i = 0; $i < 20; $i++) { $variations[] = [ - 'title' => sprintf('Page %s. %s', str_pad($i + 1, 2, '0', STR_PAD_LEFT), $helper::staticSentence(3)), + 'title' => sprintf('Page %s. %s', str_pad((string) ($i + 1), 2, '0', STR_PAD_LEFT), $helper::staticSentence(3)), 'thumbnail' => $helper::staticMediaItem('civictheme_image'), 'summary' => 'Summary ' . $helper::staticSentence(100), 'topics' => $helper::staticTerms('civictheme_topics', 1), @@ -67,6 +72,7 @@ function cs_generated_content_generated_content_create_node_civictheme_page() { $node = $helper::variationCreateNode('civictheme_page', $variation, $i, '_cs_generated_content_create_node_civictheme_page__variation_to_fields'); $variation_info = $helper::variationFormatInfo($variation); + // @phpstan-ignore-next-line $node->revision_log = 'Generated content. ' . $variation_info; $node->save(); @@ -92,8 +98,13 @@ function cs_generated_content_generated_content_create_node_civictheme_page() { /** * Processor to convert variation values to 'civictheme_page' node fields. + * + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function _cs_generated_content_create_node_civictheme_page__variation_to_fields($node, $variation) { +function _cs_generated_content_create_node_civictheme_page__variation_to_fields(NodeInterface $node, array $variation): void { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/01.helpers.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/01.helpers.inc index 03dc3e71b..8b05ce93a 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/01.helpers.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/01.helpers.inc @@ -9,8 +9,16 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Variations post-process callback. + * + * @param array $variations + * Variations to post-process. + * + * @return array> + * Post-processed variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__post_process($variations) { +function _cs_generated_content_create_node_civictheme_page__variations__post_process(array $variations): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); @@ -29,8 +37,13 @@ function _cs_generated_content_create_node_civictheme_page__variations__post_pro /** * Default values for Content component to use in variations. + * + * @return array> + * Default values for Content component. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations_components_content_default() { +function _cs_generated_content_create_node_civictheme_page__variations_components_content_default(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/02.general.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/02.general.inc index 1bfcd0c3e..5a202dbda 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/02.general.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/02.general.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, General. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__general() { +function _cs_generated_content_create_node_civictheme_page__variations__general(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/03.banner.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/03.banner.inc index 33911501a..b12cc6833 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/03.banner.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/03.banner.inc @@ -9,8 +9,14 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Banner. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function _cs_generated_content_create_node_civictheme_page__variations__banner() { +function _cs_generated_content_create_node_civictheme_page__variations__banner(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.accordion.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.accordion.inc index e323664d9..b15adbbc5 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.accordion.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.accordion.inc @@ -9,8 +9,14 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Accordion. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_accordion() { +function _cs_generated_content_create_node_civictheme_page__variations__component_accordion(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.attachment.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.attachment.inc index dd31561c4..b2d64a73b 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.attachment.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.attachment.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Attachment. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_attachment() { +function _cs_generated_content_create_node_civictheme_page__variations__component_attachment(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.automated_list.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.automated_list.inc index 69e0825b7..81a453e57 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.automated_list.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.automated_list.inc @@ -9,8 +9,14 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Automated list. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_automated_list() { +function _cs_generated_content_create_node_civictheme_page__variations__component_automated_list(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.callout.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.callout.inc index 8e30aad53..6c3b5f427 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.callout.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.callout.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Callout. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_callout() { +function _cs_generated_content_create_node_civictheme_page__variations__component_callout(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.campaign.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.campaign.inc index 55e73b1ad..2f76e3f7e 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.campaign.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.campaign.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Campaign. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_campaign() { +function _cs_generated_content_create_node_civictheme_page__variations__component_campaign(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.cards.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.cards.inc index 040720436..10f2149fd 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.cards.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.cards.inc @@ -9,8 +9,14 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Cards. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function _cs_generated_content_create_node_civictheme_page__variations__cards() { +function _cs_generated_content_create_node_civictheme_page__variations__cards(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.content.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.content.inc index 01aca839f..6b50d0bd3 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.content.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.content.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Content. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_content() { +function _cs_generated_content_create_node_civictheme_page__variations__component_content(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.iframe.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.iframe.inc index 3629ee1da..3594b1243 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.iframe.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.iframe.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Iframe. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_iframe() { +function _cs_generated_content_create_node_civictheme_page__variations__component_iframe(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.manual_list.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.manual_list.inc index 8a24952ef..cb5143482 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.manual_list.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.manual_list.inc @@ -9,8 +9,14 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Manual list. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function _cs_generated_content_create_node_civictheme_page__variations__manual_list() { +function _cs_generated_content_create_node_civictheme_page__variations__manual_list(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.map.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.map.inc index d23640860..83ffd6e81 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.map.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.map.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Map. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_map() { +function _cs_generated_content_create_node_civictheme_page__variations__component_map(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.next_step.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.next_step.inc index 92ee04c31..22540cf58 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.next_step.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.next_step.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Next Step. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_next_step() { +function _cs_generated_content_create_node_civictheme_page__variations__component_next_step(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.promo.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.promo.inc index ec6610651..d4fe2db31 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.promo.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.promo.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Promo. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_promo() { +function _cs_generated_content_create_node_civictheme_page__variations__component_promo(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.quote.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.quote.inc index f17e3ba7b..7511fc510 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.quote.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.quote.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Quote. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_quote() { +function _cs_generated_content_create_node_civictheme_page__variations__component_quote(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.slider.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.slider.inc index 5783d7f5c..63799878b 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.slider.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.slider.inc @@ -9,8 +9,14 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Slider. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_slider() { +function _cs_generated_content_create_node_civictheme_page__variations__component_slider(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.webform.inc b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.webform.inc index 98585d3a1..a29a92e03 100644 --- a/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.webform.inc +++ b/web/modules/custom/cs_generated_content/generated_content/node/civictheme_page_variations/component.webform.inc @@ -9,8 +9,13 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Page, Components - Webform. + * + * @return array> + * Variations. + * + * @SuppressWarnings(PHPMD.StaticAccess) */ -function _cs_generated_content_create_node_civictheme_page__variations__component_webform() { +function _cs_generated_content_create_node_civictheme_page__variations__component_webform(): array { /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ $helper = CsGeneratedContentHelper::getInstance(); diff --git a/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_site_sections.inc b/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_site_sections.inc index 56cf4314a..022df56f7 100644 --- a/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_site_sections.inc +++ b/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_site_sections.inc @@ -11,21 +11,24 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_taxonomy_term_civictheme_site_sections_weight() { +function cs_generated_content_generated_content_create_taxonomy_term_civictheme_site_sections_weight(): int { return 25; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_taxonomy_term_civictheme_site_sections_tracking() { +function cs_generated_content_generated_content_create_taxonomy_term_civictheme_site_sections_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_taxonomy_term_civictheme_site_sections() { +function cs_generated_content_generated_content_create_taxonomy_term_civictheme_site_sections(): array { $total_terms_count = 10; /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ diff --git a/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_topics.inc b/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_topics.inc index 0d835b796..74dc9c001 100644 --- a/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_topics.inc +++ b/web/modules/custom/cs_generated_content/generated_content/taxonomy_term/civictheme_topics.inc @@ -11,21 +11,24 @@ use Drupal\cs_generated_content\CsGeneratedContentHelper; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_taxonomy_term_civictheme_topics_weight() { +function cs_generated_content_generated_content_create_taxonomy_term_civictheme_topics_weight(): int { return 20; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_taxonomy_term_civictheme_topics_tracking() { +function cs_generated_content_generated_content_create_taxonomy_term_civictheme_topics_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_taxonomy_term_civictheme_topics() { +function cs_generated_content_generated_content_create_taxonomy_term_civictheme_topics(): array { $total_terms_count = 10; /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ diff --git a/web/modules/custom/cs_generated_content/generated_content/user/user.inc b/web/modules/custom/cs_generated_content/generated_content/user/user.inc index df8ab9709..19549026c 100644 --- a/web/modules/custom/cs_generated_content/generated_content/user/user.inc +++ b/web/modules/custom/cs_generated_content/generated_content/user/user.inc @@ -6,6 +6,7 @@ */ use Drupal\Core\Link; +use Drupal\Core\Utility\Error; use Drupal\cs_generated_content\CsGeneratedContentHelper; use Drupal\user\Entity\Role; use Drupal\user\Entity\User; @@ -13,21 +14,24 @@ use Drupal\user\Entity\User; /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_weight(). */ -function cs_generated_content_generated_content_create_user_user_weight() { +function cs_generated_content_generated_content_create_user_user_weight(): int { return 0; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE_tracking(). */ -function cs_generated_content_generated_content_create_user_user_tracking() { +function cs_generated_content_generated_content_create_user_user_tracking(): bool { return TRUE; } /** * Implements hook_generated_content_create_ENTITY_TYPE_BUNDLE(). + * + * @phpstan-ignore-next-line + * @SuppressWarnings(PHPMD.StaticAccess) */ -function cs_generated_content_generated_content_create_user_user() { +function cs_generated_content_generated_content_create_user_user(): array { $total_users_per_role = 3; /** @var \Drupal\cs_generated_content\CsGeneratedContentHelper $helper */ @@ -44,37 +48,43 @@ function cs_generated_content_generated_content_create_user_user() { } for ($i = 1; $i <= $total_users_per_role; $i++) { - $name = sprintf('p.civictheme+%s_%s@salsadigital.com.au', str_replace('civictheme_', '', $role->id()), $i); + $role_id = (string) $role->id(); - $existing_user = user_load_by_name($name); - if ($existing_user) { - \Drupal::entityTypeManager()->getStorage('user')->load($existing_user->id())->delete(); - } + if (!empty($role_id)) { + + $name = sprintf('p.civictheme+%s_%s@salsadigital.com.au', str_replace('civictheme_', '', $role_id), $i); - if (Role::load($role->id())) { - $user = User::create(); - $user->setUsername($name); - $user->setEmail($name); - $user->addRole($role->id()); - $user->activate(); - $user->enforceIsNew(); - if (!empty(getenv('DRUPAL_CS_GENERATED_CONTENT_USER_PASSWORD'))) { - $user->setPassword(getenv('DRUPAL_CS_GENERATED_CONTENT_USER_PASSWORD')); + $existing_user = user_load_by_name($name); + if ($existing_user) { + \Drupal::entityTypeManager()->getStorage('user')->load($existing_user->id())->delete(); } - try { - $user->save(); - $users[] = $user; + if (Role::load($role_id)) { + $user = User::create(); + $user->setUsername($name); + $user->setEmail($name); + $user->addRole($role_id); + $user->activate(); + $user->enforceIsNew(); + if (!empty(getenv('DRUPAL_CS_GENERATED_CONTENT_USER_PASSWORD'))) { + $user->setPassword(getenv('DRUPAL_CS_GENERATED_CONTENT_USER_PASSWORD')); + } - $helper::log( - 'Created an account %s [ID: %s] %s', - Link::createFromRoute($user->getDisplayName(), 'entity.user.canonical', ['user' => $user->id()])->toString(), - $user->id(), - Link::createFromRoute('Edit', 'entity.user.edit_form', ['user' => $user->id()])->toString() - ); - } - catch (\Exception $exception) { - watchdog_exception('cs_generated_content', $exception); + try { + $user->save(); + $users[] = $user; + + $helper::log( + 'Created an account %s [ID: %s] %s', + Link::createFromRoute($user->getDisplayName(), 'entity.user.canonical', ['user' => $user->id()])->toString(), + $user->id(), + Link::createFromRoute('Edit', 'entity.user.edit_form', ['user' => $user->id()])->toString() + ); + } + catch (\Exception $exception) { + $logger = \Drupal::logger('cs_generated_content'); + Error::logException($logger, $exception); + } } } } diff --git a/web/modules/custom/cs_generated_content/src/CsGeneratedContentAssetGenerator.php b/web/modules/custom/cs_generated_content/src/CsGeneratedContentAssetGenerator.php index 10a78abbf..c12e2b7ca 100644 --- a/web/modules/custom/cs_generated_content/src/CsGeneratedContentAssetGenerator.php +++ b/web/modules/custom/cs_generated_content/src/CsGeneratedContentAssetGenerator.php @@ -16,7 +16,7 @@ class CsGeneratedContentAssetGenerator extends GeneratedContentAssetGenerator { /** * {@inheritdoc} */ - protected function getAssetsDirs() { + protected function getAssetsDirs(): array { $module_path = $this->moduleExtensionList->getPath('cs_generated_content'); return [ diff --git a/web/modules/custom/cs_generated_content/src/CsGeneratedContentCivicthemeTrait.php b/web/modules/custom/cs_generated_content/src/CsGeneratedContentCivicthemeTrait.php index 077d41f47..89a8b74c4 100644 --- a/web/modules/custom/cs_generated_content/src/CsGeneratedContentCivicthemeTrait.php +++ b/web/modules/custom/cs_generated_content/src/CsGeneratedContentCivicthemeTrait.php @@ -2,89 +2,97 @@ namespace Drupal\cs_generated_content; +use Drupal\Core\Entity\FieldableEntityInterface; +use Drupal\node\NodeInterface; use Drupal\paragraphs\Entity\Paragraph; +use Drupal\taxonomy\Entity\Term; /** * Trait CsGeneratedContentTrait. * * Trait for centralised CivicTheme components handling. + * + * @SuppressWarnings(PHPMD.ExcessivePublicCount) */ trait CsGeneratedContentCivicthemeTrait { /** * Light theme name. */ - public static function civicthemeThemeLight() { + public static function civicthemeThemeLight(): string { return 'light'; } /** * Dark theme name. */ - public static function civicthemeThemeDark() { + public static function civicthemeThemeDark(): string { return 'dark'; } /** * Page content type name. */ - public static function civicthemePageContentType() { + public static function civicthemePageContentType(): string { return 'civictheme_page'; } /** * Event content type name. */ - public static function civicthemeEventContentType() { + public static function civicthemeEventContentType(): string { return 'civictheme_event'; } /** * Default Automated list view name. */ - public static function civicthemeAutomatedListType() { + public static function civicthemeAutomatedListType(): string { return 'civictheme_automated_list__block1'; } /** * Limited type name. */ - public static function civicthemeAutomatedListLimitTypeLimited() { + public static function civicthemeAutomatedListLimitTypeLimited(): string { return 'limited'; } /** * Unlimited type name. */ - public static function civicthemeAutomatedListLimitTypeUnlimited() { + public static function civicthemeAutomatedListLimitTypeUnlimited(): string { return 'unlimited'; } /** * Promo card type name. */ - public static function civicthemePromoCardType() { + public static function civicthemePromoCardType(): string { return 'civictheme_promo_card'; } /** * Navigation card type name. */ - public static function civicthemeNavigationCardType() { + public static function civicthemeNavigationCardType(): string { return 'civictheme_navigation_card'; } /** * Snippet type name. */ - public static function civicthemeSnippetType() { + public static function civicthemeSnippetType(): string { return 'civictheme_snippet'; } /** * Available theme names. + * + * @return array + * Theme names. */ - public static function civicthemeThemes() { + public static function civicthemeThemes(): array { return [ static::civicthemeThemeLight(), static::civicthemeThemeDark(), @@ -94,35 +102,38 @@ public static function civicthemeThemes() { /** * Spacing - none. */ - public static function civicthemeVerticalSpacingTypeNone() { + public static function civicthemeVerticalSpacingTypeNone(): string { return 'none'; } /** * Spacing - top. */ - public static function civicthemeVerticalSpacingTypeTop() { + public static function civicthemeVerticalSpacingTypeTop(): string { return 'top'; } /** * Spacing - bottom. */ - public static function civicthemeVerticalSpacingTypeBottom() { + public static function civicthemeVerticalSpacingTypeBottom(): string { return 'bottom'; } /** * Spacing - both. */ - public static function civicthemeVerticalSpacingTypeBoth() { + public static function civicthemeVerticalSpacingTypeBoth(): string { return 'both'; } /** * Types of spaces. + * + * @return array + * Types of spaces. */ - public static function civicthemeVerticalSpacingTypes() { + public static function civicthemeVerticalSpacingTypes(): array { return [ static:: civicthemeVerticalSpacingTypeNone(), static:: civicthemeVerticalSpacingTypeTop(), @@ -134,21 +145,24 @@ public static function civicthemeVerticalSpacingTypes() { /** * Banner type - Default. */ - public static function civicthemeBannerTypeDefault() { + public static function civicthemeBannerTypeDefault(): string { return 'default'; } /** * Banner type - Large. */ - public static function civicthemeBannerTypeLarge() { + public static function civicthemeBannerTypeLarge(): string { return 'large'; } /** * Types of banner. + * + * @return array + * Types of banner. */ - public static function civicthemeBannerTypes() { + public static function civicthemeBannerTypes(): array { return [ static::civicthemeBannerTypeDefault(), static::civicthemeBannerTypeLarge(), @@ -158,49 +172,55 @@ public static function civicthemeBannerTypes() { /** * Image position - left. */ - public static function civicthemeImagePositionLeft() { + public static function civicthemeImagePositionLeft(): string { return 'left'; } /** * Image position - right. */ - public static function civicthemeImagePositionRight() { + public static function civicthemeImagePositionRight(): string { return 'right'; } /** * Image blend-mode. */ - public static function civicthemeImageBlendMode() { + public static function civicthemeImageBlendMode(): string { return 'soft-light'; } /** * Small size name. */ - public static function civicthemeSizeSmall() { + public static function civicthemeSizeSmall(): string { return 'small'; } /** * Large size name. */ - public static function civicthemeSizeLarge() { + public static function civicthemeSizeLarge(): string { return 'large'; } /** * Static Topics. - */ - public static function civicthemeStaticTopics($count = NULL) { + * + * @param int|null $count + * Number of topics to return. + * + * @return array + * Array of topics. + */ + public static function civicthemeStaticTopics(int $count = NULL): array { return static::staticTerms('civictheme_topics', $count); } /** * Static Topic. */ - public static function civicthemeStaticTopic() { + public static function civicthemeStaticTopic(): ?Term { $entities = static::civicthemeStaticTopics(1); return count($entities) > 0 ? reset($entities) : NULL; @@ -208,29 +228,41 @@ public static function civicthemeStaticTopic() { /** * Expose single listing filter type. + * + * @return array + * Filter types. */ - public static function civicThemeExposeSingleFilter() { + public static function civicThemeExposeSingleFilter(): array { return ['topic']; } /** * Expose multiple filter types. + * + * @return array + * Filter types. */ - public static function civicThemeExposeMultipleFilters() { + public static function civicThemeExposeMultipleFilters(): array { return ['topic', 'type', 'title']; } /** * Static Site sections. - */ - public static function civicthemeStaticSiteSections($count = NULL) { + * + * @param int|null $count + * Number of site sections to return. + * + * @return array + * Array of site sections. + */ + public static function civicthemeStaticSiteSections(int $count = NULL): array { return static::staticTerms('civictheme_site_sections', $count); } /** * Static Site section. */ - public static function civicthemeStaticSiteSection() { + public static function civicthemeStaticSiteSection(): ?Term { $entities = static::civicthemeStaticSiteSections(1); return count($entities) > 0 ? reset($entities) : NULL; @@ -239,8 +271,8 @@ public static function civicthemeStaticSiteSection() { /** * Generic component attach helper. */ - public static function civicthemeComponentAttach($node, $field_name, $type, $options) { - $method = 'civicthemeParagraph' . str_replace(' ', '', (ucwords(str_replace('_', ' ', $type)))) . 'Attach'; + public static function civicthemeComponentAttach(NodeInterface $node, string $field_name, string $component_type, array $component_options): void { + $method = 'civicthemeParagraph' . str_replace(' ', '', (ucwords(str_replace('_', ' ', $component_type)))) . 'Attach'; if (!method_exists(self::class, $method)) { throw new \RuntimeException(sprintf('Method "%s" is not defined in "%s" class.', $method, self::class)); @@ -253,34 +285,34 @@ public static function civicthemeComponentAttach($node, $field_name, $type, $opt 'background' => FALSE, ]; - $options += $defaults; + $component_options += $defaults; - if (empty(array_filter($options))) { - return NULL; + if (empty(array_filter($component_options))) { + return; } // Theme. - if (!empty($options['theme'])) { - $options['theme'] = static::civicthemeValueFromOptions(static::civicthemeThemes(), $options['theme']); + if (!empty($component_options['theme'])) { + $component_options['theme'] = static::civicthemeValueFromOptions(static::civicthemeThemes(), $component_options['theme']); } // Space. - if (!empty($options['vertical_spacing'])) { - $options['vertical_spacing'] = static::civicthemeValueFromOptions(static::civicthemeVerticalSpacingTypes(), $options['vertical_spacing']); + if (!empty($component_options['vertical_spacing'])) { + $component_options['vertical_spacing'] = static::civicthemeValueFromOptions(static::civicthemeVerticalSpacingTypes(), $component_options['vertical_spacing']); } // Background. - if (!empty($options['background'])) { - $options['background'] = (bool) $options['background']; + if (!empty($component_options['background'])) { + $component_options['background'] = (bool) $component_options['background']; } - call_user_func([self::class, $method], $node, $field_name, $options); + call_user_func([self::class, $method], $node, $field_name, $component_options); } /** * Attach Content paragraph to a node. */ - public static function civicthemeParagraphContentAttach($node, $field_name, $options) { + public static function civicthemeParagraphContentAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -293,7 +325,7 @@ public static function civicthemeParagraphContentAttach($node, $field_name, $opt $paragraph = self::civicthemeParagraphAttach('civictheme_content', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -303,7 +335,7 @@ public static function civicthemeParagraphContentAttach($node, $field_name, $opt /** * Attach Accordion paragraph to a node. */ - public static function civicthemeParagraphAccordionAttach($node, $field_name, $options) { + public static function civicthemeParagraphAccordionAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -313,37 +345,32 @@ public static function civicthemeParagraphAccordionAttach($node, $field_name, $o 'expand_all' => FALSE, ]; - if (!empty($options['panels']) && count($options['panels']) > 0) { - $panels = $options['panels']; - unset($options['panels']); - } - else { - // Only create if panels were provided. + if (empty($options['panels']) && count($options['panels']) > 0) { return; } + $panels = $options['panels']; + unset($options['panels']); + if (!empty($options['expand_all'])) { $options['expand'] = (bool) $options['expand_all']; } $paragraph = self::civicthemeParagraphAttach('civictheme_accordion', $node, $field_name, $options); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } - // Accordion panels. - if (!empty($panels)) { - foreach ($panels as $panel_options) { - $panel_options['content'] = static::civicthemeNormaliseRichTextContentValue($panel_options['content'] ?? ''); + foreach ($panels as $panel_options) { + $panel_options['content'] = static::civicthemeNormaliseRichTextContentValue($panel_options['content'] ?? ''); - if (!empty($panel_options['expand'])) { - $panel_options['expand'] = (bool) $panel_options['expand']; - } + if (!empty($panel_options['expand'])) { + $panel_options['expand'] = (bool) $panel_options['expand']; + } - $panel = self::civicthemeParagraphAttach('civictheme_accordion_panel', $paragraph, 'field_c_p_panels', $panel_options, TRUE); - if (!empty($panel)) { - $paragraph->field_c_p_panels->appendItem($panel); - } + $panel = self::civicthemeParagraphAttach('civictheme_accordion_panel', $paragraph, 'field_c_p_panels', $panel_options, TRUE); + if ($panel instanceof Paragraph) { + $paragraph->field_c_p_panels->appendItem($panel); } } @@ -354,8 +381,11 @@ public static function civicthemeParagraphAccordionAttach($node, $field_name, $o /** * Attach paragraph to entity. + * + * @SuppressWarnings(PHPMD.BooleanArgumentFlag) + * @SuppressWarnings(PHPMD.StaticAccess) */ - protected static function civicthemeParagraphAttach($type, $entity, $field_name, $options, $save = FALSE) { + protected static function civicthemeParagraphAttach(string $type, FieldableEntityInterface $entity, string $field_name, array $options, bool $save = FALSE): ?Paragraph { if (!$entity->hasField($field_name)) { return NULL; } @@ -381,8 +411,14 @@ protected static function civicthemeParagraphAttach($type, $entity, $field_name, /** * Normalise rich text content field. - */ - protected static function civicthemeNormaliseRichTextContentValue($value) { + * + * @param string|array $value + * Field value. + * + * @return array + * Normalised field value. + */ + protected static function civicthemeNormaliseRichTextContentValue(string|array $value): array { $value = is_array($value) ? $value : ['value' => $value]; $value += [ 'value' => '', @@ -395,14 +431,14 @@ protected static function civicthemeNormaliseRichTextContentValue($value) { /** * Check that value exists in the provided options or return the first option. */ - protected static function civicthemeValueFromOptions(array $options, $value) { + protected static function civicthemeValueFromOptions(array $options, mixed $value): mixed { return in_array($value, $options) ? $value : reset($options); } /** * Attach Attachment paragraph to a node. */ - public static function civicthemeParagraphAttachmentAttach($node, $field_name, $options) { + public static function civicthemeParagraphAttachmentAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -416,7 +452,7 @@ public static function civicthemeParagraphAttachmentAttach($node, $field_name, $ $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_attachment', $node, $field_name, $options); @@ -429,7 +465,7 @@ public static function civicthemeParagraphAttachmentAttach($node, $field_name, $ /** * Attach Callout paragraph to a node. */ - public static function civicthemeParagraphCalloutAttach($node, $field_name, $options) { + public static function civicthemeParagraphCalloutAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -443,7 +479,7 @@ public static function civicthemeParagraphCalloutAttach($node, $field_name, $opt $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_callout', $node, $field_name, $options); @@ -456,7 +492,7 @@ public static function civicthemeParagraphCalloutAttach($node, $field_name, $opt /** * Attach Campaign paragraph to a node. */ - public static function civicthemeParagraphCampaignAttach($node, $field_name, $options) { + public static function civicthemeParagraphCampaignAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -473,12 +509,12 @@ public static function civicthemeParagraphCampaignAttach($node, $field_name, $op $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_campaign', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -488,7 +524,7 @@ public static function civicthemeParagraphCampaignAttach($node, $field_name, $op /** * Attach Iframe paragraph to a node. */ - public static function civicthemeParagraphIframeAttach($node, $field_name, $options) { + public static function civicthemeParagraphIframeAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -500,12 +536,12 @@ public static function civicthemeParagraphIframeAttach($node, $field_name, $opti $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_iframe', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -515,7 +551,7 @@ public static function civicthemeParagraphIframeAttach($node, $field_name, $opti /** * Attach Map paragraph to a node. */ - public static function civicthemeParagraphMapAttach($node, $field_name, $options) { + public static function civicthemeParagraphMapAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -528,12 +564,12 @@ public static function civicthemeParagraphMapAttach($node, $field_name, $options $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_map', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -543,7 +579,7 @@ public static function civicthemeParagraphMapAttach($node, $field_name, $options /** * Attach Next Step paragraph to a node. */ - public static function civicthemeParagraphNextStepAttach($node, $field_name, $options) { + public static function civicthemeParagraphNextStepAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -557,12 +593,12 @@ public static function civicthemeParagraphNextStepAttach($node, $field_name, $op $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_next_step', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -572,7 +608,7 @@ public static function civicthemeParagraphNextStepAttach($node, $field_name, $op /** * Attach Promo paragraph to a node. */ - public static function civicthemeParagraphPromoAttach($node, $field_name, $options) { + public static function civicthemeParagraphPromoAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -585,12 +621,12 @@ public static function civicthemeParagraphPromoAttach($node, $field_name, $optio $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_promo', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -600,7 +636,7 @@ public static function civicthemeParagraphPromoAttach($node, $field_name, $optio /** * Attach Quote paragraph to a node. */ - public static function civicthemeParagraphQuoteAttach($node, $field_name, $options) { + public static function civicthemeParagraphQuoteAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -613,12 +649,12 @@ public static function civicthemeParagraphQuoteAttach($node, $field_name, $optio $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_quote', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -627,8 +663,10 @@ public static function civicthemeParagraphQuoteAttach($node, $field_name, $optio /** * Attach Automated list paragraph to a node. + * + * @SuppressWarnings(PHPMD.ElseExpression) */ - public static function civicthemeParagraphAutomatedListAttach($node, $field_name, $options) { + public static function civicthemeParagraphAutomatedListAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -656,7 +694,7 @@ public static function civicthemeParagraphAutomatedListAttach($node, $field_name $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } if ($options['list_limit_type'] == static::civicthemeAutomatedListLimitTypeLimited()) { @@ -668,7 +706,7 @@ public static function civicthemeParagraphAutomatedListAttach($node, $field_name $paragraph = self::civicthemeParagraphAttach('civictheme_automated_list', $node, $field_name, $options); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -678,7 +716,7 @@ public static function civicthemeParagraphAutomatedListAttach($node, $field_name /** * Attach Webform paragraph to a node. */ - public static function civicthemeParagraphWebformAttach($node, $field_name, $options) { + public static function civicthemeParagraphWebformAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -690,12 +728,12 @@ public static function civicthemeParagraphWebformAttach($node, $field_name, $opt $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_webform', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -704,8 +742,10 @@ public static function civicthemeParagraphWebformAttach($node, $field_name, $opt /** * Attach Slider paragraph to a node. + * + * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ - public static function civicthemeParagraphSliderAttach($node, $field_name, $options) { + public static function civicthemeParagraphSliderAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -717,7 +757,7 @@ public static function civicthemeParagraphSliderAttach($node, $field_name, $opti $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } if (!empty($options['slides']) && count($options['slides']) > 0) { @@ -727,7 +767,7 @@ public static function civicthemeParagraphSliderAttach($node, $field_name, $opti $paragraph = self::civicthemeParagraphAttach('civictheme_slider', $node, $field_name, $options); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -738,7 +778,7 @@ public static function civicthemeParagraphSliderAttach($node, $field_name, $opti $type = $slide_options['type']; unset($slide_options['type']); $slide = self::civicthemeParagraphAttach($type, $paragraph, 'field_c_p_slides', $slide_options, TRUE); - if (!empty($slide)) { + if ($slide instanceof Paragraph) { $paragraph->field_c_p_slides->appendItem($slide); } } @@ -751,8 +791,10 @@ public static function civicthemeParagraphSliderAttach($node, $field_name, $opti /** * Attach Card container paragraph to a node. + * + * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ - public static function civicthemeParagraphManualListAttach($node, $field_name, $options) { + public static function civicthemeParagraphManualListAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -768,7 +810,7 @@ public static function civicthemeParagraphManualListAttach($node, $field_name, $ $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } if (!empty($options['list_items']) && count($options['list_items']) > 0) { @@ -778,7 +820,7 @@ public static function civicthemeParagraphManualListAttach($node, $field_name, $ $paragraph = self::civicthemeParagraphAttach('civictheme_manual_list', $node, $field_name, $options); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } @@ -789,7 +831,7 @@ public static function civicthemeParagraphManualListAttach($node, $field_name, $ $type = $list_item_options['type']; unset($list_item_options['type']); $card = self::civicthemeParagraphAttach($type, $paragraph, 'field_c_p_list_items', $list_item_options, TRUE); - if (!empty($card)) { + if ($card instanceof Paragraph) { $paragraph->field_c_p_list_items->appendItem($card); } } @@ -803,7 +845,7 @@ public static function civicthemeParagraphManualListAttach($node, $field_name, $ /** * Attach Search paragraph to a node. */ - public static function civicthemeParagraphSearchAttach($node, $field_name, $options) { + public static function civicthemeParagraphSearchAttach(NodeInterface $node, string $field_name, array $options): void { if (!$node->hasField($field_name)) { return; } @@ -818,12 +860,12 @@ public static function civicthemeParagraphSearchAttach($node, $field_name, $opti $options += $defaults; if (empty(array_filter($options))) { - return NULL; + return; } $paragraph = self::civicthemeParagraphAttach('civictheme_search', $node, $field_name, $options, TRUE); - if (empty($paragraph)) { + if (!$paragraph instanceof Paragraph) { return; } diff --git a/web/modules/custom/cs_generated_content/src/CsGeneratedContentHelper.php b/web/modules/custom/cs_generated_content/src/CsGeneratedContentHelper.php index 7012900c0..82fca5c86 100644 --- a/web/modules/custom/cs_generated_content/src/CsGeneratedContentHelper.php +++ b/web/modules/custom/cs_generated_content/src/CsGeneratedContentHelper.php @@ -2,6 +2,7 @@ namespace Drupal\cs_generated_content; +use Drupal\Core\Entity\EntityInterface; use Drupal\generated_content\Helpers\GeneratedContentHelper; /** @@ -18,10 +19,10 @@ class CsGeneratedContentHelper extends GeneratedContentHelper { /** * Select a random real webform. * - * @return \Drupal\webform\Entity\Webform|null + * @return \Drupal\Core\Entity\EntityInterface|null * Webform entity object or NULL if no entities were found. */ - public static function randomRealWebform() { + public static function randomRealWebform(): ?EntityInterface { $entities = static::randomRealEntities('webform', NULL, 1); return count($entities) > 0 ? reset($entities) : NULL; @@ -30,13 +31,13 @@ public static function randomRealWebform() { /** * Generate a pre-defined static external URL. * - * @param string|bool $domain + * @param string $domain * (optional) Domain name. Defaults to 'www.example.com'. * * @return string * URL with a path. */ - public static function staticUrl($domain = FALSE) { + public static function staticUrl(string $domain = NULL): string { $parts = []; $parts[] = 'https://'; $parts[] = $domain ? rtrim($domain, '/') : 'www.example.com'; @@ -54,11 +55,11 @@ public static function staticUrl($domain = FALSE) { * @param string $format * Text format. Defaults to 'civictheme_rich_text'. * - * @return array + * @return array * Array of static content string as an element with 'value' key and format * as en element with 'format' key. */ - public static function staticSentenceFieldValue($count = 5, $format = 'civictheme_rich_text') { + public static function staticSentenceFieldValue(int $count = 5, string $format = 'civictheme_rich_text'): array { return [ 'value' => static::staticSentence($count), 'format' => $format, @@ -73,11 +74,11 @@ public static function staticSentenceFieldValue($count = 5, $format = 'civicthem * @param string $format * Text format. Defaults to 'civictheme_rich_text'. * - * @return array + * @return array * Array of static content string as an element with 'value' key and format * as en element with 'format' key. */ - public static function staticRichTextFieldValue($count = 5, $format = 'civictheme_rich_text') { + public static function staticRichTextFieldValue(int $count = 5, string $format = 'civictheme_rich_text'): array { return [ 'value' => static::staticRichText($count), 'format' => $format, @@ -90,10 +91,10 @@ public static function staticRichTextFieldValue($count = 5, $format = 'civicthem * @param int $count * Number of words. * - * @return array + * @return array * Array of static link URI and content string. */ - public static function staticLinkFieldValue($count = 2) { + public static function staticLinkFieldValue(int $count = 2): array { return [ 'uri' => static::staticUrl(), 'title' => static::staticSentence($count), @@ -103,7 +104,7 @@ public static function staticLinkFieldValue($count = 2) { /** * {@inheritdoc} */ - public static function staticRichText($paragraphs = 4, $prefix = '') { + public static function staticRichText($paragraphs = 4, $prefix = ''): string { $content = parent::staticRichText($paragraphs, $prefix); $content .= '' . self::staticSentence(2) . ''; @@ -113,7 +114,7 @@ public static function staticRichText($paragraphs = 4, $prefix = '') { /** * Convert date string to formatted date in UTC timezone. */ - public static function dateToUtc($date, $format = 'Y-m-d\TH:i:s') { + public static function dateToUtc(string $date, string $format = 'Y-m-d\TH:i:s'): string { $datetime = new \DateTime($date); $datetime->setTimezone(new \DateTimeZone('UTC')); diff --git a/web/modules/custom/cs_generated_content/src/CsGeneratedContentServiceProvider.php b/web/modules/custom/cs_generated_content/src/CsGeneratedContentServiceProvider.php index 93a986745..2a7aedcae 100644 --- a/web/modules/custom/cs_generated_content/src/CsGeneratedContentServiceProvider.php +++ b/web/modules/custom/cs_generated_content/src/CsGeneratedContentServiceProvider.php @@ -17,7 +17,7 @@ class CsGeneratedContentServiceProvider extends ServiceProviderBase { /** * {@inheritdoc} */ - public function alter(ContainerBuilder $container) { + public function alter(ContainerBuilder $container): void { $definition = $container->getDefinition('generated_content.asset_generator'); $definition->setClass('Drupal\cs_generated_content\CsGeneratedContentAssetGenerator'); } diff --git a/web/sites/default/default.settings.php b/web/sites/default/default.settings.php index c0b18427a..00f8a26ca 100644 --- a/web/sites/default/default.settings.php +++ b/web/sites/default/default.settings.php @@ -812,11 +812,11 @@ * site. * - migrate_file_public_path - The location of the source Drupal 6 or Drupal 7 * public files. This can be a local file directory containing the source - * Drupal 6 or Drupal 7 site (e.g /var/www/docroot), or the site address + * Drupal 6 or Drupal 7 site (e.g /var/www/web), or the site address * (e.g http://example.com). * - migrate_file_private_path - The location of the source Drupal 7 private * files. This can be a local file directory containing the source Drupal 7 - * site (e.g /var/www/docroot), or empty to use the same value as Public + * site (e.g /var/www/web), or empty to use the same value as Public * files directory. * * Sample configuration for a drupal 6 source site with the source files in a diff --git a/web/themes/contrib/civictheme/civictheme.api.php b/web/themes/contrib/civictheme/civictheme.api.php index 38dae9a53..639501798 100644 --- a/web/themes/contrib/civictheme/civictheme.api.php +++ b/web/themes/contrib/civictheme/civictheme.api.php @@ -31,7 +31,7 @@ * - site_sections: (array) Array of Site section entities. * - cache_tags: (array) Array of the cache tags. */ -function hook_civictheme_automated_list_view_info_alter(array &$info, array &$settings) { +function hook_civictheme_automated_list_view_info_alter(array &$info, array &$settings): void { // Change the view name and block based on the conditions set in the // Automated list settings. if ($settings['content_type'] == 'event') { @@ -51,7 +51,7 @@ function hook_civictheme_automated_list_view_info_alter(array &$info, array &$se * @param array $variables * Array of preprocess variables of the Automated list view. */ -function hook_civictheme_automated_list_preprocess_view_alter(array &$variables, ViewExecutable &$view) { +function hook_civictheme_automated_list_preprocess_view_alter(array &$variables, ViewExecutable &$view): void { if ($view->id() == 'civictheme_view_examples') { $variables['theme'] = CivicthemeConstants::THEME_DARK; $variables['with_background'] = TRUE; diff --git a/web/themes/contrib/civictheme/civictheme.info.yml b/web/themes/contrib/civictheme/civictheme.info.yml index 358f0fd5a..54e997f16 100644 --- a/web/themes/contrib/civictheme/civictheme.info.yml +++ b/web/themes/contrib/civictheme/civictheme.info.yml @@ -1,8 +1,8 @@ name: CivicTheme type: theme base theme: false -description: CivicTheme is a Drupal 9 component-based theme. -core_version_requirement: ^9 || ^10 +description: CivicTheme is a Drupal 10 component-based theme. +core_version_requirement: ^10 libraries: - 'civictheme/global' diff --git a/web/themes/contrib/civictheme/civictheme.post_update.php b/web/themes/contrib/civictheme/civictheme.post_update.php index b6961f9e0..1d78d73ce 100644 --- a/web/themes/contrib/civictheme/civictheme.post_update.php +++ b/web/themes/contrib/civictheme/civictheme.post_update.php @@ -8,6 +8,7 @@ use Drupal\civictheme\CivicthemeConstants; use Drupal\civictheme\CivicthemeUpdateHelper; use Drupal\Core\Entity\EntityInterface; +use Drupal\Core\Entity\FieldableEntityInterface; use Drupal\Core\StringTranslation\TranslatableMarkup; use Drupal\node\Entity\Node; @@ -15,18 +16,20 @@ /** * Updates vertical spacing on nodes and components where it has not been set. + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ -function civictheme_post_update_set_vertical_spacing_empty_value(array &$sandbox) { +function civictheme_post_update_set_vertical_spacing_empty_value(array &$sandbox): ?string { return \Drupal::classResolver(CivicthemeUpdateHelper::class)->update( $sandbox, 'node', ['civictheme_page'], // Start callback. - function (CivicthemeUpdateHelper $helper) { + function (CivicthemeUpdateHelper $helper): void { // Noop. }, // Process callback. - function (CivicthemeUpdateHelper $helper, EntityInterface $entity) { + function (CivicthemeUpdateHelper $helper, EntityInterface $entity): bool { if (!$entity instanceof Node) { return FALSE; } @@ -35,6 +38,7 @@ function (CivicthemeUpdateHelper $helper, EntityInterface $entity) { // Update vertical spacing for node. if (is_null(civictheme_get_field_value($entity, 'field_c_n_vertical_spacing', TRUE))) { + // @phpstan-ignore-next-line $entity->field_c_n_vertical_spacing = CivicthemeConstants::VERTICAL_SPACING_NONE; $updated = TRUE; } @@ -68,7 +72,7 @@ function (CivicthemeUpdateHelper $helper, EntityInterface $entity) { return $updated; }, // Finished callback. - function (CivicthemeUpdateHelper $helper) { + function (CivicthemeUpdateHelper $helper): TranslatableMarkup { return new TranslatableMarkup("Updated values for fields 'field_c_n_vertical_spacing' and 'field_c_p_vertical_spacing'.\n"); }, ); @@ -76,8 +80,10 @@ function (CivicthemeUpdateHelper $helper) { /** * Renames 'Column count' and 'Fill width' List fields and updates content. + * + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ -function civictheme_post_update_rename_list_fields(array &$sandbox) { +function civictheme_post_update_rename_list_fields(array &$sandbox): ?string { $field_mapping = [ 'field_c_p_fill_width' => 'field_c_p_list_fill_width', 'field_c_p_column_count' => 'field_c_p_list_column_count', @@ -160,16 +166,16 @@ function civictheme_post_update_rename_list_fields(array &$sandbox) { 'paragraph', array_keys($new_form_display_config), // Start callback. - function (CivicthemeUpdateHelper $helper) use ($new_field_configs) { + function (CivicthemeUpdateHelper $helper) use ($new_field_configs): void { $config_path = \Drupal::service('extension.list.theme')->getPath('civictheme') . '/config/install'; $helper->createConfigs($new_field_configs, $config_path); }, // Process callback. - function (CivicthemeUpdateHelper $helper, EntityInterface $entity) use ($field_mapping) { + function (CivicthemeUpdateHelper $helper, FieldableEntityInterface $entity) use ($field_mapping): bool { return $helper->copyFieldContent($entity, $field_mapping); }, // Finished callback. - function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config, $new_form_display_group_config) { + function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config, $new_form_display_group_config): TranslatableMarkup { $helper->deleteConfig($old_field_configs); foreach ($new_form_display_config as $bundle => $config) { @@ -186,7 +192,7 @@ function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_dis /** * Replaces 'Summary' with 'Content' field in components and updates content. */ -function civictheme_post_update_replace_summary_field(array &$sandbox) { +function civictheme_post_update_replace_summary_field(array &$sandbox): ?string { $field_mapping = [ 'field_c_p_summary' => 'field_c_p_content', ]; @@ -237,16 +243,16 @@ function civictheme_post_update_replace_summary_field(array &$sandbox) { 'paragraph', array_keys($new_form_display_config), // Start callback. - function (CivicthemeUpdateHelper $helper) use ($new_field_configs) { + function (CivicthemeUpdateHelper $helper) use ($new_field_configs): void { $config_path = \Drupal::service('extension.list.theme')->getPath('civictheme') . '/config/install'; $helper->createConfigs($new_field_configs, $config_path); }, // Process callback. - function (CivicthemeUpdateHelper $helper, EntityInterface $entity) use ($field_mapping) { + function (CivicthemeUpdateHelper $helper, FieldableEntityInterface $entity) use ($field_mapping): bool { return $helper->copyFieldContent($entity, $field_mapping); }, // Finished callback. - function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config) { + function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config): TranslatableMarkup { $helper->deleteConfig($old_field_configs); foreach ($new_form_display_config as $bundle => $config) { @@ -263,7 +269,7 @@ function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_dis /** * Renames 'Date' field in Event content type and updates content. */ -function civictheme_post_update_rename_event_date_field(array &$sandbox) { +function civictheme_post_update_rename_event_date_field(array &$sandbox): ?string { $field_mapping = [ 'field_c_n_date' => 'field_c_n_date_range', ]; @@ -303,16 +309,16 @@ function civictheme_post_update_rename_event_date_field(array &$sandbox) { 'node', ['civictheme_event'], // Start callback. - function (CivicthemeUpdateHelper $helper) use ($new_field_configs) { + function (CivicthemeUpdateHelper $helper) use ($new_field_configs): void { $config_path = \Drupal::service('extension.list.theme')->getPath('civictheme') . '/config/install'; $helper->createConfigs($new_field_configs, $config_path); }, // Process callback. - function (CivicthemeUpdateHelper $helper, EntityInterface $entity) use ($field_mapping) { + function (CivicthemeUpdateHelper $helper, FieldableEntityInterface $entity) use ($field_mapping): bool { return $helper->copyFieldContent($entity, $field_mapping); }, // Finished callback. - function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config, $new_form_display_group_config) { + function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config, $new_form_display_group_config): TranslatableMarkup { $helper->deleteConfig($old_field_configs); foreach ($new_form_display_config as $bundle => $config) { @@ -327,7 +333,7 @@ function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_dis /** * Renames 'Banner blend mode' field in nodes and updates content. */ -function civictheme_post_update_rename_node_banner_blend_mode(array &$sandbox) { +function civictheme_post_update_rename_node_banner_blend_mode(array &$sandbox): ?string { $field_mapping = [ 'field_c_n_blend_mode' => 'field_c_n_banner_blend_mode', 'field_c_b_blend_mode' => 'field_c_b_banner_blend_mode', @@ -369,16 +375,16 @@ function civictheme_post_update_rename_node_banner_blend_mode(array &$sandbox) { 'node', ['civictheme_page'], // Start callback. - function (CivicthemeUpdateHelper $helper) use ($new_field_configs) { + function (CivicthemeUpdateHelper $helper) use ($new_field_configs): void { $config_path = \Drupal::service('extension.list.theme')->getPath('civictheme') . '/config/install'; $helper->createConfigs($new_field_configs, $config_path); }, // Process callback. - function (CivicthemeUpdateHelper $helper, EntityInterface $entity) use ($field_mapping) { + function (CivicthemeUpdateHelper $helper, FieldableEntityInterface $entity) use ($field_mapping): bool { return $helper->copyFieldContent($entity, $field_mapping); }, // Finished callback. - function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config, $new_form_display_group_config) { + function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config, $new_form_display_group_config): TranslatableMarkup { $helper->deleteConfig($old_field_configs); foreach ($new_form_display_config as $bundle => $config) { @@ -393,7 +399,7 @@ function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_dis /** * Renames 'Banner blend mode' field in blocks and updates content. */ -function civictheme_post_update_rename_block_banner_blend_mode(array &$sandbox) { +function civictheme_post_update_rename_block_banner_blend_mode(array &$sandbox): ?string { $field_mapping = [ 'field_c_b_blend_mode' => 'field_c_b_banner_blend_mode', ]; @@ -425,16 +431,16 @@ function civictheme_post_update_rename_block_banner_blend_mode(array &$sandbox) 'block_content', ['civictheme_banner'], // Start callback. - function (CivicthemeUpdateHelper $helper) use ($new_field_configs) { + function (CivicthemeUpdateHelper $helper) use ($new_field_configs): void { $config_path = \Drupal::service('extension.list.theme')->getPath('civictheme') . '/config/install'; $helper->createConfigs($new_field_configs, $config_path); }, // Process callback. - function (CivicthemeUpdateHelper $helper, EntityInterface $entity) use ($field_mapping) { + function (CivicthemeUpdateHelper $helper, FieldableEntityInterface $entity) use ($field_mapping): bool { return $helper->copyFieldContent($entity, $field_mapping); }, // Finished callback. - function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config) { + function (CivicthemeUpdateHelper $helper) use ($old_field_configs, $new_form_display_config): TranslatableMarkup { $helper->deleteConfig($old_field_configs); foreach ($new_form_display_config as $bundle => $config) { diff --git a/web/themes/contrib/civictheme/civictheme.theme b/web/themes/contrib/civictheme/civictheme.theme index d8e9324d5..6b8448d78 100644 --- a/web/themes/contrib/civictheme/civictheme.theme +++ b/web/themes/contrib/civictheme/civictheme.theme @@ -54,8 +54,10 @@ require_once 'includes/webform.inc'; /** * Implements hook_theme(). + * + * @phpstan-ignore-next-line */ -function civictheme_theme() { +function civictheme_theme(): array { // Components from the library are used directly by including them within // existing templates. // @@ -88,7 +90,7 @@ function civictheme_theme() { /** * Implements hook_theme_suggestions_HOOK_alter(). */ -function civictheme_theme_suggestions_block_alter(array &$suggestions, array $variables) { +function civictheme_theme_suggestions_block_alter(array &$suggestions, array $variables): void { // Add theme suggestions to all blocks whose bundle starts with 'civictheme_'. if (!empty($variables['elements']['#base_plugin_id']) && $variables['elements']['#base_plugin_id'] == 'block_content') { $entity = $variables['elements']['content']['#block_content'] ?? NULL; @@ -101,7 +103,7 @@ function civictheme_theme_suggestions_block_alter(array &$suggestions, array $va /** * Implements hook_theme_registry_alter(). */ -function civictheme_theme_registry_alter(&$theme_registry) { +function civictheme_theme_registry_alter(array &$theme_registry): void { // Define a new preprocess hook that will always run last. $hook = 'civictheme_preprocess_last'; @@ -123,7 +125,7 @@ function civictheme_theme_registry_alter(&$theme_registry) { /** * Implements hook_preprocess_last(). */ -function civictheme_preprocess_last(&$variables, $hook) { +function civictheme_preprocess_last(array &$variables, string $hook): void { // Process attributes for all components before they are sent to templates. civictheme_convert_attributes_to_modifier_class($variables); } @@ -131,7 +133,7 @@ function civictheme_preprocess_last(&$variables, $hook) { /** * Implements hook_preprocess_HOOK(). */ -function civictheme_preprocess_html(&$variables) { +function civictheme_preprocess_html(array &$variables): void { _civictheme_preprocess_html__skip_link($variables); _civictheme_preprocess_html__site_section($variables); @@ -142,7 +144,7 @@ function civictheme_preprocess_html(&$variables) { /** * Implements hook_preprocess_HOOK(). */ -function civictheme_preprocess_page(&$variables) { +function civictheme_preprocess_page(array &$variables): void { // All pages. _civictheme_preprocess_page($variables); @@ -158,7 +160,7 @@ function civictheme_preprocess_page(&$variables) { // // IMPORTANT! Do not add anything below this line or components will not be // able to discover variables. - $page_variables = array_filter($variables['page'], function ($key) { + $page_variables = array_filter($variables['page'], function ($key): bool { return strpos($key, '#') !== 0; }, ARRAY_FILTER_USE_KEY); $variables += $page_variables; @@ -167,7 +169,7 @@ function civictheme_preprocess_page(&$variables) { /** * Implements hook_preprocess_HOOK(). */ -function civictheme_preprocess_node(&$variables) { +function civictheme_preprocess_node(array &$variables): void { // All nodes. _civictheme_preprocess_node($variables); @@ -184,7 +186,7 @@ function civictheme_preprocess_node(&$variables) { /** * Implements hook_preprocess_HOOK(). */ -function civictheme_preprocess_block(&$variables) { +function civictheme_preprocess_block(array &$variables): void { _civictheme_preprocess_block__system_main_block($variables); _civictheme_preprocess_block__civictheme_banner($variables); _civictheme_preprocess_block__navigation($variables); @@ -197,28 +199,28 @@ function civictheme_preprocess_block(&$variables) { /** * Implements template_preprocess_image(). */ -function civictheme_preprocess_image(&$variables) { +function civictheme_preprocess_image(array &$variables): void { _civictheme_preprocess_image($variables); } /** * Implement template_preprocess_menu_local_tasks(). */ -function civictheme_preprocess_menu_local_tasks(&$variables) { +function civictheme_preprocess_menu_local_tasks(array &$variables): void { _civictheme_preprocess_menu_local_tasks($variables); } /** * Implements template_preprocess_menu(). */ -function civictheme_preprocess_menu(&$variables) { +function civictheme_preprocess_menu(array &$variables): void { _civictheme_preprocess_menu_items($variables['items']); } /** * Implements template_preprocess_field(). */ -function civictheme_preprocess_field(&$variables) { +function civictheme_preprocess_field(array &$variables): void { _civictheme_preprocess_wysiwyg_field($variables); _civictheme_preprocess_date_range_field($variables); } @@ -226,6 +228,6 @@ function civictheme_preprocess_field(&$variables) { /** * Implements hook_library_info_alter(). */ -function civictheme_library_info_alter(&$libraries, $extension) { +function civictheme_library_info_alter(array &$libraries, string $extension): void { _civictheme_library_info_alter__color_selector($libraries, $extension); } diff --git a/web/themes/contrib/civictheme/civictheme_create_subtheme.php b/web/themes/contrib/civictheme/civictheme_create_subtheme.php index b688fea0c..679289961 100755 --- a/web/themes/contrib/civictheme/civictheme_create_subtheme.php +++ b/web/themes/contrib/civictheme/civictheme_create_subtheme.php @@ -36,18 +36,18 @@ /** * Main functionality. */ -function main(array $argv, $argc) { +function main(array $argv, int $argc): int { $default_new_theme_directory = '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'custom'; if (in_array($argv[1] ?? NULL, ['--help', '-help', '-h', '-?'])) { - print_help($default_new_theme_directory); + print_command_help($default_new_theme_directory); return EXIT_SUCCESS; } // Show help if not enough or more than required arguments. if ($argc < 4 || $argc > 6) { - print_help($default_new_theme_directory); + print_command_help($default_new_theme_directory); return EXIT_ERROR; } @@ -98,9 +98,12 @@ function main(array $argv, $argc) { /** * Print help. * + * @param string $default_new_theme_dir + * Default new theme directory. + * * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ -function print_help($default_new_theme_dir) { +function print_command_help($default_new_theme_dir): void { $script_name = basename(__FILE__); print << + * Decoded composer.json. + * * @SuppressWarnings(PHPMD.MissingImport) */ -function find_composerjson($dir) { +function find_composerjson(string $dir): array { $filepath = $dir . DIRECTORY_SEPARATOR . 'composer.json'; if (!file_exists($filepath)) { throw new \Exception('Unable to find CivicTheme composer.json location.'); } - return json_decode(file_get_contents($filepath), TRUE); + return json_decode((string) file_get_contents($filepath), TRUE); } /** * Find package.json. * + * @param string $dir + * Directory to search in. + * + * @return array + * Decoded package.json. + * * @SuppressWarnings(PHPMD.MissingImport) */ -function find_packagejson($dir) { +function find_packagejson(string $dir): array { $filepath = $dir . DIRECTORY_SEPARATOR . 'package.json'; if (!file_exists($filepath)) { throw new \Exception('Unable to find CivicTheme package.json location.'); } - return json_decode(file_get_contents($filepath), TRUE); + return json_decode((string) file_get_contents($filepath), TRUE); } // ////////////////////////////////////////////////////////////////////////// // @@ -331,9 +346,13 @@ function find_packagejson($dir) { * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ -function file_copy_recursively($src, $dst, array $exclude = [], $permissions = 0755, $copy_empty_dirs = FALSE) { +function file_copy_recursively(string $src, string $dst, array $exclude = [], $permissions = 0755, $copy_empty_dirs = FALSE): bool { $parent = dirname($dst); + if (empty($parent)) { + throw new \Exception(sprintf('Unable to get parent directory of "%s".', $dst)); + } + if (!is_dir($parent)) { mkdir($parent, $permissions, TRUE); } @@ -343,11 +362,21 @@ function file_copy_recursively($src, $dst, array $exclude = [], $permissions = 0 // Changing dir symlink will be relevant to the current destination's file // directory. $cur_dir = getcwd(); + + if (!$cur_dir) { + throw new \Exception(sprintf('Unable to get current working directory.')); + } + chdir($parent); + $ret = TRUE; if (!is_readable(basename($dst))) { + if (empty(readlink($src))) { + throw new \Exception(sprintf('Symlink target "%s" does not exist.', $src)); + } $ret = symlink(readlink($src), basename($dst)); } + chdir($cur_dir); return $ret; @@ -356,7 +385,11 @@ function file_copy_recursively($src, $dst, array $exclude = [], $permissions = 0 if (is_file($src)) { $ret = copy($src, $dst); if ($ret) { - chmod($dst, fileperms($src)); + $perms = fileperms($src); + if ($perms === FALSE) { + throw new \Exception(sprintf('Unable to get permissions of "%s".', $src)); + } + chmod($dst, $perms); } return $ret; @@ -367,14 +400,16 @@ function file_copy_recursively($src, $dst, array $exclude = [], $permissions = 0 } $dir = dir($src); - while (FALSE !== $entry = $dir->read()) { + while ($dir && FALSE !== $entry = $dir->read()) { if ($entry == '.' || $entry == '..' || in_array($entry, $exclude)) { continue; } file_copy_recursively($src . DIRECTORY_SEPARATOR . $entry, $dst . DIRECTORY_SEPARATOR . $entry, $exclude, $permissions, $copy_empty_dirs); } - $dir->close(); + if ($dir) { + $dir->close(); + } return TRUE; } @@ -382,16 +417,16 @@ function file_copy_recursively($src, $dst, array $exclude = [], $permissions = 0 /** * Replace file content. */ -function file_replace_file_content($needle, $replacement, $filename) { +function file_replace_file_content(string $needle, string $replacement, string $filename): void { if (!is_readable($filename) || file_is_excluded_from_processing($filename)) { - return FALSE; + return; } $content = file_get_contents($filename); $replaced = is_regex($needle) - ? preg_replace($needle, $replacement, $content) - : str_replace($needle, $replacement, $content); + ? preg_replace($needle, $replacement, (string) $content) + : str_replace($needle, $replacement, (string) $content); if ($replaced != $content) { file_put_contents($filename, $replaced); @@ -401,7 +436,7 @@ function file_replace_file_content($needle, $replacement, $filename) { /** * Replace directory content. */ -function file_replace_dir_content($needle, $replacement, $dir) { +function file_replace_dir_content(string $needle, string $replacement, string $dir): void { $files = file_scandir_recursive($dir, file_ignore_paths()); foreach ($files as $filename) { file_replace_file_content($needle, $replacement, $filename); @@ -411,7 +446,7 @@ function file_replace_dir_content($needle, $replacement, $dir) { /** * Replace a string in the file name. */ -function file_replace_string_filename($search, $replace, $dir) { +function file_replace_string_filename(string $search, string $replace, string $dir): void { $files = file_scandir_recursive($dir, file_ignore_paths()); foreach ($files as $filename) { $new_filename = str_replace($search, $replace, $filename); @@ -428,7 +463,7 @@ function file_replace_string_filename($search, $replace, $dir) { /** * Remove directory. */ -function file_remove_dir($dir) { +function file_remove_dir(string $dir): void { if (is_dir($dir)) { $files = file_scandir_recursive($dir, [], TRUE); foreach ($files as $file) { @@ -449,13 +484,23 @@ function file_remove_dir($dir) { /** * Recursively scan directory for files. * + * @param string $dir + * Directory to scan. + * @param array $ignore_paths + * Optional array of paths to ignore. + * @param bool $include_dirs + * Optional flag to include directories in the result. + * + * @return array + * Array of discovered files. + * * @SuppressWarnings(PHPMD.BooleanArgumentFlag) */ -function file_scandir_recursive($dir, $ignore_paths = [], $include_dirs = FALSE) { +function file_scandir_recursive(string $dir, array $ignore_paths = [], bool $include_dirs = FALSE): array { $discovered = []; if (is_dir($dir)) { - $paths = array_diff(scandir($dir), ['.', '..']); + $paths = array_diff(scandir($dir) ?: [], ['.', '..']); foreach ($paths as $path) { $path = $dir . '/' . $path; @@ -484,8 +529,11 @@ function file_scandir_recursive($dir, $ignore_paths = [], $include_dirs = FALSE) /** * Ignore path. + * + * @return array + * Array of paths to ignore. */ -function file_ignore_paths() { +function file_ignore_paths(): array { return array_merge([ '.git', '.idea', @@ -501,15 +549,21 @@ function file_ignore_paths() { /** * Internal paths to ignore. + * + * @return array + * Array of internal paths. */ -function file_internal_paths() { +function file_internal_paths(): array { return []; } /** * Example component paths. + * + * @return array + * Array of example component paths. */ -function example_component_paths() { +function example_component_paths(): array { return [ 'components/01-atoms/demo-button', 'components/02-molecules/navigation-card', @@ -518,9 +572,9 @@ function example_component_paths() { } /** - * Check if the file ia excluded from the processing. + * Check if the file is excluded from the processing. */ -function file_is_excluded_from_processing($filename) { +function file_is_excluded_from_processing(string $filename): bool { $excluded_patterns = [ '.+\.png', '.+\.jpg', @@ -529,7 +583,7 @@ function file_is_excluded_from_processing($filename) { '.+\.tiff', ]; - return preg_match('/^(' . implode('|', $excluded_patterns) . ')$/', $filename); + return (bool) preg_match('/^(' . implode('|', $excluded_patterns) . ')$/', $filename); } /** @@ -537,7 +591,7 @@ function file_is_excluded_from_processing($filename) { * * @SuppressWarnings(PHPMD.MissingImport) */ -function file_tempdir($dir = NULL, $prefix = 'tmp_', $mode = 0700, $max_attempts = 1000) { +function file_tempdir(string $dir = NULL, string $prefix = 'tmp_', int $mode = 0700, int $max_attempts = 1000): string { if (is_null($dir)) { $dir = sys_get_temp_dir(); } @@ -545,11 +599,11 @@ function file_tempdir($dir = NULL, $prefix = 'tmp_', $mode = 0700, $max_attempts $dir = rtrim($dir, DIRECTORY_SEPARATOR); if (!is_dir($dir) || !is_writable($dir)) { - return FALSE; + throw new \RuntimeException(sprintf('Unable to find writable temporary directory "%s".', $dir)); } if (strpbrk($prefix, '\\/:*?"<>|') !== FALSE) { - return FALSE; + throw new \RuntimeException(sprintf('The prefix "%s" contains invalid characters.', $prefix)); } $attempts = 0; @@ -577,7 +631,7 @@ function file_tempdir($dir = NULL, $prefix = 'tmp_', $mode = 0700, $max_attempts * @return string * Relative path between 2 directories. */ -function file_get_relative_dir($dir1, $dir2) { +function file_get_relative_dir(string $dir1, string $dir2): string { $dir1 = rtrim($dir1, '/') . '/'; $dir2 = rtrim($dir2, '/') . '/'; @@ -622,7 +676,7 @@ function file_get_relative_dir($dir1, $dir2) { * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.IfStatementAssignment) */ -function file_path_canonicalize($path) { +function file_path_canonicalize(string $path): string { $output = ''; while ($path !== '') { @@ -647,7 +701,7 @@ function file_path_canonicalize($path) { ($prefix = $path) == '/..' ) { $path = '/' . substr($path, strlen($prefix)); - $output = substr($output, 0, strrpos($output, '/')); + $output = substr($output, 0, (int) strrpos($output, '/')); continue; } @@ -679,7 +733,7 @@ function file_path_canonicalize($path) { /** * Check if the provided string is a regular expression. */ -function is_regex($str) { +function is_regex(string $str): bool { if (preg_match('/^(.{3,}?)[imsxuADU]*$/', $str, $m)) { $start = substr($m[1], 0, 1); $end = substr($m[1], -1); @@ -701,7 +755,7 @@ function is_regex($str) { /** * Show a verbose message. */ -function verbose() { +function verbose(): void { if (getenv('SCRIPT_QUIET') != '1') { print call_user_func_array('sprintf', func_get_args()) . PHP_EOL; } @@ -720,7 +774,8 @@ function verbose() { // Allow to skip the script run. if (getenv('SCRIPT_RUN_SKIP') != 1) { // Custom error handler to catch errors based on set ERROR_LEVEL. - set_error_handler(function ($severity, $message, $file, $line) { + // @phpstan-ignore-next-line + set_error_handler(function ($severity, $message, $file, $line): void { if (!(error_reporting() & $severity)) { // This error code is not included in error_reporting. return; @@ -730,9 +785,6 @@ function verbose() { try { $code = main($argv, $argc); - if (is_null($code)) { - throw new \Exception('Script exited without providing an exit code.'); - } exit($code); } catch (\ErrorException $exception) { diff --git a/web/themes/contrib/civictheme/civictheme_library/scripts/extract_css_colors_to_csv.php b/web/themes/contrib/civictheme/civictheme_library/scripts/extract_css_colors_to_csv.php index 626cfc5e7..ec1a925e5 100644 --- a/web/themes/contrib/civictheme/civictheme_library/scripts/extract_css_colors_to_csv.php +++ b/web/themes/contrib/civictheme/civictheme_library/scripts/extract_css_colors_to_csv.php @@ -35,7 +35,7 @@ * * @SuppressWarnings(PHPMD.MissingImport) */ -function main(array $argv, $argc) { +function main(array $argv, int $argc):int { if (in_array($argv[1] ?? NULL, ['--help', '-help', '-h', '-?'])) { print_help(); @@ -72,7 +72,7 @@ function main(array $argv, $argc) { * * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ -function print_help() { +function print_help(): void { $script_name = basename(__FILE__); print << * Array of collected variables as name=>value. */ -function collect_variables($content) { +function collect_variables(string $content): array { $vars = []; $matches = []; preg_match_all('/(--[a-zA-Z0-9-]+)\s*:\s*([^;]+);/i', $content, $matches, PREG_SET_ORDER); - array_walk($matches, function ($value) use (&$vars) { + array_walk($matches, function (array $value) use (&$vars): void { if (!empty($value[1])) { - $vars[trim($value[1])] = trim($value[2]) ?? NULL; + $vars[trim($value[1])] = trim($value[2] ?? ''); } }); @@ -117,9 +117,12 @@ function collect_variables($content) { /** * Filter variables based on a custom criteria. + * + * @return array + * Array of filtered variables as name=>value. */ -function filter_variables($vars) { - $vars = array_filter($vars, function ($k) { +function filter_variables(array $vars): array { + $vars = array_filter($vars, function ($k): bool { return strpos($k, '--ct') === 0; }, ARRAY_FILTER_USE_KEY); @@ -132,10 +135,10 @@ function filter_variables($vars) { * @param array $vars * Array of variables with names as keys and values as values. * - * @return array + * @return array> * Array of parsed variables. */ -function parse_variables(array $vars) { +function parse_variables(array $vars): array { $variables = []; foreach ($vars as $name => $value) { @@ -170,7 +173,7 @@ function parse_variables(array $vars) { * * @SuppressWarnings(PHPMD.MissingImport) */ -function output_csv(array $vars, $stream = 'php://output') { +function output_csv(array $vars, $stream = 'php://output'): void { if (empty($vars)) { throw new \Exception('No variables found'); } @@ -180,6 +183,10 @@ function output_csv(array $vars, $stream = 'php://output') { $out = fopen($stream, 'w'); + if ($out === FALSE) { + throw new \Exception(sprintf('Unable to open stream %s for writing.', $stream)); + } + fputcsv($out, $header); foreach ($vars as $line) { fputcsv($out, $line); @@ -223,7 +230,7 @@ function output_csv(array $vars, $stream = 'php://output') { * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ElseExpression) */ -function parse_variable_name($name, $prefix = NULL) { +function parse_variable_name(string $name, string $prefix = NULL): array { if (empty($name)) { throw new \Exception('Empty name provided.'); } @@ -246,6 +253,10 @@ function parse_variable_name($name, $prefix = NULL) { $parts = array_values($parts); } + if (empty($parts)) { + throw new \Exception(sprintf('Incorrectly named variable %s: component name is missing.', $name)); + } + // Filter by rule - maybe we do not need this variable at all. $allowed_rules = [ 'color', @@ -257,20 +268,23 @@ function parse_variable_name($name, $prefix = NULL) { 'border-right-color', ]; - foreach ($allowed_rules as $k => $allowed_rule) { - $allowed_rules[$k] = explode('-', $allowed_rule); + foreach ($allowed_rules as $k => $v) { + $allowed_rules[$k] = explode('-', $v); } - usort($allowed_rules, function ($a, $b) { + // @phpstan-ignore-next-line + usort($allowed_rules, function (array $a, array $b): int { return count($b) - count($a); }); - foreach ($allowed_rules as $k => $allowed_rule) { + foreach ($allowed_rules as $allowed_rule) { + // @phpstan-ignore-next-line if (count($parts) <= count($allowed_rule)) { continue; } $matched_count = 0; + // @phpstan-ignore-next-line $allowed_rule = array_reverse($allowed_rule); foreach ($allowed_rule as $allowed_rule_idx => $allowed_rule_part) { if ($parts[count($parts) - 1 - $allowed_rule_idx] == $allowed_rule_part) { @@ -338,7 +352,7 @@ function parse_variable_name($name, $prefix = NULL) { * * @SuppressWarnings(PHPMD.MissingImport) */ -function verbose() { +function verbose(): void { if (getenv('SCRIPT_QUIET') != '1') { print call_user_func_array('sprintf', func_get_args()) . PHP_EOL; } @@ -355,7 +369,8 @@ function verbose() { } // Custom error handler to catch errors based on set ERROR_LEVEL. -set_error_handler(function ($severity, $message, $file, $line) { +// @phpstan-ignore-next-line +set_error_handler(function ($severity, $message, $file, $line): void { if (!(error_reporting() & $severity)) { // This error code is not included in error_reporting. return; @@ -367,9 +382,6 @@ function verbose() { if (getenv('SCRIPT_RUN_SKIP') != 1) { try { $code = main($argv, $argc); - if (is_null($code)) { - throw new \Exception('Script exited without providing an exit code.'); - } exit($code); } catch (\ErrorException $exception) { diff --git a/web/themes/contrib/civictheme/civictheme_starter_kit/civictheme_starter_kit.theme b/web/themes/contrib/civictheme/civictheme_starter_kit/civictheme_starter_kit.theme index f91f3ea00..a8843538d 100644 --- a/web/themes/contrib/civictheme/civictheme_starter_kit/civictheme_starter_kit.theme +++ b/web/themes/contrib/civictheme/civictheme_starter_kit/civictheme_starter_kit.theme @@ -11,7 +11,7 @@ use Drupal\views\ViewExecutable; /** * Implements hook_civictheme_automated_list_preprocess_view_alter(). */ -function civictheme_starter_kit_civictheme_automated_list_preprocess_view_alter(array &$settings, ViewExecutable &$view) { +function civictheme_starter_kit_civictheme_automated_list_preprocess_view_alter(array &$settings, ViewExecutable &$view): void { if ($view->id() === 'civictheme_automated_list_examples' && $view->getDisplay()->display['id'] === 'civictheme_automated_list_page') { $settings['title'] = ''; $settings['theme'] = 'light'; @@ -24,7 +24,7 @@ function civictheme_starter_kit_civictheme_automated_list_preprocess_view_alter( /** * Implements hook_civictheme_automated_list_preprocess_view_alter(). */ -function civictheme_starter_kit_civictheme_automated_list_view_name_alter(string &$view_name, string &$display_id, Paragraph $paragraph) { +function civictheme_starter_kit_civictheme_automated_list_view_name_alter(string &$view_name, string &$display_id, Paragraph $paragraph): void { // This is an example. if ($paragraph->hasField('field_c_p_content_type') && !$paragraph->get('field_c_p_content_type')->isEmpty()) { if ($paragraph->get('field_c_p_content_type')->getString() == 'civictheme_event') { diff --git a/web/themes/contrib/civictheme/civictheme_starter_kit/scripts/add_phpcs_exclusions.php b/web/themes/contrib/civictheme/civictheme_starter_kit/scripts/add_phpcs_exclusions.php index 888ea1183..31f499551 100644 --- a/web/themes/contrib/civictheme/civictheme_starter_kit/scripts/add_phpcs_exclusions.php +++ b/web/themes/contrib/civictheme/civictheme_starter_kit/scripts/add_phpcs_exclusions.php @@ -39,7 +39,7 @@ * * @SuppressWarnings(PHPMD.MissingImport) */ -function main(array $argv, $argc) { +function main(array $argv, int $argc): int { if (in_array($argv[1] ?? NULL, ['--help', '-help', '-h', '-?'])) { print_help(); @@ -67,12 +67,16 @@ function main(array $argv, $argc) { $files = glob($target_directory . '**/*.js'); + if (empty($files)) { + throw new \Exception(sprintf('No files found in directory "%s".', $target_directory_original) . PHP_EOL); + } + foreach ($files as $file) { if (!file_exists($file)) { continue; } - $contents = file_get_contents($file); + $contents = file_get_contents($file) ?: ''; if (str_contains($contents, $template)) { print " > [SKIPPED] $file" . PHP_EOL; continue; @@ -90,7 +94,7 @@ function main(array $argv, $argc) { /** * Print help. */ -function print_help() { +function print_help(): void { print <<component_settings = $settings; // Preprocess view properties based on the settings above. @@ -163,7 +164,7 @@ function _civictheme_automated_list__get_view(array &$settings) { * @SuppressWarnings(PHPMD.MissingImport) * @SuppressWarnings(PHPMD.ElseExpression) */ -function _civictheme_automated_list__update_view(ViewExecutable $view) { +function _civictheme_automated_list__update_view(ViewExecutable $view): void { if (!isset($view->component_settings)) { return; } diff --git a/web/themes/contrib/civictheme/includes/banner.inc b/web/themes/contrib/civictheme/includes/banner.inc index cd3c6237d..e9c2bb851 100644 --- a/web/themes/contrib/civictheme/includes/banner.inc +++ b/web/themes/contrib/civictheme/includes/banner.inc @@ -21,7 +21,7 @@ use Drupal\Core\Link; * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ -function _civictheme_preprocess_block__civictheme_banner(&$variables) { +function _civictheme_preprocess_block__civictheme_banner(array &$variables): void { if ($variables['base_plugin_id'] != 'block_content') { return; } @@ -80,7 +80,7 @@ function _civictheme_preprocess_block__civictheme_banner(&$variables) { * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ -function _civictheme_preprocess_block__civictheme_banner__node(&$variables) { +function _civictheme_preprocess_block__civictheme_banner__node(array &$variables): void { $node = \Drupal::routeMatch()->getParameter('node_revision') ?: \Drupal::routeMatch()->getParameter('node'); if (empty($node)) { @@ -148,16 +148,13 @@ function _civictheme_preprocess_block__civictheme_banner__node(&$variables) { * @SuppressWarnings(PHPMD.StaticAccess) * @SuppressWarnings(PHPMD.ElseExpression) */ -function _civictheme_preprocess_block__civictheme_banner__breadcrumb(&$variables) { +function _civictheme_preprocess_block__civictheme_banner__breadcrumb(array &$variables): void { // Disable breadcrumb on homepage. if (\Drupal::service('path.matcher')->isFrontPage()) { return; } $breadcrumb = \Drupal::service('breadcrumb')->build(\Drupal::getContainer()->get('current_route_match')); - if (!$breadcrumb) { - return; - } // Always show the last item as a plain text (not a link). $variables['breadcrumb']['active_is_link'] = FALSE; diff --git a/web/themes/contrib/civictheme/includes/block_content.inc b/web/themes/contrib/civictheme/includes/block_content.inc index 2d978446d..528cde973 100644 --- a/web/themes/contrib/civictheme/includes/block_content.inc +++ b/web/themes/contrib/civictheme/includes/block_content.inc @@ -8,7 +8,7 @@ /** * Preprocess for block_content block. */ -function _civictheme_preprocess_block__content(&$variables) { +function _civictheme_preprocess_block__content(array &$variables): void { if (isset($variables['elements']['#base_plugin_id']) && $variables['base_plugin_id'] != 'block_content') { return; } diff --git a/web/themes/contrib/civictheme/includes/callout.inc b/web/themes/contrib/civictheme/includes/callout.inc index 1490404c8..b9c7b8dc2 100644 --- a/web/themes/contrib/civictheme/includes/callout.inc +++ b/web/themes/contrib/civictheme/includes/callout.inc @@ -8,7 +8,7 @@ /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_callout(&$variables) { +function civictheme_preprocess_paragraph__civictheme_callout(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__content($variables); _civictheme_preprocess_paragraph__paragraph_field__links($variables); diff --git a/web/themes/contrib/civictheme/includes/campaign.inc b/web/themes/contrib/civictheme/includes/campaign.inc index 3361ef709..c301d7e1b 100644 --- a/web/themes/contrib/civictheme/includes/campaign.inc +++ b/web/themes/contrib/civictheme/includes/campaign.inc @@ -8,7 +8,7 @@ /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_campaign(&$variables) { +function civictheme_preprocess_paragraph__civictheme_campaign(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__image($variables); _civictheme_preprocess_paragraph__paragraph_field__image_position($variables); diff --git a/web/themes/contrib/civictheme/includes/cards.inc b/web/themes/contrib/civictheme/includes/cards.inc index 186f8e30b..05f03c472 100644 --- a/web/themes/contrib/civictheme/includes/cards.inc +++ b/web/themes/contrib/civictheme/includes/cards.inc @@ -16,7 +16,7 @@ use Drupal\civictheme\CivicthemeConstants; /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_promo_card(&$variables) { +function civictheme_preprocess_paragraph__civictheme_promo_card(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__image($variables); _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__summary($variables); @@ -30,7 +30,7 @@ function civictheme_preprocess_paragraph__civictheme_promo_card(&$variables) { /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_promo_card_ref(&$variables) { +function civictheme_preprocess_paragraph__civictheme_promo_card_ref(array &$variables): void { _civictheme_preprocess_paragraph__node_field__image($variables); _civictheme_preprocess_paragraph__node_field__title($variables); _civictheme_preprocess_paragraph__node_field__summary($variables); @@ -44,7 +44,7 @@ function civictheme_preprocess_paragraph__civictheme_promo_card_ref(&$variables) * * @SuppressWarnings(PHPMD.ElseExpression) */ -function _civictheme_preprocess_node__civictheme_promo_card(&$variables) { +function _civictheme_preprocess_node__civictheme_promo_card(array &$variables): void { /** @var \Drupal\node\NodeInterface $node */ $node = $variables['node']; @@ -77,7 +77,7 @@ function _civictheme_preprocess_node__civictheme_promo_card(&$variables) { /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_event_card(&$variables) { +function civictheme_preprocess_paragraph__civictheme_event_card(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__image($variables); _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__summary($variables); @@ -92,7 +92,7 @@ function civictheme_preprocess_paragraph__civictheme_event_card(&$variables) { /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_event_card_ref(&$variables) { +function civictheme_preprocess_paragraph__civictheme_event_card_ref(array &$variables): void { _civictheme_preprocess_paragraph__node_field__image($variables); _civictheme_preprocess_paragraph__node_field__title($variables); _civictheme_preprocess_paragraph__node_field__location($variables); @@ -106,7 +106,7 @@ function civictheme_preprocess_paragraph__civictheme_event_card_ref(&$variables) /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_navigation_card(&$variables) { +function civictheme_preprocess_paragraph__civictheme_navigation_card(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__image($variables); _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__summary($variables); @@ -119,7 +119,7 @@ function civictheme_preprocess_paragraph__civictheme_navigation_card(&$variables /** * Implements template_preprocess_node(). */ -function _civictheme_preprocess_node__civictheme_navigation_card(&$variables) { +function _civictheme_preprocess_node__civictheme_navigation_card(array &$variables): void { _civictheme_preprocess_paragraph__node_field__image($variables); _civictheme_preprocess_paragraph__node_field__title($variables); _civictheme_preprocess_paragraph__node_field__summary($variables, 'civictheme_navigation_card'); @@ -131,7 +131,7 @@ function _civictheme_preprocess_node__civictheme_navigation_card(&$variables) { /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_navigation_card_ref(&$variables) { +function civictheme_preprocess_paragraph__civictheme_navigation_card_ref(array &$variables): void { _civictheme_preprocess_paragraph__node_field__title($variables); _civictheme_preprocess_paragraph__node_field__summary($variables); _civictheme_preprocess_paragraph__node_field__image($variables); @@ -142,7 +142,7 @@ function civictheme_preprocess_paragraph__civictheme_navigation_card_ref(&$varia /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_publication_card(&$variables) { +function civictheme_preprocess_paragraph__civictheme_publication_card(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__image($variables); _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__summary($variables); @@ -160,7 +160,7 @@ function civictheme_preprocess_paragraph__civictheme_publication_card(&$variable /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_subject_card(&$variables) { +function civictheme_preprocess_paragraph__civictheme_subject_card(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__image($variables); _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__link($variables); @@ -170,7 +170,7 @@ function civictheme_preprocess_paragraph__civictheme_subject_card(&$variables) { /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_subject_card_ref(&$variables) { +function civictheme_preprocess_paragraph__civictheme_subject_card_ref(array &$variables): void { _civictheme_preprocess_paragraph__node_field__image($variables); _civictheme_preprocess_paragraph__node_field__title($variables); _civictheme_preprocess_paragraph__node_field__link($variables); @@ -180,7 +180,7 @@ function civictheme_preprocess_paragraph__civictheme_subject_card_ref(&$variable /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_service_card(&$variables) { +function civictheme_preprocess_paragraph__civictheme_service_card(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__title($variables); _civictheme_preprocess_paragraph__paragraph_field__links($variables); _civictheme_preprocess_paragraph__paragraph_field__theme($variables); diff --git a/web/themes/contrib/civictheme/includes/content.inc b/web/themes/contrib/civictheme/includes/content.inc index 1b6033537..1410d65aa 100644 --- a/web/themes/contrib/civictheme/includes/content.inc +++ b/web/themes/contrib/civictheme/includes/content.inc @@ -8,7 +8,7 @@ /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_content(&$variables) { +function civictheme_preprocess_paragraph__civictheme_content(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__content($variables); _civictheme_preprocess_paragraph__paragraph_field__theme($variables); _civictheme_preprocess_paragraph__paragraph_field__vertical_spacing($variables); diff --git a/web/themes/contrib/civictheme/includes/form.inc b/web/themes/contrib/civictheme/includes/form.inc index 6ca4121dc..d09321153 100644 --- a/web/themes/contrib/civictheme/includes/form.inc +++ b/web/themes/contrib/civictheme/includes/form.inc @@ -16,7 +16,7 @@ use Drupal\paragraphs\Entity\Paragraph; * * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_form_alter(&$form, FormStateInterface $form_state, $form_id) { +function civictheme_form_alter(array &$form, FormStateInterface $form_state, string $form_id): void { _civictheme_form_alter__webform_submission($form, $form_state, $form_id); _civictheme_form_alter__non_form_elements($form); } @@ -24,14 +24,14 @@ function civictheme_form_alter(&$form, FormStateInterface $form_state, $form_id) /** * Implements template_preprocess_select(). */ -function civictheme_preprocess_select(&$variables) { +function civictheme_preprocess_select(array &$variables): void { _civictheme_preprocess_form__theme($variables); } /** * Implements template_preprocess_input(). */ -function civictheme_preprocess_input(&$variables) { +function civictheme_preprocess_input(array &$variables): void { _civictheme_preprocess_form__theme($variables); $variables['state'] = 'none'; @@ -50,7 +50,7 @@ function civictheme_preprocess_input(&$variables) { /** * Implements template_preprocess_form_element(). */ -function civictheme_preprocess_form_element(&$variables) { +function civictheme_preprocess_form_element(array &$variables): void { _civictheme_preprocess_form__theme($variables); _civictheme_preprocess_form_element__classes($variables); _civictheme_preprocess_form_element__description($variables); @@ -59,7 +59,7 @@ function civictheme_preprocess_form_element(&$variables) { /** * Implements template_preprocess_form_element_label(). */ -function civictheme_preprocess_form_element_label(&$variables) { +function civictheme_preprocess_form_element_label(array &$variables): void { _civictheme_preprocess_form__theme($variables); $variables['content'] = $variables['title'] ?? ''; @@ -74,21 +74,19 @@ function civictheme_preprocess_form_element_label(&$variables) { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function _civictheme_form_alter__webform_submission(&$form, FormStateInterface $form_state, $form_id) { +function _civictheme_form_alter__webform_submission(array &$form, FormStateInterface $form_state, string $form_id): void { if (!empty($form_id) && strpos($form_id, 'webform_submission_') === 0) { /** @var \Drupal\webform\WebformSubmissionForm $form_object */ $form_object = $form_state->getFormObject(); /** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */ $webform_submission = $form_object->getEntity(); - if ($webform_submission) { - $source = $webform_submission->getSourceEntity(); - - $paragraph_id = !empty($source) ? $source->id() : ''; - if (!empty($paragraph_id) && !empty($form['elements'])) { - $theme = civictheme_get_field_theme_value(Paragraph::load($paragraph_id)); - _civictheme_form__propagate_component_theme($form['elements'], $theme); - } + $source = $webform_submission->getSourceEntity(); + + $paragraph_id = !empty($source) ? $source->id() : ''; + if (!empty($paragraph_id) && !empty($form['elements'])) { + $theme = civictheme_get_field_theme_value(Paragraph::load($paragraph_id)); + _civictheme_form__propagate_component_theme($form['elements'], $theme); } } } @@ -104,7 +102,7 @@ function _civictheme_form_alter__webform_submission(&$form, FormStateInterface $ * * @SuppressWarnings(PHPMD.StaticAccess) */ -function _civictheme_form_alter__non_form_elements(&$elements) { +function _civictheme_form_alter__non_form_elements(array &$elements): void { $element_keys = Element::children($elements); foreach ($element_keys as $element_key) { if (empty($elements[$element_key]['#type'])) { @@ -129,7 +127,7 @@ function _civictheme_form_alter__non_form_elements(&$elements) { /** * Alter link elements within forms. */ -function _civictheme_form_alter__non_form_elements__link(&$element) { +function _civictheme_form_alter__non_form_elements__link(array &$element): void { // Convert "button" links into CivicTheme button links. if (!empty($element['#attributes']['class']) && in_array('button', $element['#attributes']['class'])) { $element_theme = _civictheme_form__get_component_theme($element); @@ -145,7 +143,7 @@ function _civictheme_form_alter__non_form_elements__link(&$element) { /** * Sets form element theme based on attributes passed from parent components. */ -function _civictheme_preprocess_form__theme(&$variables) { +function _civictheme_preprocess_form__theme(array &$variables): void { // Setting theme for form element. if ( isset($variables['element']['#attributes']['#civictheme_theme']) @@ -169,7 +167,7 @@ function _civictheme_preprocess_form__theme(&$variables) { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function _civictheme_preprocess_form__hidden_fields($variables) { +function _civictheme_preprocess_form__hidden_fields(array $variables): void { if (empty($variables['form'])) { return; } @@ -198,7 +196,7 @@ function _civictheme_preprocess_form__hidden_fields($variables) { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function _civictheme_preprocess_form_element__classes(&$variables) { +function _civictheme_preprocess_form_element__classes(array &$variables): void { // Handle any malformed attribute class properties. $variables['attributes']['class'] = $variables['attributes']['class'] ?? []; $variables['attributes']['class'] = is_string($variables['attributes']['class']) ? [$variables['attributes']['class']] : $variables['attributes']['class']; @@ -224,7 +222,7 @@ function _civictheme_preprocess_form_element__classes(&$variables) { /** * Preprocesses form element description. */ -function _civictheme_preprocess_form_element__description(&$variables) { +function _civictheme_preprocess_form_element__description(array &$variables): void { $variables['description'] = $variables['element']['#description'] ?? NULL; $variables['description_display'] = $variables['element']['#description_display'] ?? NULL; } @@ -232,9 +230,15 @@ function _civictheme_preprocess_form_element__description(&$variables) { /** * Get fields from the form without hidden fields. * + * @param array $form + * Form array. + * + * @return array + * Array of fields. + * * @SuppressWarnings(PHPMD.StaticAccess) */ -function _civictheme_form__get_fields($form) { +function _civictheme_form__get_fields(array $form): array { $exclude = [ 'form_build_id', 'form_id', @@ -250,7 +254,7 @@ function _civictheme_form__get_fields($form) { /** * Get component theme from the element. */ -function _civictheme_form__get_component_theme($element) { +function _civictheme_form__get_component_theme(array $element): string { $theme = CivicthemeConstants::THEME_LIGHT; if (isset($element['#attributes']['#civictheme_theme']) && in_array($element['#attributes']['#civictheme_theme'], [ @@ -268,7 +272,7 @@ function _civictheme_form__get_component_theme($element) { * * @SuppressWarnings(PHPMD.StaticAccess) */ -function _civictheme_form__propagate_component_theme(&$elements, $theme) { +function _civictheme_form__propagate_component_theme(array &$elements, string $theme): void { $form_elements = Element::children($elements); foreach ($form_elements as $form_element) { $elements[$form_element]['#attributes']['#civictheme_theme'] = $theme; @@ -283,6 +287,6 @@ function _civictheme_form__propagate_component_theme(&$elements, $theme) { /** * Check if form field is set to have multiple values. */ -function _civictheme_form__field_is_multiple(array $field) { - return $field['#type'] == 'checkboxes' || ($field['#type'] == 'select' && $field["#multiple"] ?? FALSE); +function _civictheme_form__field_is_multiple(array $field): bool { + return $field['#type'] == 'checkboxes' || ($field['#type'] == 'select' && ($field["#multiple"] ?? FALSE)); } diff --git a/web/themes/contrib/civictheme/includes/iframe.inc b/web/themes/contrib/civictheme/includes/iframe.inc index 2424bf245..c8108e6b5 100644 --- a/web/themes/contrib/civictheme/includes/iframe.inc +++ b/web/themes/contrib/civictheme/includes/iframe.inc @@ -8,7 +8,7 @@ /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_iframe(&$variables) { +function civictheme_preprocess_paragraph__civictheme_iframe(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__theme($variables); _civictheme_preprocess_paragraph__paragraph_field__vertical_spacing($variables); _civictheme_preprocess_paragraph__paragraph_field__background($variables); diff --git a/web/themes/contrib/civictheme/includes/image.inc b/web/themes/contrib/civictheme/includes/image.inc index 530967ef9..fa0362dc6 100644 --- a/web/themes/contrib/civictheme/includes/image.inc +++ b/web/themes/contrib/civictheme/includes/image.inc @@ -10,7 +10,7 @@ * * @SuppressWarnings(PHPMD.StaticAccess) */ -function _civictheme_preprocess_image(&$variables) { +function _civictheme_preprocess_image(array &$variables): void { if (isset($variables['attributes']['src'])) { $variables['url'] = $variables['attributes']['src']; } diff --git a/web/themes/contrib/civictheme/includes/libraries.inc b/web/themes/contrib/civictheme/includes/libraries.inc index 950c312b9..8bcb83a31 100644 --- a/web/themes/contrib/civictheme/includes/libraries.inc +++ b/web/themes/contrib/civictheme/includes/libraries.inc @@ -24,7 +24,7 @@ use Drupal\civictheme\CivicthemeConfigManager; * @SuppressWarnings(PHPMD.StaticAccess) * @SuppressWarnings(PHPMD.ElseExpression) */ -function _civictheme_library_info_alter__color_selector(&$libraries, $extension) { +function _civictheme_library_info_alter__color_selector(array &$libraries, string $extension): void { // Filter for the current theme or a parent theme (in case if current theme is // a sub-theme of a theme that declares libraries). $themes = \Drupal::service('theme_handler')->listInfo(); diff --git a/web/themes/contrib/civictheme/includes/link.inc b/web/themes/contrib/civictheme/includes/link.inc index 3177f4957..a6d85416b 100644 --- a/web/themes/contrib/civictheme/includes/link.inc +++ b/web/themes/contrib/civictheme/includes/link.inc @@ -34,15 +34,20 @@ function _civictheme_process_html_content_links($html, $base_url, $new_window = return $html; } + if (empty($html)) { + return $html; + } + $class_prefix = 'ct-'; $link_class = 'ct-content-link ct-theme-light'; $link_external_class = 'ct-content-link--external'; $html = _civictheme_process_html_content_links_emails($html); - $dom = Html::load($html); - - if (!$dom) { + try { + $dom = Html::load($html); + } + catch (\Exception $e) { return $html; } @@ -108,14 +113,15 @@ function _civictheme_process_html_content_links($html, $base_url, $new_window = * @SuppressWarnings(PHPMD.StaticAccess) * @SuppressWarnings(PHPMD.MissingImport) */ -function _civictheme_process_html_content_links_emails($html) { +function _civictheme_process_html_content_links_emails(string $html): string { if (_civictheme_feature_is_optedout('process', 'components.link.email')) { return $html; } - $dom = Html::load($html); - - if (!$dom) { + try { + $dom = Html::load($html); + } + catch (\Exception $e) { return $html; } @@ -123,12 +129,18 @@ function _civictheme_process_html_content_links_emails($html) { $text_nodes = $xpath->query('//text()[not(ancestor::a)]'); + if (!$text_nodes || !$text_nodes->count()) { + return $html; + } + foreach ($text_nodes as $text_node) { if (preg_match_all(_civictheme_process_html_content_links_get_email_regex(), $text_node->nodeValue, $matches)) { $emails = $matches[0]; foreach ($emails as $email) { $replacement = $dom->createDocumentFragment(); + // @phpstan-ignore-next-line $replacement->appendXML(str_replace($email, "$email", $text_node->textContent)); + /** @var \DOMChildNode $text_node */ $text_node->replaceWith($replacement); } } @@ -140,6 +152,6 @@ function _civictheme_process_html_content_links_emails($html) { /** * Email pattern as a regex string. */ -function _civictheme_process_html_content_links_get_email_regex() { +function _civictheme_process_html_content_links_get_email_regex(): string { return '/\b[A-Za-z0-9._%+-]+@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+(?:[a-zA-Z]{2,})\b)(?!\.[a-zA-Z0-9]{1,}\b)/'; } diff --git a/web/themes/contrib/civictheme/includes/local_tasks.inc b/web/themes/contrib/civictheme/includes/local_tasks.inc index af47a0059..6f4be03b4 100644 --- a/web/themes/contrib/civictheme/includes/local_tasks.inc +++ b/web/themes/contrib/civictheme/includes/local_tasks.inc @@ -10,7 +10,7 @@ use Drupal\civictheme\CivicthemeConstants; /** * Pre-process for local tasks. */ -function _civictheme_preprocess_menu_local_tasks(&$variables) { +function _civictheme_preprocess_menu_local_tasks(array &$variables): void { $local_task_types = ['primary', 'secondary']; $context_theme = civictheme_get_theme_config_manager()->load('components.header.theme', CivicthemeConstants::HEADER_THEME_DEFAULT); @@ -31,7 +31,8 @@ function _civictheme_preprocess_menu_local_tasks(&$variables) { } // Sort tabs by weight. - array_multisort(array_column($variables['links'][$local_task_type], 'weight'), SORT_ASC, $variables['links'][$local_task_type]); + $weights = array_column($variables['links'][$local_task_type], 'weight'); + array_multisort($weights, SORT_ASC, $variables['links'][$local_task_type]); unset($variables[$local_task_type]); } } diff --git a/web/themes/contrib/civictheme/includes/manual_list.inc b/web/themes/contrib/civictheme/includes/manual_list.inc index 3fe8a3de8..7b360db68 100644 --- a/web/themes/contrib/civictheme/includes/manual_list.inc +++ b/web/themes/contrib/civictheme/includes/manual_list.inc @@ -12,7 +12,7 @@ use Drupal\Component\Utility\Html; * * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_preprocess_paragraph__civictheme_manual_list(&$variables) { +function civictheme_preprocess_paragraph__civictheme_manual_list(array &$variables): void { /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */ $paragraph = $variables['paragraph']; @@ -34,6 +34,7 @@ function civictheme_preprocess_paragraph__civictheme_manual_list(&$variables) { 'cache_tags' => $paragraph->getCacheTags(), ]; + /** @var \Drupal\Core\Entity\EntityInterface[] $items */ $items = civictheme_get_field_referenced_entities($paragraph, 'field_c_p_list_items'); $builder = \Drupal::entityTypeManager()->getViewBuilder('paragraph'); if ($items) { diff --git a/web/themes/contrib/civictheme/includes/map.inc b/web/themes/contrib/civictheme/includes/map.inc index e1444052d..3c4406628 100644 --- a/web/themes/contrib/civictheme/includes/map.inc +++ b/web/themes/contrib/civictheme/includes/map.inc @@ -8,7 +8,7 @@ /** * Implements template_preprocess_paragraph(). */ -function civictheme_preprocess_paragraph__civictheme_map(&$variables) { +function civictheme_preprocess_paragraph__civictheme_map(array &$variables): void { _civictheme_preprocess_paragraph__paragraph_field__theme($variables); _civictheme_preprocess_paragraph__paragraph_field__vertical_spacing($variables); _civictheme_preprocess_paragraph__paragraph_field__background($variables); diff --git a/web/themes/contrib/civictheme/includes/media.inc b/web/themes/contrib/civictheme/includes/media.inc index add994f0e..a210a1a31 100644 --- a/web/themes/contrib/civictheme/includes/media.inc +++ b/web/themes/contrib/civictheme/includes/media.inc @@ -6,23 +6,26 @@ */ use Drupal\Core\Template\Attribute; +use Drupal\file\FileInterface; +use Drupal\media\MediaInterface; /** * Implements hook_preprocess__HOOK(). * * @SuppressWarnings(PHPMD.StaticAccess) */ -function civictheme_preprocess_media__civictheme_image(&$variables) { +function civictheme_preprocess_media__civictheme_image(array &$variables): void { if (empty($variables['media'])) { return; } - /** @var \Drupal\media\MediaInterface $media */ $media = $variables['media']; - /** @var \Drupal\file\Entity\File|null $image_file */ - $image_file = civictheme_get_field_referenced_entities($media, 'field_c_m_image', TRUE); - if ($image_file) { - /** @var \Drupal\Core\Image\ImageInterface $image */ + if (!$media instanceof MediaInterface) { + return; + } + + $image_file = civictheme_get_field_referenced_entity($media, 'field_c_m_image'); + if ($image_file instanceof FileInterface) { $image = \Drupal::service('image.factory')->get($image_file->getFileUri()); if ($image->isValid()) { $variables['width'] = $image->getWidth(); @@ -37,16 +40,20 @@ function civictheme_preprocess_media__civictheme_image(&$variables) { /** * Implements hook_preprocess__HOOK(). */ -function civictheme_preprocess_media__civictheme_video(&$variables) { +function civictheme_preprocess_media__civictheme_video(array &$variables): void { if (empty($variables['media'])) { return; } - /** @var \Drupal\media\MediaInterface $media */ $media = $variables['media']; + if (!$media instanceof MediaInterface) { + return; + } - /** @var \Drupal\file\Entity\File $video_file */ foreach ($media->get('field_c_m_video_file')->referencedEntities() as $video_file) { + if (!$video_file instanceof FileInterface) { + continue; + } $variables['sources'][] = [ 'url' => $video_file->createFileUrl(), 'type' => $video_file->getMimeType(), @@ -65,13 +72,16 @@ function civictheme_preprocess_media__civictheme_video(&$variables) { * @SuppressWarnings(PHPMD.StaticAccess) * @SuppressWarnings(PHPMD.MissingImport) */ -function civictheme_preprocess_media__civictheme_remote_video(&$variables) { +function civictheme_preprocess_media__civictheme_remote_video(array &$variables): void { if (empty($variables['media'])) { return; } - /** @var \Drupal\media\MediaInterface $media */ $media = $variables['media']; + if (!$media instanceof MediaInterface) { + return; + } + try { $resource_url = \Drupal::service('media.oembed.url_resolver')->getResourceUrl($media->get('field_c_m_oembed_video')->first()->getValue()['value'], $variables['width'] ?? NULL, $variables['height'] ?? NULL); $resource = \Drupal::service('media.oembed.resource_fetcher')->fetchResource($resource_url); @@ -80,14 +90,13 @@ function civictheme_preprocess_media__civictheme_remote_video(&$variables) { // Set 'title' attribute (if provided) on the oEmbed iframe element. $doc = _civictheme_get_dom_document($html); - if ($doc) { - $iframe_elements = $doc->getElementsByTagName('iframe'); - // oEmbed can use an HTML tag other than