Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nabeghe committed Jan 19, 2024
0 parents commit 363b23b
Show file tree
Hide file tree
Showing 10 changed files with 370 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea
/vendor/
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Hadi Akbarzadeh

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.
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Light Localziation for PHP

> A light weight and path-based PHP localization library that translations are loaded up when needed.
## 🫡 Usage

### 🚀 Installation

You can install the package via composer:

```bash
composer require nabeghe/light-localization
```

### 📁 Localization Directory

- Create a directory for localization.
- In this directory, create new folders, each of these folders actually represent Localization codes.
They can be language codes or anything else.
- Inside each code directory, php files will be placed, each of these files has the role of a translator.
These files can return an array or an object that implements the ArrayAccess interface. If it's an array, each key
will represent a value, but if it's an object, each field or method is a translation key.
The priority is with the method & it must return a value. With the method, you can have dynamic localization!

### Examples

Check the examples folder in the repositiry.

```php
use Nabeghe\LightLocalization\Localizer;

$localizer = new Localizer(__DIR__ . '/langs');
echo $localizer->get('title');
```

**Notice:** The localization code can be specified in the constructor method.
Of course, it's possible to change it later via method `recode`.

## 🧩 Features

- Get the value using the key.
- Localization code (the second parameter of Localizer constructor).
- Default translation value if the key doesn't exists,
(the third parameter of Localizer constructor).
- Create different translators in different files.
- Reload the translator.
- Remove the loaded translator.
- Refreshing translators and reloading them.
- Changing the localization code.

## 📖 License

Copyright (c) 2023 Hadi Akbarzadeh

Licensed under the MIT license, see [LICENSE.md](LICENSE.md) for details.
22 changes: 22 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "nabeghe/light-localization",
"description": "A light weight and path-based PHP localization library that translations are loaded up when needed.",
"type": "library",
"version": "0.1.0",
"homepage": "https://github.com/Nabeghe/LightLocalization",
"license": "MIT",
"autoload": {
"psr-4": {
"Nabeghe\\LightLocalization\\": "src/"
}
},
"authors": [
{
"name": "Hadi Akbarzadeh",
"email": "[email protected]",
"homepage": "https://elatel.ir",
"role": "Developer"
}
],
"require": {}
}
10 changes: 10 additions & 0 deletions examples/array/langs/generic/main.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

return [
'title' => 'Light Localization',
'message' => 'Hey Honey, are you ready?',
'primary_btn_title' => 'Yes',
'secondary_btn_title' => 'No',
'success' => 'Welcome',
'unsuccess' => 'Bye',
];
16 changes: 16 additions & 0 deletions examples/array/localizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

use Nabeghe\LightLocalization\Localizer;

require_once __DIR__ . '/../../vendor/autoload.php';

$localizer = new Localizer(__DIR__ . '/langs');
echo $localizer->get('title');
echo PHP_EOL;
echo $localizer->get('message');
echo PHP_EOL;
echo $localizer->get('primary_btn_title') . '|' . $localizer->get('secondary_btn_title');
echo PHP_EOL;
echo $localizer->get('success');
echo PHP_EOL;
echo $localizer->get('unsuccess');
28 changes: 28 additions & 0 deletions examples/class/langs/generic/main.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

use Nabeghe\LightLocalization\Translator;

return new class extends Translator {
public string $title = 'Light Localization';

public string $primary_btn_title = 'Yes';

public string $secondary_btn_title = 'No';

public string $success = 'Welcome';

public string $unsuccess = 'Bye';

public function message()
{
$msgs = [
'Hey Honey, are you ready?',
'Hey Babe, Let\'s go?',
'Yeah darling... Come with me.',
'Hello Sweetheart, ready for some fun?',
'Hey Love, what do you think about a little adventure?',
'Sweetie, shall we make this a memorable day?',
];
return $msgs[array_rand($msgs)];
}
};
17 changes: 17 additions & 0 deletions examples/class/localizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

use Nabeghe\LightLocalization\Localizer;

require_once __DIR__ . '/../../vendor/autoload.php';

$localizer = new Localizer(__DIR__ . '/langs');
var_dump($localizer->getTranslators());
echo $localizer->get('title');
echo PHP_EOL;
echo $localizer->get('message');
echo PHP_EOL;
echo $localizer->get('primary_btn_title') . '|' . $localizer->get('secondary_btn_title');
echo PHP_EOL;
echo $localizer->get('success');
echo PHP_EOL;
echo $localizer->get('unsuccess');
156 changes: 156 additions & 0 deletions src/Localizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<?php

