Author: Maurício Meneghini Fauth (MauricioFauth)
Committer: GitHub (web-flow)
Pusher: saundefined
Date: 2024-11-14T11:37:00+03:00

Commit: 
https://github.com/php/web-php/commit/cdf59074d31ce7cdc8cb03e910fdc3311eb6879a
Raw diff: 
https://github.com/php/web-php/commit/cdf59074d31ce7cdc8cb03e910fdc3311eb6879a.diff

Replace languages.inc globals with I18n\Languages consts (#1121)

The include/languages.inc file was not removed as it's used in other
repositories. It should be removed after migration.

Tests were added to ensure that the global variables and the constants
are in sync with each other.

Signed-off-by: Maurício Meneghini Fauth <mauri...@mfauth.net>

Changed paths:
  A  src/I18n/Languages.php
  A  tests/Unit/I18n/LanguagesTest.php
  M  docs.php
  M  download-docs.php
  M  error.php
  M  include/errors.inc
  M  include/langchooser.inc
  M  include/languages.inc
  M  include/layout.inc
  M  include/shared-manual.inc
  M  include/site.inc
  M  js/search-index.php
  M  manual/help-translate.php
  M  mirror.php
  M  my.php


Diff:

diff --git a/docs.php b/docs.php
index 04dd131079..3119d5bf7d 100644
--- a/docs.php
+++ b/docs.php
@@ -1,4 +1,7 @@
 <?php
+
+use phpweb\I18n\Languages;
+
 $_SERVER['BASE_PAGE'] = 'docs.php';
 include_once __DIR__ . '/include/prepend.inc';
 
@@ -27,19 +30,19 @@
 <?php
 
 // List all manual languages viewable online
-$lastlang = end($ACTIVE_ONLINE_LANGUAGES);
-foreach ($ACTIVE_ONLINE_LANGUAGES as $langcode => $langname) {
+$lastlang = array_key_last(Languages::ACTIVE_ONLINE_LANGUAGES);
+foreach (Languages::ACTIVE_ONLINE_LANGUAGES as $langcode => $langname) {
     if (!file_exists($_SERVER["DOCUMENT_ROOT"] . 
"/manual/{$langcode}/index.php")) {
         continue;
     }
 
     // Make preferred language bold
-    if ($langcode == $LANG) { echo "<strong>"; }
+    if ($langcode === $LANG) { echo "<strong>"; }
 
     echo '<a href="/manual/' . $langcode . '/">' . $langname . '</a>';
-    echo ($lastlang != $langname) ? ",\n" : "\n";
+    echo ($lastlang !== $langcode) ? ",\n" : "\n";
 
-    if ($langcode == $LANG) { echo "</strong>"; }
+    if ($langcode === $LANG) { echo "</strong>"; }
 }
 
 ?>
diff --git a/download-docs.php b/download-docs.php
index 0d31fd10fa..9abfc80f52 100644
--- a/download-docs.php
+++ b/download-docs.php
@@ -1,9 +1,12 @@
 <?php
+
+use phpweb\I18n\Languages;
+
 $_SERVER['BASE_PAGE'] = 'download-docs.php';
 include_once __DIR__ . '/include/prepend.inc';
 
 if (!empty($_GET['active_langs'])) {
-    echo serialize($ACTIVE_ONLINE_LANGUAGES);
+    echo serialize(Languages::ACTIVE_ONLINE_LANGUAGES);
     exit;
 }
 
@@ -90,8 +93,8 @@
 $filepath = $filename = '';
 
 // Go through all possible manual languages
-foreach ($LANGUAGES as $langcode => $language) {
-    if (isset($INACTIVE_ONLINE_LANGUAGES[$langcode]) && $MYSITE !== 
'http://docs.php.net/') {
+foreach (Languages::LANGUAGES as $langcode => $language) {
+    if (isset(Languages::INACTIVE_ONLINE_LANGUAGES[$langcode]) && $MYSITE !== 
'http://docs.php.net/') {
        continue;
     }
 
@@ -180,7 +183,7 @@
             $cellclass = "";
         }
 
-        echo "<tr>\n<th class=\"subl\">" . $LANGUAGES[$langcode] . "</th>\n";
+        echo "<tr>\n<th class=\"subl\">" . Languages::LANGUAGES[$langcode] . 
"</th>\n";
 
         foreach ($formats as $formatname => $extension) {
 
diff --git a/error.php b/error.php
index 2801188f14..423135a29e 100644
--- a/error.php
+++ b/error.php
@@ -9,11 +9,11 @@
 
 */
 
+use phpweb\I18n\Languages;
 use phpweb\UserPreferences;
 
 // Ensure that our environment is set up
 include_once __DIR__ . '/include/prepend.inc';
-include_once __DIR__ . '/include/languages.inc';
 include_once __DIR__ . '/include/errors.inc';
 
 // Get URI for this request, strip leading slash
@@ -79,7 +79,7 @@
 //     default language manual accessibility on mirror sites through 
/manual/filename)
 // @todo do we rely on this? how about removing it...
 if (preg_match("!^manual/([^/]*)$!", $URI, $array)) {
-    if (!isset($INACTIVE_ONLINE_LANGUAGES[$array[1]])) {
+    if (!isset(Languages::INACTIVE_ONLINE_LANGUAGES[$array[1]])) {
         mirror_redirect("/manual/$LANG/$array[1]");
     }
 } elseif (preg_match("!^manual/html/([^/]+)$!", $URI, $array)) {
@@ -705,10 +705,10 @@
 // ============================================================================
 // For manual pages for inactive languages, point visitors to the English page
 if (preg_match("!^manual/([^/]+)/([^/]+).php$!", $URI, $match) &&
-    isset($INACTIVE_ONLINE_LANGUAGES[$match[1]])) {
+    isset(Languages::INACTIVE_ONLINE_LANGUAGES[$match[1]])) {
     $try = find_manual_page("en", $match[2]);
     if ($try) {
-        error_inactive_manual_page($INACTIVE_ONLINE_LANGUAGES[$match[1]], 
$try);
+        
error_inactive_manual_page(Languages::INACTIVE_ONLINE_LANGUAGES[$match[1]], 
$try);
     }
 }
 
diff --git a/include/errors.inc b/include/errors.inc
index 17fd869123..76637c2dad 100644
--- a/include/errors.inc
+++ b/include/errors.inc
@@ -5,6 +5,8 @@
   not available.
 */
 
+use phpweb\I18n\Languages;
+
 // A 'good looking' 404 error message page
 function error_404(): void
 {
@@ -37,7 +39,7 @@ function error_404_manual(): void
 // An error message page for manual pages from inactive languages
 function error_inactive_manual_page($lang_name, $en_page): void
 {
-    global $MYSITE, $ACTIVE_ONLINE_LANGUAGES;
+    global $MYSITE;
     status_header(404);
     site_header('Page gone', ["noindex"]);
     echo "<h1>Page gone</h1>\n" .
@@ -48,7 +50,7 @@ function error_inactive_manual_page($lang_name, $en_page): 
void
     echo "<p>The English page is available at <a 
href=\"{$en_url}\">{$en_url}</a></p>\n";
     echo "<p>Several other languages are also available:</p>\n";
     echo "<ul>\n";
-    foreach ($ACTIVE_ONLINE_LANGUAGES as $alt_lang => $alt_lang_name) {
+    foreach (Languages::ACTIVE_ONLINE_LANGUAGES as $alt_lang => 
$alt_lang_name) {
         if ($alt_lang === "en") {
             continue;
         }
diff --git a/include/langchooser.inc b/include/langchooser.inc
index 61def940f8..f46498a363 100644
--- a/include/langchooser.inc
+++ b/include/langchooser.inc
@@ -28,6 +28,7 @@
 
 */
 
+use phpweb\I18n\Languages;
 use phpweb\LangChooser;
 
 require_once __DIR__ . '/../src/autoload.php';
@@ -37,7 +38,7 @@ $_SERVER['STRIPPED_URI'] = 
htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES,
 
 // The code is encapsulated in a function,
 // so the variable namespace is not polluted
-list($LANG, $EXPL_LANG) = (new LangChooser($LANGUAGES, 
$INACTIVE_ONLINE_LANGUAGES, $userPreferences->languageCode, default_language() 
?: ''))->chooseCode(
+list($LANG, $EXPL_LANG) = (new LangChooser(Languages::LANGUAGES, 
Languages::INACTIVE_ONLINE_LANGUAGES, $userPreferences->languageCode, 
default_language() ?: ''))->chooseCode(
     $_REQUEST['lang'] ?? null,
     $_SERVER['REQUEST_URI'],
     $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null,
diff --git a/include/languages.inc b/include/languages.inc
index e197263716..84e97b8c20 100644
--- a/include/languages.inc
+++ b/include/languages.inc
@@ -1,9 +1,9 @@
 <?php
+/**
+ * This file is deprecated, and it exists for backward compatibility purposes 
only.
+ * It must be kept in sync with {@see \phpweb\I18n\Languages}.
+ */
 
-/*
- This is a list of all manual languages hosted
- within PHP Git repositories (https://github.com/php/doc-{lang})
-*/
 $LANGUAGES = [
     'en' => 'English',
     'de' => 'German',
@@ -20,32 +20,9 @@ $LANGUAGES = [
     'zh' => 'Chinese (Simplified)',
 ];
 
-/*
- The following languages are inactive, which means they will not:
- - Show up via the language select box at php.net
- - Be selectable via my.php
- - Accept redirections to the translation, despite ACCEPT_LANGUAGE
- - Be listed at php.net/docs or php.net/download-docs
- However, translation status for these languages is available at:
- - https://doc.php.net/
-*/
 $INACTIVE_ONLINE_LANGUAGES = [
     'pl' => 'Polish',
     'ro' => 'Romanian',
 ];
 
 $ACTIVE_ONLINE_LANGUAGES = array_diff($LANGUAGES, $INACTIVE_ONLINE_LANGUAGES);
-
-// Convert between language codes back and forth
-// [We use non-standard languages codes and so conversion
-// is needed when communicating with the outside world]
-function language_convert(string $langcode): string
-{
-    global $LANGUAGES;
-    switch ($langcode) {
-        case 'zh_cn': return 'zh';
-        default:
-            // Fallback on english if we got something wacky
-            return array_key_exists($langcode, $LANGUAGES) ? $langcode : 'en';
-    }
-}
diff --git a/include/layout.inc b/include/layout.inc
index 5174395e40..86969807e7 100644
--- a/include/layout.inc
+++ b/include/layout.inc
@@ -1,5 +1,6 @@
 <?php
 
+use phpweb\I18n\Languages;
 use phpweb\Navigation\NavItem;
 
 $_SERVER['STATIC_ROOT'] = $MYSITE;
@@ -463,7 +464,7 @@ META
 
     $config["headsup"] = get_news_changes();
 
-    $lang = language_convert($config["lang"]);
+    $lang = (new Languages())->convert($config["lang"]);
     $curr = $config["current"];
     $classes = $config['classes'];
 
diff --git a/include/shared-manual.inc b/include/shared-manual.inc
index 8610f112fc..eb0437e278 100644
--- a/include/shared-manual.inc
+++ b/include/shared-manual.inc
@@ -22,6 +22,7 @@ $PGI = []; $SIDEBAR_DATA = '';
 // User note display functions
 // 
=============================================================================
 
+use phpweb\I18n\Languages;
 use phpweb\UserNotes\Sorter;
 use phpweb\UserNotes\UserNote;
 
@@ -271,7 +272,6 @@ function manual_navigation_methodname($methodname) {
 // including HTTP header information
 function manual_setup($setup): void {
     global $PGI, $MYSITE, $USERNOTES;
-    global $ACTIVE_ONLINE_LANGUAGES;
 
     //TODO: get rid of this hack to get the related items into manual_footer
     global $__RELATED;
@@ -281,7 +281,7 @@ function manual_setup($setup): void {
     }
     $PGI = $setup;
     // Set base href for this manual page
-    $base = 'manual/' . language_convert($setup['head'][1]) . "/";
+    $base = 'manual/' . (new Languages())->convert($setup['head'][1]) . "/";
     $_SERVER['BASE_PAGE'] = $base . $setup['this'][0];
     $_SERVER['BASE_HREF'] = $MYSITE . $_SERVER['BASE_PAGE'];
 
@@ -313,7 +313,7 @@ function manual_setup($setup): void {
     $config = [
         "current" => "docs",
         "breadcrumbs" => $breadcrumbs,
-        "languages" => array_keys($ACTIVE_ONLINE_LANGUAGES),
+        "languages" => array_keys(Languages::ACTIVE_ONLINE_LANGUAGES),
         "meta-navigation" => [
             "contents" => $base . $setup["home"][0],
             "index" => $base . $setup["up"][0],
@@ -340,12 +340,12 @@ PAGE_TOOLS;
 }
 
 function manual_language_chooser($currentlang, $currentpage) {
-    global $ACTIVE_ONLINE_LANGUAGES, $LANG;
+    global $LANG;
 
     // Prepare the form with all the options
     $othersel = ' selected="selected"';
     $out = [];
-    foreach ($ACTIVE_ONLINE_LANGUAGES as $lang => $text) {
+    foreach (Languages::ACTIVE_ONLINE_LANGUAGES as $lang => $text) {
         $selected = '';
         if ($lang == $currentlang) {
             $selected = ' selected="selected"';
diff --git a/include/site.inc b/include/site.inc
index 50877ecbfa..2aa9c4a593 100644
--- a/include/site.inc
+++ b/include/site.inc
@@ -1,5 +1,7 @@
 <?php
 
+use phpweb\I18n\Languages;
+
 // Define some constants, and $MIRRORS array
 // Mirror type constants
 const MIRROR_DOWNLOAD = 0;
@@ -31,9 +33,6 @@ $MIRRORS = [
  */
 $COUNTRIES = include __DIR__ . '/countries.inc';
 
-// Define $LANGUAGES array
-include __DIR__ . '/languages.inc';
-
 // Returns true if the current (or specified)
 // site is the primary mirror site
 function is_primary_site($site = false)
@@ -261,14 +260,14 @@ if (!isset($MIRRORS[$MYSITE])) {
 
 // Override mirror language with local preference
 if (isset($_SERVER['MIRROR_LANGUAGE'])) {
-    if (isset($LANGUAGES[$_SERVER['MIRROR_LANGUAGE']])) {
+    if (isset(Languages::LANGUAGES[$_SERVER['MIRROR_LANGUAGE']])) {
         $MIRRORS[$MYSITE][6] = $_SERVER['MIRROR_LANGUAGE'];
     }
 }
 
 // Fallback to English in case the language
 // set is definitely not supported
-if (!isset($LANGUAGES[$MIRRORS[$MYSITE][6]])) {
+if (!isset(Languages::LANGUAGES[$MIRRORS[$MYSITE][6]])) {
     $MIRRORS[$MYSITE][6] = "en";
 }
 
diff --git a/js/search-index.php b/js/search-index.php
index 6fb15b3cb3..7d2f50193d 100644
--- a/js/search-index.php
+++ b/js/search-index.php
@@ -1,5 +1,7 @@
 <?php
 
+use phpweb\I18n\Languages;
+
 $_GET["lang"] = "en";
 if (!isset($_GET["lang"])) {
     header("Location: http://php.net";);
@@ -9,7 +11,7 @@
     $_SERVER["DOCUMENT_ROOT"] = __DIR__ . "/../";
 }
 include __DIR__ . '/../include/prepend.inc';
-if (!isset($ACTIVE_ONLINE_LANGUAGES[$_GET["lang"]])) {
+if (!isset(Languages::ACTIVE_ONLINE_LANGUAGES[$_GET["lang"]])) {
     header("Location: http://php.net";);
 }
 $lang = $_GET["lang"];
diff --git a/manual/help-translate.php b/manual/help-translate.php
index ab8b5c051e..df69f428da 100644
--- a/manual/help-translate.php
+++ b/manual/help-translate.php
@@ -1,4 +1,7 @@
 <?php
+
+use phpweb\I18n\Languages;
+
 $_SERVER['BASE_PAGE'] = 'manual/help-translate.php';
 include_once __DIR__ . '/../include/prepend.inc';
 include_once __DIR__ . '/../include/shared-manual.inc';
@@ -26,7 +29,7 @@
 // $archived are manuals we have old versions of
 $archived = ['da', 'kr', 'pl', 'tw'];
 
-foreach ($INACTIVE_ONLINE_LANGUAGES as $cc => $lang) {
+foreach (Languages::INACTIVE_ONLINE_LANGUAGES as $cc => $lang) {
     $link = 'no archive';
     if (in_array($cc, $archived, true)) {
         $link = '<a href="http://docs.php.net/manual/' . $cc . '">archive</a>';
diff --git a/mirror.php b/mirror.php
index ea1c397d62..4b6c40dd2a 100644
--- a/mirror.php
+++ b/mirror.php
@@ -1,4 +1,7 @@
 <?php
+
+use phpweb\I18n\Languages;
+
 $_SERVER['BASE_PAGE'] = 'mirror.php';
 include_once __DIR__ . '/include/prepend.inc';
 $SIDEBAR_DATA = '
@@ -84,7 +87,7 @@
 <h2>Mirror Services</h2>
 
 <ul>
- <li>Default language is <?php echo $LANGUAGES[default_language()]; ?></li>
+ <li>Default language is <?php echo Languages::LANGUAGES[default_language()]; 
?></li>
 </ul>
 
 <h2>Mirror Status</h2>
diff --git a/my.php b/my.php
index 8ad08ded48..1fdb9d2824 100644
--- a/my.php
+++ b/my.php
@@ -1,5 +1,6 @@
 <?php
 
+use phpweb\I18n\Languages;
 use phpweb\UserPreferences;
 
 $_SERVER['BASE_PAGE'] = 'my.php';
@@ -9,7 +10,7 @@
 header_nocache();
 
 // Languages array copy and options to list
-$langs = $ACTIVE_ONLINE_LANGUAGES;
+$langs = Languages::ACTIVE_ONLINE_LANGUAGES;
 $options = [];
 
 // We have post data, and it is an available language
diff --git a/src/I18n/Languages.php b/src/I18n/Languages.php
new file mode 100644
index 0000000000..a74fc65469
--- /dev/null
+++ b/src/I18n/Languages.php
@@ -0,0 +1,74 @@
+<?php
+
+declare(strict_types=1);
+
+namespace phpweb\I18n;
+
+use function array_key_exists;
+
+final class Languages
+{
+    /**
+     * This is a list of all manual languages hosted
+     * within PHP Git repositories (https://github.com/php/doc-{lang})
+     */
+    public const LANGUAGES = [
+        'en' => 'English',
+        'de' => 'German',
+        'es' => 'Spanish',
+        'fr' => 'French',
+        'it' => 'Italian',
+        'ja' => 'Japanese',
+        'pl' => 'Polish',
+        'pt_BR' => 'Brazilian Portuguese',
+        'ro' => 'Romanian',
+        'ru' => 'Russian',
+        'tr' => 'Turkish',
+        'uk' => 'Ukrainian',
+        'zh' => 'Chinese (Simplified)',
+    ];
+
+    /**
+     * The following languages are inactive, which means they will not:
+     * - Show up via the language select box at php.net
+     * - Be selectable via my.php
+     * - Accept redirections to the translation, despite ACCEPT_LANGUAGE
+     * - Be listed at php.net/docs or php.net/download-docs
+     * However, translation status for these languages is available at:
+     * - https://doc.php.net/
+     */
+    public const INACTIVE_ONLINE_LANGUAGES = [
+        'pl' => 'Polish',
+        'ro' => 'Romanian',
+    ];
+
+    public const ACTIVE_ONLINE_LANGUAGES = [
+        'en' => 'English',
+        'de' => 'German',
+        'es' => 'Spanish',
+        'fr' => 'French',
+        'it' => 'Italian',
+        'ja' => 'Japanese',
+        'pt_BR' => 'Brazilian Portuguese',
+        'ru' => 'Russian',
+        'tr' => 'Turkish',
+        'uk' => 'Ukrainian',
+        'zh' => 'Chinese (Simplified)',
+    ];
+
+    /**
+     * Convert between language codes back and forth
+     *
+     * Uses non-standard languages codes and so conversion is needed when 
communicating with the outside world.
+     *
+     * Fall back to English if the language is not available.
+     */
+    public function convert(string $languageCode): string
+    {
+        return match ($languageCode) {
+            'zh_cn', 'zh_CN' => 'zh',
+            'pt_br', 'pt_BR' => 'pt_BR',
+            default => array_key_exists($languageCode, self::LANGUAGES) ? 
$languageCode : 'en',
+        };
+    }
+}
diff --git a/tests/Unit/I18n/LanguagesTest.php 
b/tests/Unit/I18n/LanguagesTest.php
new file mode 100644
index 0000000000..c1eeacd728
--- /dev/null
+++ b/tests/Unit/I18n/LanguagesTest.php
@@ -0,0 +1,63 @@
+<?php
+
+declare(strict_types=1);
+
+namespace phpweb\Test\Unit\I18n;
+
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\TestCase;
+use phpweb\I18n\Languages;
+
+use function array_diff;
+
+#[CoversClass(Languages::class)]
+final class LanguagesTest extends TestCase
+{
+    #[DataProvider('languageCodeProvider')]
+    public function testConvert(string $languageCode, string $expected): void
+    {
+        self::assertSame($expected, (new Languages())->convert($languageCode));
+    }
+
+    public static function languageCodeProvider(): iterable
+    {
+        yield ['en', 'en'];
+        yield ['de', 'de'];
+        yield ['es', 'es'];
+        yield ['fr', 'fr'];
+        yield ['it', 'it'];
+        yield ['ja', 'ja'];
+        yield ['pl', 'pl'];
+        yield ['pt_br', 'pt_BR'];
+        yield ['pt_BR', 'pt_BR'];
+        yield ['ro', 'ro'];
+        yield ['ru', 'ru'];
+        yield ['tr', 'tr'];
+        yield ['uk', 'uk'];
+        yield ['zh', 'zh'];
+        yield ['zh_cn', 'zh'];
+        yield ['zh_CN', 'zh'];
+        yield ['unknown', 'en'];
+        yield ['', 'en'];
+    }
+
+    public function testConstantsDifference(): void
+    {
+        self::assertSame(
+            array_diff(Languages::LANGUAGES, 
Languages::INACTIVE_ONLINE_LANGUAGES),
+            Languages::ACTIVE_ONLINE_LANGUAGES,
+        );
+    }
+
+    public function testLanguagesIncGlobalVariables(): void
+    {
+        global $LANGUAGES, $INACTIVE_ONLINE_LANGUAGES, 
$ACTIVE_ONLINE_LANGUAGES;
+
+        include __DIR__ . '/../../../include/languages.inc';
+
+        self::assertSame(Languages::LANGUAGES, $LANGUAGES);
+        self::assertSame(Languages::INACTIVE_ONLINE_LANGUAGES, 
$INACTIVE_ONLINE_LANGUAGES);
+        self::assertSame(Languages::ACTIVE_ONLINE_LANGUAGES, 
$ACTIVE_ONLINE_LANGUAGES);
+    }
+}

Reply via email to