From 5da7b6bb24cb1122e73714fdf0af48bcd8d23791 Mon Sep 17 00:00:00 2001
From: Alpheus <26622568+alpheustangs@users.noreply.github.com>
Date: Fri, 30 Jun 2023 23:17:54 +0800
Subject: [PATCH] Add files
---
.gitattributes | 3 +
.gitignore | 14 +++++
LICENSE | 21 +++++++
README.md | 76 +++++++++++++++++++++++
composer.json | 34 +++++++++++
src/Lang.php | 159 +++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 307 insertions(+)
create mode 100644 .gitattributes
create mode 100644 .gitignore
create mode 100644 LICENSE
create mode 100644 README.md
create mode 100644 composer.json
create mode 100644 src/Lang.php
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..37f2374
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,3 @@
+# Auto detect text files and perform LF normalization
+* text=auto
+*.php linguist-language=PHP
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..3c75192
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,14 @@
+# cache
+__MACOSX
+.DS_Store
+
+# settings
+.vscode/
+
+# composer
+vendor/
+composer.phar
+composer.lock
+
+# log
+*.log
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..c69593a
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 Alpheus
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d39ceea
--- /dev/null
+++ b/README.md
@@ -0,0 +1,76 @@
+# ComfyPHP Multiple Languages Extension
+
+This is a extension for ComfyPHP framework to enable the function using multiple languages.
+
+## Default & Recommended Directory Structure
+
+- `src` directory (default)
+ Where the source files for editing reside.
+ - `langs` directory (default)
+ Store all languages related source code.
+ - `en` directory (optional)
+ English translation folder.
+ - `index.json` language file
+ English translation files.
+ - `zh-Hant` directory (optional)
+ Traditional Chinese translation folder.
+ - `index.json` language file
+ Traditional Chinese translation files.
+
+## Before Using it
+
+As this is an extension for ComfyPHP, All dependencies required in ComfyPHP and ComfyPHP is needed to use this extension.
+
+## Download / Install
+
+To use this extension, you can install it with Composer.
+
+```bash
+composer require comfyphp/lang
+```
+
+## Usage
+
+ComfyPHP will search for the all the languages based on the `CONFIG_LANG_PATH` settings in `comfy.lang.config.php`.
+
+You can add the following line into somewhere and import it into every files later, here we take `src/pages/_init.php` for example:
+
+```php
+$lang = new ComfyPHP\Lang();
+```
+
+Create separate JSON files for each language you want to support. And Place these files in the languages folder. For example, create the following files:
+
+```php
+// src/langs/en/index.json
+{
+ "hello": "Hello!"
+}
+// src/langs/en/special.json
+{
+ "setting": {
+ "title": "Settings"
+ "info": "This is the Settings page."
+ }
+}
+```
+
+In the files where you want to use the multiple languages extension, add the following code to require the file which you initialized the lang extension and enable the function to use those languages:
+
+```php
+$root = $GLOBALS["ROOT"];
+$pagePath = $GLOBALS["CONFIG_PAGE_PATH"];
+require_once "$root/$pagePath/_init.php";
+$t = $lang->useLanguage();
+```
+
+Within the body of your code, you can now access the language strings.
+
+```php
+echo $t("hello");
+echo $t("special:setting.info");
+```
+
+## License
+
+This project is MIT licensed, you can find the license file [here](./LICENSE).
diff --git a/composer.json b/composer.json
new file mode 100644
index 0000000..d809622
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,34 @@
+{
+ "name": "comfyphp/lang",
+ "description": "Extension to enable multiple languages for ComfyPHP",
+ "keywords": [
+ "php",
+ "comfy",
+ "comfyphp",
+ "framework",
+ "comfortable",
+ "comfortably",
+ "multiple",
+ "lang",
+ "language",
+ "languages"
+ ],
+ "homepage": "https://github.com/alpheustangs/comfyphp-lang",
+ "license": "MIT",
+ "authors": [
+ {
+ "name": "Alpheus",
+ "homepage": "https://github.com/alpheustangs",
+ "email": "26622568+alpheustangs@users.noreply.github.com"
+ }
+ ],
+ "require": {
+ "php": ">=8.0",
+ "comfyphp/core": "^1.0.1"
+ },
+ "autoload": {
+ "psr-4": {
+ "ComfyPHP\\": "src/"
+ }
+ }
+}
diff --git a/src/Lang.php b/src/Lang.php
new file mode 100644
index 0000000..61592b6
--- /dev/null
+++ b/src/Lang.php
@@ -0,0 +1,159 @@
+core = new Core();
+ $this->tool = new Tool();
+
+ // declarations
+ $this->root = $GLOBALS["ROOT"];
+
+ $GLOBALS["CONFIG_LANG_PATH"] = "src/langs";
+ $GLOBALS["CONFIG_LANG_PROVIDER"] = ["en", "zh-Hant"];
+ $GLOBALS["CONFIG_LANG_FALLBACK"] = "en";
+ $GLOBALS["CONFIG_LANG_PARAM"] = false;
+ $GLOBALS["CONFIG_LANG_PARAM_NAME"] = "lang";
+ $GLOBALS["CONFIG_LANG_COOKIE"] = false;
+ $GLOBALS["CONFIG_LANG_COOKIE_NAME"] = "lang";
+ $GLOBALS["CONFIG_LANG_COOKIE_DOMAIN"] = "";
+ $GLOBALS["CONFIG_LANG_COOKIE_TIME"] = time() + 3600 * 24 * 30;
+
+ // init $lang
+ $this->lang = $GLOBALS["CONFIG_LANG_FALLBACK"];
+
+ // get configs
+ $this->getConfigs();
+
+ // get langs
+ $this->getLangs();
+ }
+
+ private function getConfigs()
+ {
+ $name = "comfy.lang.config.php";
+ $configs = [
+ "CONFIG_LANG_PATH" => ["multiple languages location", "string", "src/langs"],
+ "CONFIG_LANG_PROVIDER" => ["which languages to provide", "array", ["en", "zh-Hant"]],
+ "CONFIG_LANG_FALLBACK" => ["fallback language if any issue", "string", "en"],
+ "CONFIG_LANG_PARAM" => ["allow user to change language by URL, such as ?lang=en", "boolean", true],
+ "CONFIG_LANG_PARAM_NAME" => ["name of the parameter that will be read by ComfyPHP", "string", "lang"],
+ "CONFIG_LANG_COOKIE" => ["save language preference to cookie", "boolean", true],
+ "CONFIG_LANG_COOKIE_NAME" => ["cookie name that store the language", "string", "lang"],
+ "CONFIG_LANG_COOKIE_DOMAIN" => ["cookie domain that store the language, default blank for localhost", "string", ""],
+ "CONFIG_LANG_COOKIE_TIME" => ["how long will the cookie be valid, default 1 month", "dynamic", "time() + 3600 * 24 * 30"],
+ ];
+
+ $this->core->setConfigs($name, $configs);
+ }
+
+ private function getLangs()
+ {
+ // lang provider
+ $provider = $GLOBALS["CONFIG_LANG_PROVIDER"];
+
+ // param
+ $paramConfig = $GLOBALS["CONFIG_LANG_PARAM"];
+ $paramName = $GLOBALS["CONFIG_LANG_PARAM_NAME"];
+
+ // cookie
+ $cookieConfig = $GLOBALS["CONFIG_LANG_COOKIE"];
+ $cookieName = $GLOBALS["CONFIG_LANG_COOKIE_NAME"];
+ $cookieDomain = $GLOBALS["CONFIG_LANG_COOKIE_DOMAIN"];
+ $cookieTime = $GLOBALS["CONFIG_LANG_COOKIE_TIME"];
+
+ // param
+ if (
+ $paramConfig &&
+ isset($paramName) &&
+ isset($_GET[$paramName]) &&
+ in_array($_GET[$paramName], $provider)
+ ) {
+ $this->lang = htmlspecialchars($_GET[$paramName]);
+ }
+ // cookie
+ elseif (
+ $cookieConfig &&
+ isset($cookieName) &&
+ isset($_COOKIE[$cookieName]) &&
+ in_array($_COOKIE[$cookieName], $provider)
+ ) {
+ $this->lang = htmlspecialchars($_COOKIE[$cookieName]);
+ }
+
+ // set cookie
+ $cookieConfig && setcookie($cookieName, $this->lang, $cookieTime, "/", $cookieDomain);
+ }
+
+ public function useLanguage()
+ {
+ return function ($key) {
+ // declarations
+ $root = $this->root;
+ $lang = $this->lang;
+ $fallback = $GLOBALS["CONFIG_LANG_FALLBACK"];
+ $path = $GLOBALS["CONFIG_LANG_PATH"];
+
+ // $targetFile = "settings" etc...
+ // $keys = ["home", "title"];
+
+ $targeyAndKeys = explode(":", $key);
+ $targetFile = $targeyAndKeys[0];
+
+ // target file is set
+ // settings:home.title
+ if (isset($targeyAndKeys[1])) {
+ $keys = explode(".", $targeyAndKeys[1]);
+ $targetFilePath = "$root/$path/$lang/$targetFile.json";
+ $fallbackFilePath = "$root/$path/$fallback/$targetFile.json";
+ }
+ // target file is not set
+ // home.title
+ else {
+ $keys = explode(".", $targeyAndKeys[0]);
+ $targetFilePath = "$root/$path/$lang/index.json";
+ $fallbackFilePath = "$root/$path/$fallback/index.json";
+ }
+
+ if (file_exists("$targetFilePath")) {
+ $json = file_get_contents("$targetFilePath");
+ $json_data = json_decode($json, true);
+ } else if (file_exists("$fallbackFilePath")) {
+ $json = file_get_contents("$fallbackFilePath");
+ $json_data = json_decode($json, true);
+ }
+
+ return $this->searchKey($json_data, $keys);
+ };
+ }
+
+ private function searchKey(array $data, array $keys): string
+ {
+ // declarations
+ $debug = $GLOBALS["SYSTEM_DEBUG"];
+ // Get the first key from the array
+ $currentKey = array_shift($keys);
+
+ if (is_array($data) && array_key_exists($currentKey, $data)) {
+ $value = $data[$currentKey];
+
+ if (count($keys) > 0 && is_array($value)) {
+ $result = $this->searchKey($value, $keys);
+ return is_string($result) ? $result : ($debug ? "key:$result not found" : "");
+ } else {
+ return is_string($value) ? $value : ($debug ? "key:$value not found" : "");
+ }
+ }
+
+ return ($debug ? "key:$currentKey not found" : "");
+ }
+}