namespace Nabeghe\LightLocalization;

/**
* Localizer class.
* @package Nabeghe\LightLocalization
*/
class Localizer
{
/**
* Default translator name.
*/
public const DEFAULT_TRANSLATOR = 'main';

/**
* The root path where the directories related to the codes are located.
* @var string
*/
protected string $path;

/**
* Current directory code
* @var string
*/
protected string $code;

/**
* The default translation returned if the requested key (translation) doesn't exist.
* @see self::get()
* @var mixed
*/
protected $defaultTranslation;

/**
* Loaded translators.
* @var array
*/
protected array $translators = [];

/**
* Gets the translators list.
* @return array
*/
public function getTranslators(): array
{
return $this->translators;
}

/**
* Constructor.
* @param string $path The root path where the directories related to the codes are located.
* @param string $code Optional. Localization code. Default generic.
* @param string $default_translation Optional. The default translation returned if the requested key (translation) doesn't exist.. Default empty string.
*/
public function __construct(string $path, string $code = 'generic', $default_translation = '')
{
$this->path = rtrim($path, '/');
$this->code = $code;
$this->defaultTranslation = $default_translation;
}

/**
* Gets the file path of a translator.
* @param string $translator_name Optional. The translator name. Default main.
* @return string
*/
public function getTranslatorPath($translator_name = self::DEFAULT_TRANSLATOR): string
{
return "$this->path/$this->code/$translator_name.php";
}

/**
* Checks if a translator is loaded or not.
* @param $translator_name
* @return bool
*/
public function isLoaded($translator_name): bool
{
return isset($this->translators[$translator_name]);
}

/**
* Loads a translator even if it is already loaded.
* @param string $translator_name
* @return bool
*/
public function load($translator_name = self::DEFAULT_TRANSLATOR): bool
{
$siccess = false;
$branch_path = $this->getTranslatorPath($translator_name);
if (file_exists($branch_path)) {
$new_data = include $branch_path;
if (!$new_data) {
$new_data = [];
} else {
$siccess = true;
}
}
$this->translators[$translator_name] = $new_data ?? [];
return $siccess;
}

/**
* Loads all loaded translators from the beginning.
*/
public function refresh()
{
$translators_names = array_keys($this->translators);
foreach ($translators_names as $translator_name) {
$this->load($translator_name);
}
}

/**
* Removes a translator from loaded state.
* @param string $translator_name
* @return bool
*/
public function unload($translator_name = self::DEFAULT_TRANSLATOR): bool
{
if (isset($this->translators[$translator_name])) {
unset($this->translators[$translator_name]);
return true;
}
return false;
}

/**
* Changes the localization code.
* @param string $code
* @param bool $refresh Optional. After changing the code, should it reload the loaded translators or remove all of them from the loaded state? Default false.
*/
public function recode($code, $refresh = false)
{
$this->code = $code;
if ($refresh) {
$this->refresh();
} else {
$this->translators = [];
}
}

/**
* @param string $key The key is in the translator.
* @param string $translator_name
* @return string|mixed
*/
public function get(string $key, $translator_name = self::DEFAULT_TRANSLATOR)
{
if (!isset($this->translators[$translator_name])) {
$this->load($translator_name);
}
return $this->translators[$translator_name][$key] ?? $this->defaultTranslation;
}
}
43 changes: 43 additions & 0 deletions src/Translator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Nabeghe\LightLocalization;

use ArrayAccess;

/**
* Translator class.
* @package Nabeghe\LightLocalization
*/
class Translator implements ArrayAccess
{
public function offsetExists($offset)
{
return method_exists($this, $offset)
|| property_exists($this, $offset);
}

public function offsetGet($offset)
{
if (method_exists($this, $offset)) {
return $this->$offset();
}

if (property_exists($this, $offset)) {
return $this->$offset;
}

return null;
}

public function offsetSet($offset, $value)
{
$this->$offset = $offset;
}

public function offsetUnset($offset)
{
if (property_exists($this, $offset)) {
unset($this->$offset);
}
}
}

0 comments on commit 363b23b

Please sign in to comment.