From eb024a3718a47aa596abfab4e611d5532eea8d2a Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 9 Jul 2019 21:44:02 +0200 Subject: [PATCH 1/2] Refactor L10n for testing - Moving L10n to L10n\L10n - Adding constructor information - Adding to factory - simplify/speedup tests --- src/App.php | 34 +- src/Core/L10n.php | 311 +------------ src/Core/L10n/L10n.php | 426 ++++++++++++++++++ src/Factory/DependencyFactory.php | 6 +- src/Module/Register.php | 4 +- tests/Util/L10nMockTrait.php | 46 -- tests/include/ApiTest.php | 6 +- .../AutomaticInstallationConsoleTest.php | 9 +- tests/src/Content/SmiliesTest.php | 136 +++--- tests/src/Content/Text/BBCodeTest.php | 13 +- tests/src/Core/InstallerTest.php | 42 +- tests/src/Database/DBATest.php | 6 +- tests/src/Database/DBStructureTest.php | 7 +- 13 files changed, 596 insertions(+), 450 deletions(-) create mode 100644 src/Core/L10n/L10n.php delete mode 100644 tests/Util/L10nMockTrait.php diff --git a/src/App.php b/src/App.php index 8b2d50512b..4def7fefa0 100644 --- a/src/App.php +++ b/src/App.php @@ -11,6 +11,7 @@ use Exception; use Friendica\Core\Config\Cache\ConfigCache; use Friendica\Core\Config\Configuration; use Friendica\Core\Hook; +use Friendica\Core\L10n\L10n; use Friendica\Core\Theme; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -128,6 +129,11 @@ class App */ private $database; + /** + * @var L10n The translator + */ + private $l10n; + /** * Returns the current config cache of this node * @@ -207,6 +213,14 @@ class App return $this->database; } + /** + * @return L10n + */ + public function getL10n() + { + return $this->l10n; + } + /** * Register a stylesheet file path to be included in the tag of every page. * Inclusion is done in App->initHead(). @@ -253,11 +267,12 @@ class App * @param BaseURL $baseURL The full base URL of this Friendica app * @param LoggerInterface $logger The current app logger * @param Profiler $profiler The profiler of this application + * @param L10n $l10n The translator instance * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend) * * @throws Exception if the Basepath is not usable */ - public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, $isBackend = true) + public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, $isBackend = true) { BaseObject::setApp($this); @@ -268,6 +283,7 @@ class App $this->baseURL = $baseURL; $this->profiler = $profiler; $this->logger = $logger; + $this->l10n = $l10n; $this->profiler->reset(); @@ -373,8 +389,6 @@ class App } $this->loadDefaultTimezone(); - - Core\L10n::init(); } /** @@ -518,7 +532,7 @@ class App $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [ '$local_user' => local_user(), '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION, - '$delitem' => Core\L10n::t('Delete this item?'), + '$delitem' => $this->l10n->t('Delete this item?'), '$update_interval' => $interval, '$shortcut_icon' => $shortcut_icon, '$touch_icon' => $touch_icon, @@ -560,7 +574,7 @@ class App } $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [ '$toggle_link' => $link, - '$toggle_text' => Core\L10n::t('toggle mobile') + '$toggle_text' => $this->l10n->t('toggle mobile') ]); } @@ -876,7 +890,7 @@ class App { $system_theme = $this->config->get('system', 'theme'); if (!$system_theme) { - throw new Exception(Core\L10n::t('No system theme config value set.')); + throw new Exception($this->l10n->t('No system theme config value set.')); } // Sane default @@ -1026,8 +1040,8 @@ class App $stamp1 = microtime(true); session_start(); $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack()); - Core\L10n::setSessionVariable(); - Core\L10n::setLangFromSession(); + $this->l10n->setSessionVariable(); + $this->l10n->setLangFromSession(); } else { $_SESSION = []; Core\Worker::executeIfIdle(); @@ -1171,7 +1185,7 @@ class App //Check if module is an app and if public access to apps is allowed or not $privateapps = $this->config->get('config', 'private_addons', false); if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) { - info(Core\L10n::t("You must be logged in to use addons. ")); + info($this->l10n->t("You must be logged in to use addons. ")); } else { include_once "addon/{$this->module}/{$this->module}.php"; if (function_exists($this->module . '_module')) { @@ -1361,7 +1375,7 @@ class App $a = $this; // Used as is in view/php/default.php - $lang = Core\L10n::getCurrentLang(); + $lang = $this->l10n->getCurrentLang(); /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything require_once $template; diff --git a/src/Core/L10n.php b/src/Core/L10n.php index ae0ed18c3d..1eae16bca8 100644 --- a/src/Core/L10n.php +++ b/src/Core/L10n.php @@ -4,50 +4,27 @@ */ namespace Friendica\Core; -use Friendica\BaseObject; -use Friendica\Database\DBA; -use Friendica\Util\Strings; +use Friendica\Core\L10n\L10n as L10nClass; /** * Provide Language, Translation, and Localization functions to the application * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N"). */ -class L10n extends BaseObject +class L10n { /** - * A string indicating the current language used for translation: - * - Two-letter ISO 639-1 code. - * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code. - * @var string + * @var L10nClass */ - private static $lang = ''; - /** - * A language code saved for later after pushLang() has been called. - * - * @var string - */ - private static $langSave = ''; + private static $l10n; /** - * An array of translation strings whose key is the neutral english message. + * Initializes the L10n static wrapper with the instance * - * @var array + * @param L10nClass $l10n The l10n class */ - private static $strings = []; - /** - * An array of translation strings saved for later after pushLang() has been called. - * - * @var array - */ - private static $stringsSave = []; - - /** - * Detects the language and sets the translation table - */ - public static function init() + public static function init(L10nClass $l10n) { - $lang = self::detectLanguage(); - self::loadTranslationTable($lang); + self::$l10n = $l10n; } /** @@ -57,82 +34,7 @@ class L10n extends BaseObject */ public static function getCurrentLang() { - return self::$lang; - } - - /** - * Sets the language session variable - */ - public static function setSessionVariable() - { - if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) { - $_SESSION['language'] = self::$lang; - // we haven't loaded user data yet, but we need user language - if (!empty($_SESSION['uid'])) { - $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]); - if (DBA::isResult($user)) { - $_SESSION['language'] = $user['language']; - } - } - } - - if (isset($_GET['lang'])) { - $_SESSION['language'] = $_GET['lang']; - } - } - - public static function setLangFromSession() - { - if (!empty($_SESSION['language']) && $_SESSION['language'] !== self::$lang) { - self::loadTranslationTable($_SESSION['language']); - } - } - - /** - * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header - * @return string The two-letter language code - * @throws \Friendica\Network\HTTPException\InternalServerErrorException - */ - public static function detectLanguage() - { - $lang_list = []; - - if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { - // break up string into pieces (languages and q factors) - preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse); - - if (count($lang_parse[1])) { - // go through the list of prefered languages and add a generic language - // for sub-linguas (e.g. de-ch will add de) if not already in array - for ($i = 0; $i < count($lang_parse[1]); $i++) { - $lang_list[] = strtolower($lang_parse[1][$i]); - if (strlen($lang_parse[1][$i])>3) { - $dashpos = strpos($lang_parse[1][$i], '-'); - if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) { - $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos)); - } - } - } - } - } - - if (isset($_GET['lang'])) { - $lang_list = [$_GET['lang']]; - } - - // check if we have translations for the preferred languages and pick the 1st that has - foreach ($lang_list as $lang) { - if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) { - $preferred = $lang; - break; - } - } - if (isset($preferred)) { - return $preferred; - } - - // in case none matches, get the system wide configured language, or fall back to English - return Config::get('system', 'language', 'en'); + return self::$l10n->getCurrentLang(); } /** @@ -150,20 +52,7 @@ class L10n extends BaseObject */ public static function pushLang($lang) { - if (!self::$lang) { - self::init(); - } - - if ($lang === self::$lang) { - return; - } - - if (!self::$langSave) { - self::$langSave = self::$lang; - self::$stringsSave = self::$strings; - } - - self::loadTranslationTable($lang); + self::$l10n->pushLang($lang); } /** @@ -171,55 +60,7 @@ class L10n extends BaseObject */ public static function popLang() { - if (!self::$langSave) { - return; - } - - self::$strings = self::$stringsSave; - self::$lang = self::$langSave; - - self::$stringsSave = []; - self::$langSave = ''; - } - - /** - * Loads string translation table - * - * First addon strings are loaded, then globals - * - * Uses an App object shim since all the strings files refer to $a->strings - * - * @param string $lang language code to load - * @throws \Exception - */ - private static function loadTranslationTable($lang) - { - $lang = Strings::sanitizeFilePathItem($lang); - - if ($lang === self::$lang) { - return; - } - - $a = new \stdClass(); - $a->strings = []; - - // load enabled addons strings - $addons = DBA::select('addon', ['name'], ['installed' => true]); - while ($p = DBA::fetch($addons)) { - $name = Strings::sanitizeFilePathItem($p['name']); - if (file_exists("addon/$name/lang/$lang/strings.php")) { - include "addon/$name/lang/$lang/strings.php"; - } - } - - if (file_exists("view/lang/$lang/strings.php")) { - include "view/lang/$lang/strings.php"; - } - - self::$lang = $lang; - self::$strings = $a->strings; - - unset($a); + self::$l10n->popLang(); } /** @@ -240,24 +81,7 @@ class L10n extends BaseObject */ public static function t($s, ...$vars) { - if (empty($s)) { - return ''; - } - - if (!self::$lang) { - self::init(); - } - - if (!empty(self::$strings[$s])) { - $t = self::$strings[$s]; - $s = is_array($t) ? $t[0] : $t; - } - - if (count($vars) > 0) { - $s = sprintf($s, ...$vars); - } - - return $s; + return self::$l10n->t($s, $vars); } /** @@ -279,55 +103,9 @@ class L10n extends BaseObject * @return string * @throws \Exception */ - public static function tt($singular, $plural, $count) + public static function tt(string $singular, string $plural, int $count) { - if (!is_numeric($count)) { - Logger::log('Non numeric count called by ' . System::callstack(20)); - } - - if (!self::$lang) { - self::init(); - } - - if (!empty(self::$strings[$singular])) { - $t = self::$strings[$singular]; - if (is_array($t)) { - $plural_function = 'string_plural_select_' . str_replace('-', '_', self::$lang); - if (function_exists($plural_function)) { - $i = $plural_function($count); - } else { - $i = self::stringPluralSelectDefault($count); - } - - // for some languages there is only a single array item - if (!isset($t[$i])) { - $s = $t[0]; - } else { - $s = $t[$i]; - } - } else { - $s = $t; - } - } elseif (self::stringPluralSelectDefault($count)) { - $s = $plural; - } else { - $s = $singular; - } - - $s = @sprintf($s, $count); - - return $s; - } - - /** - * Provide a fallback which will not collide with a function defined in any language file - * - * @param int $n - * @return bool - */ - private static function stringPluralSelectDefault($n) - { - return $n != 1; + return self::$l10n->tt($singular, $plural, $count); } /** @@ -343,20 +121,7 @@ class L10n extends BaseObject */ public static function getAvailableLanguages() { - $langs = []; - $strings_file_paths = glob('view/lang/*/strings.php'); - - if (is_array($strings_file_paths) && count($strings_file_paths)) { - if (!in_array('view/lang/en/strings.php', $strings_file_paths)) { - $strings_file_paths[] = 'view/lang/en/strings.php'; - } - asort($strings_file_paths); - foreach ($strings_file_paths as $strings_file_path) { - $path_array = explode('/', $strings_file_path); - $langs[$path_array[2]] = $path_array[2]; - } - } - return $langs; + return self::$l10n::getAvailableLanguages(); } /** @@ -367,15 +132,7 @@ class L10n extends BaseObject */ public static function getDay($s) { - $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], - [self::t('Monday'), self::t('Tuesday'), self::t('Wednesday'), self::t('Thursday'), self::t('Friday'), self::t('Saturday'), self::t('Sunday')], - $s); - - $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], - [self::t('January'), self::t('February'), self::t('March'), self::t('April'), self::t('May'), self::t('June'), self::t('July'), self::t('August'), self::t('September'), self::t('October'), self::t('November'), self::t('December')], - $ret); - - return $ret; + return self::$l10n->getDay($s); } /** @@ -386,40 +143,6 @@ class L10n extends BaseObject */ public static function getDayShort($s) { - $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], - [self::t('Mon'), self::t('Tue'), self::t('Wed'), self::t('Thu'), self::t('Fri'), self::t('Sat'), self::t('Sun')], - $s); - - $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], - [self::t('Jan'), self::t('Feb'), self::t('Mar'), self::t('Apr'), self::t('May'), ('Jun'), self::t('Jul'), self::t('Aug'), self::t('Sep'), self::t('Oct'), self::t('Nov'), self::t('Dec')], - $ret); - - return $ret; - } - - /** - * Load poke verbs - * - * @return array index is present tense verb - * value is array containing past tense verb, translation of present, translation of past - * @throws \Friendica\Network\HTTPException\InternalServerErrorException - * @hook poke_verbs pokes array - */ - public static function getPokeVerbs() - { - // index is present tense verb - // value is array containing past tense verb, translation of present, translation of past - $arr = [ - 'poke' => ['poked', self::t('poke'), self::t('poked')], - 'ping' => ['pinged', self::t('ping'), self::t('pinged')], - 'prod' => ['prodded', self::t('prod'), self::t('prodded')], - 'slap' => ['slapped', self::t('slap'), self::t('slapped')], - 'finger' => ['fingered', self::t('finger'), self::t('fingered')], - 'rebuff' => ['rebuffed', self::t('rebuff'), self::t('rebuffed')], - ]; - - Hook::callAll('poke_verbs', $arr); - - return $arr; + return self::$l10n->getDayShort($s); } } diff --git a/src/Core/L10n/L10n.php b/src/Core/L10n/L10n.php new file mode 100644 index 0000000000..e1a8659472 --- /dev/null +++ b/src/Core/L10n/L10n.php @@ -0,0 +1,426 @@ +dba = $dba; + $this->logger = $logger; + + $this->loadTranslationTable($lang); + + \Friendica\Core\L10n::init($this); + } + + /** + * Returns the current language code + * + * @return string Language code + */ + public function getCurrentLang() + { + return $this->lang; + } + + /** + * Sets the language session variable + */ + public function setSessionVariable() + { + if (Session::get('authenticated') && !Session::get('language')) { + $_SESSION['language'] = $this->lang; + // we haven't loaded user data yet, but we need user language + if (Session::get('uid')) { + $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]); + if ($this->dba->isResult($user)) { + $_SESSION['language'] = $user['language']; + } + } + } + + if (isset($_GET['lang'])) { + Session::set('language', $_GET['lang']); + } + } + + public function setLangFromSession() + { + if (Session::get('language') !== $this->lang) { + $this->loadTranslationTable(Session::get('language')); + } + } + + /** + * This function should be called before formatting messages in a specific target language + * different from the current user/system language. + * + * It saves the current translation strings in a separate variable and loads new translations strings. + * + * If called repeatedly, it won't save the translation strings again, just load the new ones. + * + * @param string $lang Language code + * + * @throws \Exception + * @see popLang() + * @brief Stores the current language strings and load a different language. + */ + public function pushLang($lang) + { + if ($lang === $this->lang) { + return; + } + + if (!$this->langSave) { + $this->langSave = $this->lang; + $this->stringsSave = $this->strings; + } + + $this->loadTranslationTable($lang); + } + + /** + * Restores the original user/system language after having used pushLang() + */ + public function popLang() + { + if (!isset($this->langSave)) { + return; + } + + $this->strings = $this->stringsSave; + $this->lang = $this->langSave; + + unset($this->stringsSave); + unset($this->langSave); + } + + /** + * Loads string translation table + * + * First addon strings are loaded, then globals + * + * Uses an App object shim since all the strings files refer to $a->strings + * + * @param string $lang language code to load + * + * @throws \Exception + */ + private function loadTranslationTable($lang) + { + $lang = Strings::sanitizeFilePathItem($lang); + + $a = new \stdClass(); + $a->strings = []; + + // load enabled addons strings + $addons = $this->dba->select('addon', ['name'], ['installed' => true]); + while ($p = $this->dba->fetch($addons)) { + $name = Strings::sanitizeFilePathItem($p['name']); + if (file_exists("addon/$name/lang/$lang/strings.php")) { + include "addon/$name/lang/$lang/strings.php"; + } + } + + if (file_exists("view/lang/$lang/strings.php")) { + include "view/lang/$lang/strings.php"; + } + + $this->lang = $lang; + $this->strings = $a->strings; + + unset($a); + } + + /** + * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header + * + * @param string $sysLang The default fallback language + * + * @return string The two-letter language code + */ + public static function detectLanguage(string $sysLang = 'en') + { + $lang_list = []; + + if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { + // break up string into pieces (languages and q factors) + preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse); + + if (count($lang_parse[1])) { + // go through the list of prefered languages and add a generic language + // for sub-linguas (e.g. de-ch will add de) if not already in array + for ($i = 0; $i < count($lang_parse[1]); $i++) { + $lang_list[] = strtolower($lang_parse[1][$i]); + if (strlen($lang_parse[1][$i]) > 3) { + $dashpos = strpos($lang_parse[1][$i], '-'); + if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) { + $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos)); + } + } + } + } + } + + if (isset($_GET['lang'])) { + $lang_list = [$_GET['lang']]; + } + + // check if we have translations for the preferred languages and pick the 1st that has + foreach ($lang_list as $lang) { + if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) { + $preferred = $lang; + break; + } + } + if (isset($preferred)) { + return $preferred; + } + + // in case none matches, get the system wide configured language, or fall back to English + return $sysLang; + } + + /** + * @brief Return the localized version of the provided string with optional string interpolation + * + * This function takes a english string as parameter, and if a localized version + * exists for the current language, substitutes it before performing an eventual + * string interpolation (sprintf) with additional optional arguments. + * + * Usages: + * - L10n::t('This is an example') + * - L10n::t('URL %s returned no result', $url) + * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version) + * + * @param string $s + * @param array $vars Variables to interpolate in the translation string + * + * @return string + */ + public function t($s, ...$vars) + { + if (empty($s)) { + return ''; + } + + if (!empty($this->strings[$s])) { + $t = $this->strings[$s]; + $s = is_array($t) ? $t[0] : $t; + } + + if (count($vars) > 0) { + $s = sprintf($s, ...$vars); + } + + return $s; + } + + /** + * @brief Return the localized version of a singular/plural string with optional string interpolation + * + * This function takes two english strings as parameters, singular and plural, as + * well as a count. If a localized version exists for the current language, they + * are used instead. Discrimination between singular and plural is done using the + * localized function if any or the default one. Finally, a string interpolation + * is performed using the count as parameter. + * + * Usages: + * - L10n::tt('Like', 'Likes', $count) + * - L10n::tt("%s user deleted", "%s users deleted", count($users)) + * + * @param string $singular + * @param string $plural + * @param int $count + * + * @return string + * @throws \Exception + */ + public function tt(string $singular, string $plural, int $count) + { + if (!empty($this->strings[$singular])) { + $t = $this->strings[$singular]; + if (is_array($t)) { + $plural_function = 'string_plural_select_' . str_replace('-', '_', $this->lang); + if (function_exists($plural_function)) { + $i = $plural_function($count); + } else { + $i = $this->stringPluralSelectDefault($count); + } + + // for some languages there is only a single array item + if (!isset($t[$i])) { + $s = $t[0]; + } else { + $s = $t[$i]; + } + } else { + $s = $t; + } + } elseif ($this->stringPluralSelectDefault($count)) { + $s = $plural; + } else { + $s = $singular; + } + + $s = @sprintf($s, $count); + + return $s; + } + + /** + * Provide a fallback which will not collide with a function defined in any language file + * + * @param int $n + * + * @return bool + */ + private function stringPluralSelectDefault($n) + { + return $n != 1; + } + + /** + * Return installed languages codes as associative array + * + * Scans the view/lang directory for the existence of "strings.php" files, and + * returns an alphabetical list of their folder names (@-char language codes). + * Adds the english language if it's missing from the list. + * + * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...) + * + * @return array + */ + public static function getAvailableLanguages() + { + $langs = []; + $strings_file_paths = glob('view/lang/*/strings.php'); + + if (is_array($strings_file_paths) && count($strings_file_paths)) { + if (!in_array('view/lang/en/strings.php', $strings_file_paths)) { + $strings_file_paths[] = 'view/lang/en/strings.php'; + } + asort($strings_file_paths); + foreach ($strings_file_paths as $strings_file_path) { + $path_array = explode('/', $strings_file_path); + $langs[$path_array[2]] = $path_array[2]; + } + } + return $langs; + } + + /** + * Translate days and months names. + * + * @param string $s String with day or month name. + * + * @return string Translated string. + */ + public function getDay($s) + { + $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], + [$this->t('Monday'), $this->t('Tuesday'), $this->t('Wednesday'), $this->t('Thursday'), $this->t('Friday'), $this->t('Saturday'), $this->t('Sunday')], + $s); + + $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + [$this->t('January'), $this->t('February'), $this->t('March'), $this->t('April'), $this->t('May'), $this->t('June'), $this->t('July'), $this->t('August'), $this->t('September'), $this->t('October'), $this->t('November'), $this->t('December')], + $ret); + + return $ret; + } + + /** + * Translate short days and months names. + * + * @param string $s String with short day or month name. + * + * @return string Translated string. + */ + public function getDayShort($s) + { + $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + [$this->t('Mon'), $this->t('Tue'), $this->t('Wed'), $this->t('Thu'), $this->t('Fri'), $this->t('Sat'), $this->t('Sun')], + $s); + + $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + [$this->t('Jan'), $this->t('Feb'), $this->t('Mar'), $this->t('Apr'), $this->t('May'), $this->t('Jun'), $this->t('Jul'), $this->t('Aug'), $this->t('Sep'), $this->t('Oct'), $this->t('Nov'), $this->t('Dec')], + $ret); + + return $ret; + } + + /** + * Load poke verbs + * + * @return array index is present tense verb + * value is array containing past tense verb, translation of present, translation of past + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @hook poke_verbs pokes array + */ + public function getPokeVerbs() + { + // index is present tense verb + // value is array containing past tense verb, translation of present, translation of past + $arr = [ + 'poke' => ['poked', $this->t('poke'), $this->t('poked')], + 'ping' => ['pinged', $this->t('ping'), $this->t('pinged')], + 'prod' => ['prodded', $this->t('prod'), $this->t('prodded')], + 'slap' => ['slapped', $this->t('slap'), $this->t('slapped')], + 'finger' => ['fingered', $this->t('finger'), $this->t('fingered')], + 'rebuff' => ['rebuffed', $this->t('rebuff'), $this->t('rebuffed')], + ]; + + Hook::callAll('poke_verbs', $arr); + + return $arr; + } +} diff --git a/src/Factory/DependencyFactory.php b/src/Factory/DependencyFactory.php index d444f5d2f3..79d51331ae 100644 --- a/src/Factory/DependencyFactory.php +++ b/src/Factory/DependencyFactory.php @@ -3,6 +3,7 @@ namespace Friendica\Factory; use Friendica\App; +use Friendica\Core\L10n\L10n; use Friendica\Core\Config\Cache\PConfigCache; use Friendica\Factory; use Friendica\Util\BasePath; @@ -39,7 +40,10 @@ class DependencyFactory $logger = Factory\LoggerFactory::create($channel, $database, $config, $profiler); Factory\LoggerFactory::createDev($channel, $config, $profiler); $baseURL = new BaseURL($config, $_SERVER); + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'de')), + $database, + $logger); - return new App($database, $config, $mode, $router, $baseURL, $logger, $profiler, $isBackend); + return new App($database, $config, $mode, $router, $baseURL, $logger, $profiler, $l10n, $isBackend); } } diff --git a/src/Module/Register.php b/src/Module/Register.php index 06b62783f6..217581b160 100644 --- a/src/Module/Register.php +++ b/src/Module/Register.php @@ -7,10 +7,10 @@ use Friendica\Content\Text\BBCode; use Friendica\Core\Config; use Friendica\Core\Hook; use Friendica\Core\L10n; +use Friendica\Core\L10n\L10n as L10nClass; use Friendica\Core\Logger; use Friendica\Core\PConfig; use Friendica\Core\Renderer; -use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Model; @@ -203,7 +203,7 @@ class Register extends BaseModule $arr['blocked'] = $blocked; $arr['verified'] = $verified; - $arr['language'] = L10n::detectLanguage(); + $arr['language'] = L10nClass::detectLanguage($a->getConfig()->get('system', 'language')); try { $result = Model\User::create($arr); diff --git a/tests/Util/L10nMockTrait.php b/tests/Util/L10nMockTrait.php deleted file mode 100644 index e47a35edcc..0000000000 --- a/tests/Util/L10nMockTrait.php +++ /dev/null @@ -1,46 +0,0 @@ -l10nMock)) { - $this->l10nMock = \Mockery::mock('alias:' . L10n::class); - } - - $with = isset($input) ? $input : \Mockery::any(); - - $return = isset($return) ? $return : $with; - - if ($return instanceof \Mockery\Matcher\Any) { - $this->l10nMock - ->shouldReceive('t') - ->with($with) - ->times($times) - ->andReturnUsing(function($arg) { return $arg; }); - } else { - $this->l10nMock - ->shouldReceive('t') - ->with($with) - ->times($times) - ->andReturn($return); - } - } -} diff --git a/tests/include/ApiTest.php b/tests/include/ApiTest.php index 902445baa2..05ce00b10f 100644 --- a/tests/include/ApiTest.php +++ b/tests/include/ApiTest.php @@ -8,6 +8,7 @@ namespace Friendica\Test; use Friendica\App; use Friendica\Core\Config; use Friendica\Core\Config\Cache\PConfigCache; +use Friendica\Core\L10n\L10n; use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\System; @@ -55,7 +56,10 @@ class ApiTest extends DatabaseTest $logger = Factory\LoggerFactory::create('test', self::$dba, $config, self::$profiler); $baseUrl = new BaseURL($config, $_SERVER); $router = new App\Router(); - $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, false); + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'en')), + self::$dba, + $logger); + $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, $l10n, false); parent::setUp(); diff --git a/tests/src/Console/AutomaticInstallationConsoleTest.php b/tests/src/Console/AutomaticInstallationConsoleTest.php index a5df0e92aa..596c9a7d36 100644 --- a/tests/src/Console/AutomaticInstallationConsoleTest.php +++ b/tests/src/Console/AutomaticInstallationConsoleTest.php @@ -5,10 +5,10 @@ namespace Friendica\Test\src\Console; use Friendica\Console\AutomaticInstallation; use Friendica\Core\Config\Cache\ConfigCache; use Friendica\Core\Installer; +use Friendica\Core\L10n\L10n; use Friendica\Core\Logger; use Friendica\Test\Util\DBAMockTrait; use Friendica\Test\Util\DBStructureMockTrait; -use Friendica\Test\Util\L10nMockTrait; use Friendica\Test\Util\RendererMockTrait; use Friendica\Util\BaseURL; use Friendica\Util\Logger\VoidLogger; @@ -20,7 +20,6 @@ use org\bovigo\vfs\vfsStreamFile; */ class AutomaticInstallationConsoleTest extends ConsoleTest { - use L10nMockTrait; use DBAMockTrait; use DBStructureMockTrait; use RendererMockTrait; @@ -50,7 +49,9 @@ class AutomaticInstallationConsoleTest extends ConsoleTest ->removeChild('local.config.php'); } - $this->mockL10nT(); + $l10nMock = \Mockery::mock(L10n::class); + $l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); + \Friendica\Core\L10n::init($l10nMock); $this->configCache = new ConfigCache(); $this->configCache->set('system', 'basepath', $this->root->url()); @@ -72,7 +73,7 @@ class AutomaticInstallationConsoleTest extends ConsoleTest return $this->configCache->get($cat, $key); }); $this->configMock->shouldReceive('load')->andReturnUsing(function ($config, $overwrite = false) { - return $this->configCache->load($config, $overwrite); + $this->configCache->load($config, $overwrite); }); $this->mode->shouldReceive('isInstall')->andReturn(true); diff --git a/tests/src/Content/SmiliesTest.php b/tests/src/Content/SmiliesTest.php index 40d126e005..4e0859d7c4 100644 --- a/tests/src/Content/SmiliesTest.php +++ b/tests/src/Content/SmiliesTest.php @@ -1,69 +1,67 @@ -setUpVfsDir(); - $this->mockApp($this->root); - $this->app->videowidth = 425; - $this->app->videoheight = 350; - $this->configMock->shouldReceive('get') - ->with('system', 'no_smilies') - ->andReturn(false); - $this->configMock->shouldReceive('get') - ->with(false, 'system', 'no_smilies') - ->andReturn(false); - } - - public function dataLinks() - { - return [ - /** @see https://github.com/friendica/friendica/pull/6933 */ - 'bug-6933-1' => [ - 'data' => '/', - 'smilies' => ['texts' => [], 'icons' => []], - 'expected' => '/', - ], - 'bug-6933-2' => [ - 'data' => 'code', - 'smilies' => ['texts' => [], 'icons' => []], - 'expected' => 'code', - ], - ]; - } - - /** - * Test replace smilies in different texts - * @dataProvider dataLinks - * - * @param string $text Test string - * @param array $smilies List of smilies to replace - * @param string $expected Expected result - * @throws \Friendica\Network\HTTPException\InternalServerErrorException - */ - public function testReplaceFromArray($text, $smilies, $expected) - { - $output = Smilies::replaceFromArray($text, $smilies); - $this->assertEquals($expected, $output); - } -} +setUpVfsDir(); + $this->mockApp($this->root); + $this->app->videowidth = 425; + $this->app->videoheight = 350; + $this->configMock->shouldReceive('get') + ->with('system', 'no_smilies') + ->andReturn(false); + $this->configMock->shouldReceive('get') + ->with(false, 'system', 'no_smilies') + ->andReturn(false); + } + + public function dataLinks() + { + return [ + /** @see https://github.com/friendica/friendica/pull/6933 */ + 'bug-6933-1' => [ + 'data' => '/', + 'smilies' => ['texts' => [], 'icons' => []], + 'expected' => '/', + ], + 'bug-6933-2' => [ + 'data' => 'code', + 'smilies' => ['texts' => [], 'icons' => []], + 'expected' => 'code', + ], + ]; + } + + /** + * Test replace smilies in different texts + * @dataProvider dataLinks + * + * @param string $text Test string + * @param array $smilies List of smilies to replace + * @param string $expected Expected result + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + */ + public function testReplaceFromArray($text, $smilies, $expected) + { + $output = Smilies::replaceFromArray($text, $smilies); + $this->assertEquals($expected, $output); + } +} diff --git a/tests/src/Content/Text/BBCodeTest.php b/tests/src/Content/Text/BBCodeTest.php index 6ae28e8c29..df89bda312 100644 --- a/tests/src/Content/Text/BBCodeTest.php +++ b/tests/src/Content/Text/BBCodeTest.php @@ -3,20 +3,15 @@ namespace Friendica\Test\src\Content\Text; use Friendica\Content\Text\BBCode; +use Friendica\Core\L10n\L10n; use Friendica\Test\MockedTest; use Friendica\Test\Util\AppMockTrait; -use Friendica\Test\Util\L10nMockTrait; use Friendica\Test\Util\VFSTrait; -/** - * @runTestsInSeparateProcesses - * @preserveGlobalState disabled - */ class BBCodeTest extends MockedTest { use VFSTrait; use AppMockTrait; - use L10nMockTrait; protected function setUp() { @@ -43,7 +38,11 @@ class BBCodeTest extends MockedTest $this->configMock->shouldReceive('get') ->with('system', 'no_smilies') ->andReturn(false); - $this->mockL10nT(); + + $l10nMock = \Mockery::mock(L10n::class); + $l10nMock->shouldReceive('t')->withAnyArgs()->andReturnUsing(function ($args) { return $args; }); + \Friendica\Core\L10n::init($l10nMock); + } public function dataLinks() diff --git a/tests/src/Core/InstallerTest.php b/tests/src/Core/InstallerTest.php index 738403bc4e..59947efa33 100644 --- a/tests/src/Core/InstallerTest.php +++ b/tests/src/Core/InstallerTest.php @@ -7,24 +7,32 @@ use Friendica\Core\Config\Cache\ConfigCache; use Friendica\Network\CurlResult; use Friendica\Object\Image; use Friendica\Test\MockedTest; -use Friendica\Test\Util\L10nMockTrait; use Friendica\Test\Util\VFSTrait; use Friendica\Util\Network; +use Mockery\MockInterface; -/** - * @runTestsInSeparateProcesses - * @preserveGlobalState disabled - */ class InstallerTest extends MockedTest { use VFSTrait; - use L10nMockTrait; + + /** + * @var \Friendica\Core\L10n\L10n|MockInterface + */ + private $l10nMock; public function setUp() { parent::setUp(); $this->setUpVfsDir(); + + $this->l10nMock = \Mockery::mock(\Friendica\Core\L10n\L10n::class); + L10n::init($this->l10nMock); + } + + private function mockL10nT(string $text, $times = null) + { + $this->l10nMock->shouldReceive('t')->with($text, [])->andReturn($text)->times($times); } /** @@ -105,7 +113,7 @@ class InstallerTest extends MockedTest */ public function testCheckKeys() { - $this->mockL10nT(); + $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->setFunctions(['openssl_pkey_new' => false]); $install = new Installer(); @@ -229,7 +237,7 @@ class InstallerTest extends MockedTest */ public function testCheckLocalIni() { - $this->mockL10nT(); + $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->assertTrue($this->root->hasChild('config/local.config.php')); @@ -246,10 +254,12 @@ class InstallerTest extends MockedTest /** * @small + * @runInSeparateProcess + * @preserveGlobalState disabled */ public function testCheckHtAccessFail() { - $this->mockL10nT(); + $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); // Mocking the CURL Response $curlResult = \Mockery::mock(CurlResult::class); @@ -285,10 +295,12 @@ class InstallerTest extends MockedTest /** * @small + * @runInSeparateProcess + * @preserveGlobalState disabled */ public function testCheckHtAccessWork() { - $this->mockL10nT(); + $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); // Mocking the failed CURL Response $curlResultF = \Mockery::mock(CurlResult::class); @@ -326,10 +338,12 @@ class InstallerTest extends MockedTest /** * @small + * @runInSeparateProcess + * @preserveGlobalState disabled */ public function testImagick() { - $this->mockL10nT(); + $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $imageMock = \Mockery::mock('alias:'. Image::class); $imageMock @@ -353,10 +367,12 @@ class InstallerTest extends MockedTest /** * @small + * @runInSeparateProcess + * @preserveGlobalState disabled */ public function testImagickNotFound() { - $this->mockL10nT(); + $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $imageMock = \Mockery::mock('alias:' . Image::class); $imageMock @@ -399,7 +415,7 @@ class InstallerTest extends MockedTest */ public function testSetUpCache() { - $this->mockL10nT(); + $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $install = new Installer(); $configCache = \Mockery::mock(ConfigCache::class); diff --git a/tests/src/Database/DBATest.php b/tests/src/Database/DBATest.php index 530430feb1..97142976be 100644 --- a/tests/src/Database/DBATest.php +++ b/tests/src/Database/DBATest.php @@ -4,6 +4,7 @@ namespace Friendica\Test\src\Database; use Friendica\App; use Friendica\Core\Config; use Friendica\Core\Config\Cache\PConfigCache; +use Friendica\Core\L10n\L10n; use Friendica\Database\DBA; use Friendica\Factory; use Friendica\Test\DatabaseTest; @@ -20,7 +21,10 @@ class DBATest extends DatabaseTest $logger = Factory\LoggerFactory::create('test', self::$dba, $config, self::$profiler); $baseUrl = new BaseURL($config, $_SERVER); $router = new App\Router(); - $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, false); + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'en')), + self::$dba, + $logger); + $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, $l10n, false); parent::setUp(); diff --git a/tests/src/Database/DBStructureTest.php b/tests/src/Database/DBStructureTest.php index 64d249f4c0..29de13cb78 100644 --- a/tests/src/Database/DBStructureTest.php +++ b/tests/src/Database/DBStructureTest.php @@ -4,6 +4,7 @@ namespace Friendica\Test\src\Database; use Friendica\App; use Friendica\Core\Config\Cache\PConfigCache; +use Friendica\Core\L10n\L10n; use Friendica\Database\DBStructure; use Friendica\Factory; use Friendica\Model\Config\Config; @@ -24,8 +25,10 @@ class DBStructureTest extends DatabaseTest $logger = Factory\LoggerFactory::create('test', self::$dba, $config, self::$profiler); $baseUrl = new BaseURL($config, $_SERVER); $router = new App\Router(); - $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, false); - + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'en')), + self::$dba, + $logger); + $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, $l10n, false); parent::setUp(); } From 79e69ee52807967858f5cb89e702be035f979ba5 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 16 Jul 2019 16:50:49 +0200 Subject: [PATCH 2/2] Fix language (again ;-) ) --- src/Factory/DependencyFactory.php | 4 ++-- tests/include/ApiTest.php | 2 +- tests/src/Database/DBATest.php | 2 +- tests/src/Database/DBStructureTest.php | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Factory/DependencyFactory.php b/src/Factory/DependencyFactory.php index 79d51331ae..10d4ea587f 100644 --- a/src/Factory/DependencyFactory.php +++ b/src/Factory/DependencyFactory.php @@ -3,8 +3,8 @@ namespace Friendica\Factory; use Friendica\App; -use Friendica\Core\L10n\L10n; use Friendica\Core\Config\Cache\PConfigCache; +use Friendica\Core\L10n\L10n; use Friendica\Factory; use Friendica\Util\BasePath; use Friendica\Util\BaseURL; @@ -40,7 +40,7 @@ class DependencyFactory $logger = Factory\LoggerFactory::create($channel, $database, $config, $profiler); Factory\LoggerFactory::createDev($channel, $config, $profiler); $baseURL = new BaseURL($config, $_SERVER); - $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'de')), + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language')), $database, $logger); diff --git a/tests/include/ApiTest.php b/tests/include/ApiTest.php index 05ce00b10f..0c25ccc1c7 100644 --- a/tests/include/ApiTest.php +++ b/tests/include/ApiTest.php @@ -56,7 +56,7 @@ class ApiTest extends DatabaseTest $logger = Factory\LoggerFactory::create('test', self::$dba, $config, self::$profiler); $baseUrl = new BaseURL($config, $_SERVER); $router = new App\Router(); - $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'en')), + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language')), self::$dba, $logger); $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, $l10n, false); diff --git a/tests/src/Database/DBATest.php b/tests/src/Database/DBATest.php index 97142976be..cc25373e1a 100644 --- a/tests/src/Database/DBATest.php +++ b/tests/src/Database/DBATest.php @@ -21,7 +21,7 @@ class DBATest extends DatabaseTest $logger = Factory\LoggerFactory::create('test', self::$dba, $config, self::$profiler); $baseUrl = new BaseURL($config, $_SERVER); $router = new App\Router(); - $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'en')), + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language')), self::$dba, $logger); $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, $l10n, false); diff --git a/tests/src/Database/DBStructureTest.php b/tests/src/Database/DBStructureTest.php index 29de13cb78..3cecec62a9 100644 --- a/tests/src/Database/DBStructureTest.php +++ b/tests/src/Database/DBStructureTest.php @@ -25,7 +25,7 @@ class DBStructureTest extends DatabaseTest $logger = Factory\LoggerFactory::create('test', self::$dba, $config, self::$profiler); $baseUrl = new BaseURL($config, $_SERVER); $router = new App\Router(); - $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language', 'en')), + $l10n = new L10n(L10n::detectLanguage($config->get('system', 'language')), self::$dba, $logger); $this->app = new App(self::$dba, $config, self::$mode, $router, $baseUrl, $logger, self::$profiler, $l10n, false);