Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
cracksalad committed Aug 25, 2023
0 parents commit ee788e8
Show file tree
Hide file tree
Showing 6 changed files with 212 additions and 0 deletions.
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) Andreas Wahlen

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

This library depends on [php-gettext/Gettext](https://github.com/php-gettext/Gettext) and is inspired by [delight-im/PHP-I18N](https://github.com/delight-im/PHP-I18N) as well as [gettext](https://www.php.net/manual/en/function.gettext).

The main difference to delight-im/PHP-I18N is that this library does not use `gettext()` and `setlocale()` but instead is stateless and thereby supports independent (concurrent) request handling as it is done with [PSR-15: HTTP Handlers](https://www.php-fig.org/psr/psr-15/) and [OpenSwoole](https://openswoole.com/).

## Installation

NOTE: This library requires PHP 8.0+

```bash
composer require cracksalad/i18n
```

## Usage

```php
use Cracksalad\I18n;

$i18n = I18n::load('en');

$i18n->_('Hello world!');
// -> Hello world!

// format (using sprintf() internally)
$i18n->_f('%d items saved', 42);
// -> 42 items saved

// ICU MessageFormat
$i18n->_fe('I first published this library on {0, date, short}', 1692982322);
// -> I first published this library on 8/23/23

// singular vs. plural with format
$i18n->_pf('%d item saved', '%d items saved', 42);
// -> 42 items saved
$i18n->_pf('%d item saved', '%d items saved', 1);
// -> 42 item saved
```

## License

This library is licensed under the MIT License (MIT). Please see [LICENSE](LICENSE) for more information.
49 changes: 49 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"name": "cracksalad/i18n",
"version": "0.1.0",
"type": "library",
"description": "PHP library to properly handle internationalization, but in a stateless fashion - no gettext()!",
"keywords": [
"i18n",
"locale",
"translation",
"gettext",
"intl"
],
"license": "MIT",
"authors": [
{
"name": "Andreas Wahlen",
"role": "Maintainer"
}
],
"require": {
"php": ">=8.0",
"gettext/gettext": "^5.7"
},
"autoload": {
"psr-4": {
"Cracksalad\\I18n\\": "src"
}
},
"scripts": {
"phpunit": "./tools/phpunit test",
"phpcpd": "./tools/phpcpd php_include",
"psalm": "./tools/psalm --no-diff --use-baseline=psalm.baseline.xml --php-version=8.0",
"psalm-stats": "./tools/psalm --no-diff --use-baseline=psalm.baseline.xml --php-version=8.0 --stats | grep -v '(0 mixed)'",
"update-psalm-baseline": "./tools/psalm --no-diff --set-baseline=psalm.baseline.xml",
"tests": [
"@phpunit",
"@phpcpd",
"@psalm"
]
},
"scripts-descriptions": {
"phpunit": "Runs unit/integration tests.",
"phpcpd": "Runs copied code finder.",
"psalm": "Runs static analysis.",
"psalm-stats": "Print files with unsafe types based on psalm.",
"update-psalm-baseline": "Updates baseline for psalm. CAUTION should not be run as a regular procedure!",
"tests": "Runs all available tests."
}
}
4 changes: 4 additions & 0 deletions psalm.baseline.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.13.1@086b94371304750d1c673315321a55d15fc59015">

</files>
14 changes: 14 additions & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<psalm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
hideExternalErrors="true"
allowStringToStandInForClass="true"
errorBaseline="psalm.baseline.xml"
errorLevel="2"
findUnusedBaselineEntry="true"
findUnusedCode="false">

<projectFiles>
<directory name="src" />
</projectFiles>
</psalm>
84 changes: 84 additions & 0 deletions src/I18n.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);

namespace Cracksalad\I18n;

use Gettext\Translation;
use Gettext\Translations;
use Gettext\Loader\MoLoader;

/**
* @author Andreas Wahlen
*/
class I18n implements \JsonSerializable {

private string $locale;
private Translations $translations;

/**
* @throws \InvalidArgumentException if the translation .mo file could not be found or read.
*/
protected function __construct(string $locale, string $domain = 'messages', string $directory = './locale') {
$this->locale = $locale;

$path = \realpath($directory).DIRECTORY_SEPARATOR.$locale.DIRECTORY_SEPARATOR.'LC_MESSAGES'.DIRECTORY_SEPARATOR.$domain.'.mo';
if(!is_file($path) || !is_readable($path)){
throw new \InvalidArgumentException($path.' does not exist or is not readable');
}

$loader = new MoLoader();
$this->translations = $loader->loadFile($path);
}

public function jsonSerialize(): array {
return [
'locale' => $this->locale,
'translations' => $this->translations->toArray()
];
}

public function _(string $original, ?string $context = null): string {
return $this->getTranslation($original, $context)?->getTranslation() ?? $original;
}

public function _f(string $original, string|int|float ...$replacements): string {
return sprintf($this->_($original), ...$replacements);
}

public function _fe(string $original, string|int|float ...$replacements): string {
return $this->formatMessage($this->_($original), ...$replacements);
}

public function _p(string $original, string $plural, int $count): string {
$translation = $this->getTranslation($original);
if($translation === null){
return $count === 1 ? $original : $plural;
}
return $count === 1 ? ($translation->getTranslation() ?? $original) : ($translation->getPlural() ?? $plural);
}

public function _pf(string $original, string $plural, int $count, string|int|float ...$replacements): string {
array_unshift($replacements, $count);
return sprintf($this->_p($original, $plural, $count), ...$replacements);
}

public function _pfe(string $original, string $plural, int $count, string|int|float ...$replacements): string {
return $this->formatMessage($this->_p($original, $plural, $count), ...$replacements);
}

private function getTranslation(string $original, ?string $context = null): ?Translation {
return $this->translations->find($context, $original);
}

/**
* @throws \InvalidArgumentException if $pattern could not be handled by MessageFormatter::format()
*/
private function formatMessage(string $pattern, string|int|float ...$replacements): string {
$formatter = new \MessageFormatter($this->locale, $pattern);
$formatted = $formatter->format($replacements);
if($formatted === false){
throw new \InvalidArgumentException($formatter->getErrorMessage(), $formatter->getErrorCode());
}
return $formatted;
}
}

0 comments on commit ee788e8

Please sign in to comment.