diff --git a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js index 296861a70..2422200f8 100644 --- a/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js +++ b/modules/hdbt_cookie_banner/assets/js/hdbt-cookie-banner.js @@ -1,5 +1,12 @@ 'use strict'; +class UnapprovedItemError extends Error { + constructor(message, name) { + super(message) + this.name = name + } +} + ((Drupal, drupalSettings) => { // Global cookie consent status object. @@ -36,7 +43,7 @@ language: drupalSettings.hdbt_cookie_banner.langcode, theme: drupalSettings.hdbt_cookie_banner.theme, settingsPageSelector: drupalSettings.hdbt_cookie_banner.settingsPageSelector, - spacerParentSelector: '.footer', + spacerParentSelector: drupalSettings.hdbt_cookie_banner.spacerParentSelector || '.footer', }; window.hds.CookieConsentCore.create(apiUrl, options); } @@ -67,41 +74,32 @@ window.addEventListener( 'hds-cookie-consent-unapproved-item-found', (e) => { + if (typeof window.Sentry === 'undefined') { + return; + } const { storageType, keys, acceptedGroups } = e.detail // Alphabetize the keys array const sortedKeys = keys.sort(); - if (window.Sentry) { - // Sentry requires a unique name for each error in order to record - // each found unapproved item per type. - const name = `Unapproved ${storageType}` - const message = `Found: ${sortedKeys.join(', ')}` + // Sentry requires a unique name for each error in order to record + // each found unapproved item per type. + const name = `Unapproved ${storageType}` + const message = `Found: ${sortedKeys.join(', ')}` - class UnapprovedItemError extends Error { - constructor(message) { - super(message) - this.name = name - } - } - - // Capture the error with Sentry and send a message with the - // unapproved items so that they can be searched in Sentry. - window.Sentry.captureException(new UnapprovedItemError(message), { - level: 'warning', - tags: { - approvedCategories: acceptedGroups.join(', '), - }, - extra: { - storageType, - cookieNames: sortedKeys, - approvedCategories: acceptedGroups, - }, - }) - } else { - // If Sentry is not defined, throw an error. - throw new Error('Sentry is not defined') - } + // Capture the error with Sentry and send a message with the + // unapproved items so that they can be searched in Sentry. + window.Sentry.captureException(new UnapprovedItemError(message, name), { + level: 'warning', + tags: { + approvedCategories: acceptedGroups.join(', '), + }, + extra: { + storageType, + cookieNames: sortedKeys, + approvedCategories: acceptedGroups, + }, + }) } ) }, diff --git a/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json b/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json index 4484457f1..7d2ed97e3 100644 --- a/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json +++ b/modules/hdbt_cookie_banner/assets/json/siteSettingsTemplate.json @@ -29,9 +29,9 @@ "en": "Essential cookies" }, "description": { - "fi": "Välttämättömät evästeet auttavat tekemään verkkosivustosta käyttökelpoisen sallimalla perustoimintoja, kuten sivulla siirtymisen ja sivuston suojattujen alueiden käytön. Verkkosivusto ei toimi kunnolla ilman näitä evästeitä eikä niihin tarvita suostumusta.", - "sv": "Nödvändiga cookies hjälper till att göra webbplatsen användbar genom att tillåta grundläggande funktioner som att navigera på sidan och använda de skyddade områdena på webbplatsen. Webbplatsen fungerar inte korrekt utan dessa cookies och kräver inte samtycke.", - "en": "Essential cookies help to make the website usable by allowing basic functions, navigating the page and using the protected areas of the site. The website will not work properly without these cookies and their consent is not required." + "fi": "Välttämättömät evästeet varmistavat, että sivusto toimii kunnolla. Välttämättömiin evästeisiin ei tarvita suostumusta. Nämä evästeet mahdollistavat perustoimintoja, kuten sivulla siirtymisen ja sivuston suojattujen alueiden käytön.", + "sv": "Nödvändiga kakor säkerställer att webbplatsen fungerar ordentligt. För nödvändiga kakor behövs inte samtycke. Dessa kakor möjliggör grundläggande funktioner såsom sidnavigering och åtkomst till skyddade områden på webbplatsen.", + "en": "Essential cookies ensure that the website functions correctly. Essential cookies do not require consent. These cookies enable basic functions, such as site navigation and access to protected areas of the website." }, "cookies": [ { @@ -41,88 +41,14 @@ "description": { "fi": "Sivusto käyttää tätä evästettä tietojen tallentamiseen siitä, ovatko kävijät antaneet hyväksyntänsä tai kieltäytyneet evästeiden käytöstä.", "sv": "Cookie möjliggör hantering av cookies på webbplatsen.", - "en": "Used by www.hel.fi Drupal to store information about whether visitors have given or declined the use of cookie categories used on the www.hel.fi site." + "en": "Used by change-me.hel.fi Drupal to store information about whether visitors have given or declined the use of cookie categories used on the change-me.hel.fi site." }, "expiration": { "fi": "100 päivää", "sv": "100 dagar", "en": "100 days" - } - }, - { - "name": "SSESS*", - "host": "change-me.hel.fi", - "storageType": 1, - "description": { - "fi": "Sisällönhallintajärjestelmän toimintaan liittyvä eväste.", - "sv": "En cookie relaterad till driften av innehållshanteringssystemet.", - "en": "A cookie related to the operation of the content management system." - }, - "expiration": { - "fi": "23 päivää", - "sv": "23 dagar", - "en": "23 days" - } - }, - { - "name": "mtm_cookie_consent", - "host": "kartta.hel.fi", - "storageType": 1, - "description": { - "fi": "Tekninen eväste johon talletetaan tieto valinnastasi evästeiden käytöstä kertovan bannerin kohdalla", - "sv": "A technical cookie that stores information about how you responded to the notice in the cookie banner about the use of cookies.", - "en": "A technical cookie that stores information about how you responded to the notice in the cookie banner about the use of cookies." - }, - "expiration": { - "fi": "10950 päivää", - "sv": "10950 dagar", - "en": "10950 days" - } - }, - { - "name": "JSESSIONID", - "host": "helsinkikanava.fi", - "storageType": 1, - "description": { - "fi": "Sivuston pakollinen eväste mahdollistaa kävijän vierailun sivustolla.", - "sv": "Kakan är en obligatorisk kaka som gör det möjligt för besökaren att besöka webbplatsen.", - "en": "The cookie is an obligatory cookie that facilitates visiting the website." }, - "expiration": { - "fi": "Istunto", - "sv": "Session", - "en": "Session" - } - }, - { - "name": "COOKIE_SUPPORT", - "host": "helsinkikanava.fi", - "storageType": 1, - "description": { - "fi": "Mahdollistaa evästeiden hallinnan sivustolla.", - "sv": "Kakan möjliggör hanteringen av kakor på webbplatsen.", - "en": "The cookie facilitates managing cookies on the website." - }, - "expiration": { - "fi": "365 päivää", - "sv": "365 dagar", - "en": "365 days" - } - }, - { - "name": "GUEST_LANGUAGE_ID", - "host": "helsinkikanava.fi", - "storageType": 1, - "description": { - "fi": "Tämän evästeen on luonut Liferay, se tallentaa kieliasetukset.", - "sv": "Denna cookie genereras av Liferay, dess funktion är att lagra språkinställningarna.", - "en": "This cookie is generated by the Liferay, its function is to store the language preferences." - }, - "expiration": { - "fi": "365 päivää", - "sv": "365 dagar", - "en": "365 days" - } + "ype": 1 }, { "name": "helfi-settings", @@ -130,8 +56,8 @@ "storageType": 2, "description": { "fi": "Sivusto käyttää tätä tietuetta tietojen tallentamiseen siitä, mitä poikkeusilmoituksia on suljettu ja mikä on avattavien sisältöalueiden tila.", - "sv": "Används av hel.fi Drupal för att lagra information om stängda meddelanden och accordions' tillstånd.", - "en": "Used by hel.fi Drupal to store information about closed announcements and accordions' state." + "sv": "Används av change-me.hel.fi Drupal för att lagra information om stängda meddelanden och accordions' tillstånd.", + "en": "Used by change-me.hel.fi Drupal to store information about closed announcements and accordions' state." }, "expiration": "-" } @@ -145,21 +71,25 @@ "en": "Editors' functional cookies" }, "description": { - "fi": "Sisäänkirjautuneiden sisällöntuottajien välttämättömät toiminnalliset evästeet mahdollistavat editointityökalujen käytön niitä käyttäville. Näitä evästeitä ei aseteta kirjautumattomille käyttäjille.", - "sv": "Nödvändiga funktionella cookies för inloggade redaktörer möjliggör användning av redigeringsverktyg för dem som använder dem. Dessa cookies är inte inställda för icke-inloggade användare.", - "en": "Necessary functional cookies for logged-in editors enable the use of editing tools for those who use them. These cookies are not set for non-logged in users." + "fi": "Sisällöntuottajien välttämättömät toiminnalliset evästeet tallennetaan ainoastaan kirjautuneille sisällöntuottajille. Ne mahdollistavat sivuston muokkaustoiminnot.", + "sv": "Nödvändiga funktionella kakor för innehållsproducenter sparas endast hos inloggade innehållsproducenter. De möjliggör funktioner för redigering av webbplatsen.", + "en": "The essential functional cookies for content providers are only saved for content providers who are signed in. They enable the editing of the website." }, "cookies": [ { - "name": "editoria11yResultCount", + "name": "SSESS*", "host": "change-me.hel.fi", - "storageType": 2, + "storageType": 1, "description": { - "fi": "Tallentaa sisällöntuottajan näkemien saavutettavuusongelmien lukumäärän nykyisellä sivulla.", - "sv": "Spårar tillgänglighetsproblem för den aktuella sidan när du är inloggad som redaktör på hel.fi.", - "en": "Tracks accessibility issues for the current page when logged in as an editor on hel.fi." + "fi": "Sisällönhallintajärjestelmän toimintaan liittyvä eväste.", + "sv": "En cookie relaterad till driften av innehållshanteringssystemet.", + "en": "A cookie related to the operation of the content management system." }, - "expiration": "-" + "expiration": { + "fi": "23 päivää", + "sv": "23 dagar", + "en": "23 days" + } }, { "name": "Drupal.gin.sidebarExpanded.desktop", @@ -167,8 +97,8 @@ "storageType": 2, "description": { "fi": "Tallentaa tiedon sisällöntuottajan käyttöliittymän sivupalkin näkyvyydestä työpöytänäkymässä.", - "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på skrivbordet när du är inloggad som redaktör på hel.fi.", - "en": "Stores whether the admin sidebar is expanded or collapsed on desktop when logged in as an editor on hel.fi." + "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på skrivbordet när du är inloggad som redaktör på change-me.hel.fi.", + "en": "Stores whether the admin sidebar is expanded or collapsed on desktop when logged in as an editor on change-me.hel.fi." }, "expiration": "-" }, @@ -178,8 +108,8 @@ "storageType": 2, "description": { "fi": "Tallentaa tiedon sisällöntuottajan käyttöliittymän sivupalkin näkyvyydestä mobiilinäkymässä.", - "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på mobil när du är inloggad som redaktör på hel.fi.", - "en": "Stores whether the admin sidebar is expanded or collapsed on mobile when logged in as an editor on hel.fi." + "sv": "Lagrar om admin-sidopanelen är expanderad eller kollapsad på mobil när du är inloggad som redaktör på change-me.hel.fi.", + "en": "Stores whether the admin sidebar is expanded or collapsed on mobile when logged in as an editor on change-me.hel.fi." }, "expiration": "-" }, @@ -189,8 +119,8 @@ "storageType": 2, "description": { "fi": "Tallentaa tiedon sisällöntuottajan valitsemasta \"tumma tila\"-asetuksesta.", - "sv": "Lagrar användarens mörkt läge-inställning i admin-temat när du är inloggad som redaktör på hel.fi.", - "en": "Stores the user's dark mode preference in the admin theme when logged in as an editor on hel.fi." + "sv": "Lagrar användarens mörkt läge-inställning i admin-temat när du är inloggad som redaktör på change-me.hel.fi.", + "en": "Stores the user's dark mode preference in the admin theme when logged in as an editor on change-me.hel.fi." }, "expiration": "-" }, @@ -216,17 +146,6 @@ }, "expiration": "-" }, - { - "name": "ed11ySeen", - "host": "change-me.hel.fi", - "storageType": 2, - "description": { - "fi": "Tallentaa sisällöntuottajan näkemät saavutettavuusongelmat, jotta vältetään ongelmien kaksoisilmoitukset.", - "sv": "Spårar vilka tillgänglighetsproblem en inloggad redaktör redan har sett för att undvika dubbla aviseringar.", - "en": "Tracks which accessibility issues a logged-in editor has already seen to avoid duplicate notifications." - }, - "expiration": "-" - }, { "name": "Drupal.toolbar.toolbarState", "host": "change-me.hel.fi", @@ -256,6 +175,28 @@ "sv": "Session", "en": "Session" } + }, + { + "name": "editoria11yResultCount", + "host": "change-me.hel.fi", + "storageType": 2, + "description": { + "fi": "Tallentaa löydettyjen saavutettavuusongelmien määrän sisällöntuottajalle, auttaen seuraamaan ja korjaamaan ne.", + "sv": "Spårar antalet tillgänglighetsproblem som hittats på specifika sidor för en inloggad redaktör, vilket hjälper till att övervaka och åtgärda dem.", + "en": "Tracks the number of accessibility issues found on specific pages for a logged-in editor, helping monitor and address them." + }, + "expiration": "-" + }, + { + "name": "ed11ySeen", + "host": "change-me.hel.fi", + "storageType": 2, + "description": { + "fi": "Tallentaa sisällöntuottajan näkemät saavutettavuusongelmat, jotta vältetään ongelmien kaksoisilmoitukset.", + "sv": "Spårar vilka tillgänglighetsproblem en inloggad redaktör redan har sett för att undvika dubbla aviseringar.", + "en": "Tracks which accessibility issues a logged-in editor has already seen to avoid duplicate notifications." + }, + "expiration": "-" } ] } @@ -275,28 +216,43 @@ }, "cookies": [ { - "name": "httpskartta.hel.fi.SWCulture", - "host": "kartta.hel.fi", + "name": "COOKIE_SUPPORT", + "host": "helsinkikanava.fi", "storageType": 1, "description": { - "fi": "Kaupungin karttapalvelun evästeeseen tallennetaan kieli, jolla palvelua käytetään.", - "sv": "I kakan på stadens kaktjänst sparas det språk som användaren använder i tjänsten.", - "en": "The City's map service cookie saves the language in which the service is used." + "fi": "Mahdollistaa evästeiden hallinnan sivustolla.", + "sv": "Kakan möjliggör hanteringen av kakor på webbplatsen.", + "en": "The cookie facilitates managing cookies on the website." }, "expiration": { - "fi": "1826 päivää", - "sv": "1826 dagar", - "en": "1826 days" + "fi": "365 päivää", + "sv": "365 dagar", + "en": "365 days" } }, { - "name": "icareus-device", + "name": "JSESSIONID", "host": "helsinkikanava.fi", "storageType": 1, "description": { - "fi": "Helsinki-kanavan videopalvelimen eväste.", - "sv": "Helsinki-kanavas kaka gör det möjligt att göra videor till en del av innehållet på webbplatsen.", - "en": "The Helsinki Channel video server cookie facilitates including videos as part of the website's content." + "fi": "Sivuston pakollinen eväste mahdollistaa kävijän vierailun sivustolla.", + "sv": "Kakan är en obligatorisk kaka som gör det möjligt för besökaren att besöka webbplatsen.", + "en": "The cookie is an obligatory cookie that facilitates visiting the website." + }, + "expiration": { + "fi": "Istunto", + "sv": "Session", + "en": "Session" + } + }, + { + "name": "GUEST_LANGUAGE_ID", + "host": "helsinkikanava.fi", + "storageType": 1, + "description": { + "fi": "Tämän evästeen on luonut Liferay, se tallentaa kieliasetukset.", + "sv": "Denna cookie genereras av Liferay, dess funktion är att lagra språkinställningarna.", + "en": "This cookie is generated by the Liferay, its function is to store the language preferences." }, "expiration": { "fi": "365 päivää", @@ -304,6 +260,32 @@ "en": "365 days" } }, + { + "name": "icareusDevice", + "host": "helsinkikanava.fi", + "storageType": 2, + "description": { + "fi": "Helsinki-kanavan videopalvelimen eväste.", + "sv": "Helsinki-kanavas kaka gör det möjligt att göra videor till en del av innehållet på webbplatsen.", + "en": "The Helsinki Channel video server cookie facilitates including videos as part of the website's content." + }, + "expiration": "-" + }, + { + "name": "httpskartta.hel.fi.SWCulture", + "host": "kartta.hel.fi", + "storageType": 1, + "description": { + "fi": "Kaupungin karttapalvelun evästeeseen tallennetaan kieli, jolla palvelua käytetään.", + "sv": "I kakan på stadens kaktjänst sparas det språk som användaren använder i tjänsten.", + "en": "The City's map service cookie saves the language in which the service is used." + }, + "expiration": { + "fi": "1826 päivää", + "sv": "1826 dagar", + "en": "1826 days" + } + }, { "name": "VISITOR_INFO1_LIVE", "host": "youtube.com", @@ -325,8 +307,8 @@ "storageType": 1, "description": { "fi": "Googlen eväste tallentaa kävijän evästehyväskynnän.", - "sv": "Används av Google för att lagra inställningar för användarens samtycke", - "en": "Used by Google to store user consent preferences" + "sv": "Används av Google för att lagra inställningar för användarens samtycke.", + "en": "Used by Google to store user consent preferences." }, "expiration": { "fi": "5947 päivää, 15 tuntia", @@ -386,7 +368,7 @@ "description": { "fi": "Matomo-tilastointijärjestelmän eväste.", "sv": "Matomo-statistiksystemets kaka samlar information om hur webbplatsen används.", - "en": "Matomo Analytics - used to store a few details about the user such as the unique visitor ID" + "en": "Matomo Analytics - short lived cookies used to temporarily store data for the visit" }, "expiration": { "fi": "1 tunti", @@ -416,7 +398,7 @@ "description": { "fi": "Matomo-tilastointijärjestelmän eväste.", "sv": "Matomo-statistiksystemets kaka samlar information om hur webbplatsen används.", - "en": "Matomo Analytics - used to store a few details about the user such as the unique visitor ID" + "en": "Matomo Analytics - short lived cookies used to temporarily store data for the visit" }, "expiration": { "fi": "1 tunti", @@ -446,8 +428,27 @@ { "name": "helfi_accordions_open", "storageType": 1 + }, + { + "name": "cookiehub", + "storageType": 1 + }, + { + "name": "cookie-agreed-version", + "storageType": 1 + }, + { + "name": "cookie-agreed-categories", + "storageType": 1 + }, + { + "name": "cookie-agreed", + "storageType": 1 } ], + "groupsWhitelistedForApi": [ + "chat" + ], "translations": { "bannerAriaLabel": { "fi": "Evästeasetukset", @@ -455,9 +456,9 @@ "en": "Cookie settings" }, "heading": { - "fi": "{{siteName}} käyttää evästeitä", - "sv": "{{siteName}} använder kakor", - "en": "{{siteName}} uses cookies" + "fi": "Evästeet {{siteName}}-sivustolla", + "sv": "Kakor på webbplatsen {{siteName}}", + "en": "Cookies on {{siteName}}" }, "description": { "fi": "Tämä sivusto käyttää välttämättömiä evästeitä sivun perustoimintojen ja suorituskyvyn varmistamiseksi. Lisäksi käytämme kohdennusevästeitä käyttäjäkokemuksen parantamiseksi, analytiikkaan ja yksilöidyn sisällön näyttämiseen.", diff --git a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php index c6a43e3c1..7cdb927b0 100644 --- a/modules/hdbt_cookie_banner/src/Services/CookieSettings.php +++ b/modules/hdbt_cookie_banner/src/Services/CookieSettings.php @@ -4,6 +4,8 @@ namespace Drupal\hdbt_cookie_banner\Services; +use Drupal\Core\Language\LanguageInterface; +use Drupal\helfi_api_base\Environment\Environment; use Drupal\Core\Asset\LibraryDiscoveryInterface; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Language\LanguageManagerInterface; @@ -37,7 +39,37 @@ public function __construct( * @return \Drupal\Core\Url|null * The URL of the cookie settings page. */ - public function getCookieSettingsPageUrl(): ?Url { + public function getCookieSettingsPageUrl(?string $langcode = NULL): ?Url { + if (!$langcode) { + $langcode = $this->languageManager + ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT) + ->getId(); + } + + // Default to Etusivu cookie settings page. + if (!$this->useCustomSettings()) { + $environment = $this->getActiveEtusivuEnvironment(); + + if ($environment instanceof Environment) { + try { + $url = $environment->getUrl($langcode); + } + catch (\InvalidArgumentException) { + // Fallback to default language. + $langcode = $this->languageManager->getDefaultLanguage()->getId(); + $url = $environment->getUrl($langcode); + } + + $path = match($langcode) { + 'fi' => 'evasteasetukset', + 'sv' => 'cookie-installningar', + default => 'cookie-settings', + }; + + return Url::fromUri(vsprintf("%s/%s", [$url, $path])); + } + } + $route_name = 'hdbt_cookie_banner.cookie_settings_page'; try { // Check if the cookie settings page route exists. @@ -58,24 +90,19 @@ public function getCookieSettingsPageUrl(): ?Url { * Cookie banner API URL as a string. */ public function getCookieBannerApiUrl(): string { - $config = $this->configFactory->get(HdbtCookieBannerForm::SETTINGS); $language = $this->languageManager->getDefaultLanguage(); // Default to Etusivu API URL. - if (!$config->get('use_custom_settings')) { - try { - $environment = $this->environmentResolver->getEnvironment( - Project::ETUSIVU, - $this->environmentResolver->getActiveEnvironmentName() - ); + if (!$this->useCustomSettings()) { + $environment = $this->getActiveEtusivuEnvironment(); + if ($environment instanceof Environment) { return vsprintf("%s/api/cookie-banner", [ $environment->getUrl($language->getId()), ]); } - catch (\InvalidArgumentException) { - } } + return $this->urlGenerator->generateFromRoute( 'hdbt_cookie_banner.site_settings', options: ['language' => $language], @@ -94,19 +121,8 @@ public function injectBannerJavaScript(array &$attachments, ?string $library = N // Load HDS cookie consent JavaScript file from Etusivu instance. if (!$library) { - // Get active Etusivu environment. - try { - $environment = $this->environmentResolver->getEnvironment( - Project::ETUSIVU, - $this->environmentResolver->getActiveEnvironmentName() - ); - } - catch (\InvalidArgumentException) { - $environment = $this->environmentResolver->getEnvironment( - Project::ETUSIVU, - EnvironmentEnum::Prod->value - ); - } + // Get the active Etusivu environment, default to production. + $environment = $this->getActiveEtusivuEnvironment(TRUE); // Construct the URL to the HDS cookie consent JS file. $library = vsprintf("%s/etusivu-assets/%s/assets/js/hds-cookie-consent.min.js%s", [ @@ -152,4 +168,48 @@ protected function getCookieLibraryVersion(): string { return ''; } + /** + * Checks if current drupal instance uses custom settings. + * + * If not, the default settings are used and all information is retrieved + * from "hel.fi" drupal instance. + * + * @return bool + * Returns true if custom settings are used. + */ + protected function useCustomSettings(): bool { + $config = $this->configFactory->get(HdbtCookieBannerForm::SETTINGS); + return (bool) $config->get('use_custom_settings'); + } + + /** + * Get the active Etusivu environment if available. + * + * @param bool $default_to_production + * Should the Etusivu production be used? + * + * @return \Drupal\helfi_api_base\Environment\Environment|null + * Returns the active Etusivu environment or NULL. + */ + protected function getActiveEtusivuEnvironment(?bool $default_to_production = FALSE): Environment|NULL { + $environment = 'NULL'; + + // Get active Etusivu environment. + try { + $environment = $this->environmentResolver->getEnvironment( + Project::ETUSIVU, + $this->environmentResolver->getActiveEnvironmentName() + ); + } + catch (\InvalidArgumentException) { + if ($default_to_production) { + $environment = $this->environmentResolver->getEnvironment( + Project::ETUSIVU, + EnvironmentEnum::Prod->value + ); + } + } + return $environment; + } + } diff --git a/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php b/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php index 44e5ca8a9..9db9e40a0 100644 --- a/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php +++ b/modules/hdbt_cookie_banner/tests/src/Kernel/KernelTestBase.php @@ -101,7 +101,7 @@ protected function setUp(): void { $mockEnvironment = new Environment( new Address('www.test.hel.ninja'), new Address('internal-address.local', 'http', 8080), - ['en' => '/en'], + ['en' => '/en', 'fi' => '/fi', 'sv' => '/sv'], EnvironmentEnum::Test, [], ); @@ -142,7 +142,7 @@ protected function setUpTheConfigurations(array $configuration): void { $immutableConfig->method('get')->willReturnMap($configuration); // Only mock the 'HdbtCookieBannerForm::SETTINGS' configuration. - $this->configFactory->expects($this->once()) + $this->configFactory->expects($this->atLeastOnce()) ->method('get') ->with(HdbtCookieBannerForm::SETTINGS) ->willReturn($immutableConfig); diff --git a/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php b/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php index 92a055d45..b5e527c57 100644 --- a/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php +++ b/modules/hdbt_cookie_banner/tests/src/Kernel/Services/CookieSettingsTest.php @@ -10,7 +10,6 @@ use Drupal\hdbt_cookie_banner\Services\CookieSettings; use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Routing\Exception\RouteNotFoundException; -use Symfony\Component\Routing\Route; /** * Tests the CookieSettings service. @@ -33,6 +32,13 @@ class CookieSettingsTest extends KernelTestBase { */ protected LanguageInterface|MockObject $language; + /** + * An array of mock LanguageInterface objects. + * + * @var array + */ + protected array $languages; + /** * {@inheritdoc} */ @@ -49,14 +55,46 @@ protected function setUp(): void { $this->container->get('library.discovery'), ); - $this->language = $this->createMock(LanguageInterface::class); - $this->language->expects($this->any()) - ->method('getId') - ->willReturn('en'); + $this->languages = $this->setUpLanguages(); $this->languageManager->expects($this->any()) ->method('getDefaultLanguage') - ->willReturn($this->language); + ->willReturn($this->languages['en']); + $this->languageManager->expects($this->any()) + ->method('getCurrentLanguage') + ->withAnyParameters() + ->willReturn($this->languages['en']); + } + + /** + * Sets up mock LanguageInterface objects. + * + * @return array + * An array of mock LanguageInterface objects. + */ + protected function setUpLanguages(): array { + $language_fi = $this->createMock(LanguageInterface::class); + $language_fi->expects($this->any()) + ->method('getId') + ->willReturn('fi'); + $language_sv = $this->createMock(LanguageInterface::class); + $language_sv->expects($this->any()) + ->method('getId') + ->willReturn('sv'); + $language_en = $this->createMock(LanguageInterface::class); + $language_en->expects($this->any()) + ->method('getId') + ->willReturn('en'); + $language_it = $this->createMock(LanguageInterface::class); + $language_it->expects($this->any()) + ->method('getId') + ->willReturn('it'); + return [ + 'fi' => $language_fi, + 'sv' => $language_sv, + 'en' => $language_en, + 'it' => $language_it, + ]; } /** @@ -96,7 +134,7 @@ public function testGetCookieBannerApiUrlWithCustomSettings(): void { ->with( 'hdbt_cookie_banner.site_settings', [], - ['language' => $this->language], + ['language' => $this->languages['en']], ) ->willReturn('/en/api/cookie-banner'); @@ -140,27 +178,52 @@ public function testInjectBannerJavaScriptWithLibrary(): void { } /** - * Tests getCookieSettingsPageUrl when the route exists. + * Tests getCookieBannerApiUrl with custom settings. */ - public function testGetCookieSettingsPageUrlRouteExists(): void { - $route_name = 'hdbt_cookie_banner.cookie_settings_page'; + public function testGetCookieSettingsPage(): void { + // Expected settings for external (hel.fi) setup. + $expected = [ + ['site_settings', '{"test": "true"}'], + ['use_custom_settings', FALSE], + ]; - // Simulate that the route exists by not throwing an exception. - $this->routeProvider->expects($this->once()) - ->method('getRouteByName') - ->with($route_name) - ->willReturn($this->createMock(Route::class)); + // Set up the configurations with specified settings. + $this->setUpTheConfigurations($expected); - // Test that the URL is returned correctly. - $url = $this->cookieSettings->getCookieSettingsPageUrl(); - $this->assertInstanceOf(Url::class, $url); - $this->assertEquals($route_name, $url->getRouteName()); + $language_map = [ + 'en' => 'https://www.test.hel.ninja/en/cookie-settings', + 'fi' => 'https://www.test.hel.ninja/fi/evasteasetukset', + 'sv' => 'https://www.test.hel.ninja/sv/cookie-installningar', + 'it' => 'https://www.test.hel.ninja/en/cookie-settings', + ]; + + foreach ($language_map as $langcode => $mock_url) { + $return_value = match($langcode) { + 'fi' => 'fi', + 'sv' => 'sv', + default => 'en', + }; + + $this->languages[$langcode]->expects($this->any())->method('getId')->willReturn($return_value); + + // Test that the URL is returned correctly. + $url = $this->cookieSettings->getCookieSettingsPageUrl($langcode); + $this->assertInstanceOf(Url::class, $url); + } } /** * Tests getCookieSettingsPageUrl when the route does not exist. */ public function testGetCookieSettingsPageUrlRouteNotExists(): void { + // Expected settings for external (hel.fi) setup. + $expected = [ + ['use_custom_settings', TRUE], + ]; + + // Set up the configurations with specified settings. + $this->setUpTheConfigurations($expected); + $route_name = 'hdbt_cookie_banner.cookie_settings_page'; // Simulate that the route does not exist by throwing an exception.