Skip to content

Commit

Permalink
Replace iconv with intl
Browse files Browse the repository at this point in the history
Use ICU instead of iconv extension. Change readme and API.
  • Loading branch information
ElForastero committed Dec 8, 2018
1 parent a556232 commit 5cb7506
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 42 deletions.
43 changes: 33 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,30 @@
![GitHub release](https://img.shields.io/github/release/elforastero/transliterate.svg)
![Packagist](https://img.shields.io/packagist/dt/elforastero/transliterate.svg)

Небольшой пакет для транслитерации кириллицы. Из коробки поддерживаются 2 карты траслитерации: общепринятая и ГОСТ 7.79-2000. Поддерживается возможность создания своих собственных карт.
Небольшой пакет для транслитерации кириллицы с возможностью создания своих собственных карт транслитерации.

![Code example](example.png)

- [Предустановленные карты](#Предустановленные-карты)
- [Системные требования](#Системные-требования)
- [Установка](#Установка)
- [Конфигурация](#Конфигурация)
- [Использование](#Использование)
- [Создание карт транслитерации](#Создание-карт-транслитерации)
- [Создание трансформеров](#Создание-трансформеров)

## Предустановленные карты

- Русский
- Дефолтная
- ГОСТ 7.79 2000
- Украинский
- Национальная


## Системные требования
laravel >= 5.6
- laravel >= 5.6
- ext-intl

## Установка
```
Expand All @@ -35,7 +45,7 @@ ElForastero\Transliterate\ServiceProvider::class,
Если вы хотите использовать алиас, добавьте его в массив `facades` в `app.php`.

```php
'Transliteration' => ElForastero\Transliterate\Facade::class,
'Transliterator' => ElForastero\Transliterate\Facade::class,
```

## Конфигурация
Expand All @@ -51,27 +61,37 @@ ElForastero\Transliterate\ServiceProvider::class,
Вы можете использовать фасад для транслитерации строк.

```php
use Transliteration;
use Transliterator;

Transliteration::make('Двадцать тысяч льё под водой');
(new Transliterator)->make('Двадцать тысяч льё под водой');
// "Dvadcat tisyach lyo pod vodoy"
```

Альтернативная карта транслитерации может быть передана вторым параметром.

```php
Transliteration::make('Двадцать тысяч льё под водой', 'gost2000');
$transliterator = new Transliterator(Map::LANG_RU, Map::GOST_7_79_2000);
$transliterator->make('Двадцать тысяч льё под водой');
// "Dvadcat` ty'syach l`yo pod vodoj"
```

## Генерация URL

Метод `slugify` генерирует URL, убирая из строки все знаки препинания и заменяя пробелы на "-".

```php
(new Transliterator)->slugify('Съешь еще этих мягких французских булок, да выпей чаю!');
// sesh-eshhe-etih-myagkih-francuzskih-bulok-da-vipey-chayu
```

## Создание карт транслитерации

Каждая карта представляет собой ассоциативный массив с символами подлежащими замене в качестве ключей, и значениями на которые они будут заменены.

Карта создается в виде отдельного файла с возвращаемым массивом:

```php
// /resources/maps/ukraine.php
// /resources/maps/uk/ukraine.php

return [
'ї' => 'i',
Expand All @@ -83,13 +103,16 @@ return [
Добавьте путь к созданной карте в массив `maps`, конфига `transliterate.php`:

```php
'ukraine' => dirname(__DIR__) . '/resources/maps/ukraine.php',
'uk' => [
'ukraine' => dirname(__DIR__) . '/resources/maps/uk/ukraine.php',
]
```

После этого карту можно использовать.

```php
Transliteration::make('Ваша транслітерація', 'ukraine');
$transliterator = new Transliterator('uk', 'ukraine');
$transliterator->make('Ваша транслітерація');
```

## Создание трансформеров
Expand All @@ -109,4 +132,4 @@ ElForastero\Transliterate\Transformer::register(\Closure::fromCallable('trim')),
ElForastero\Transliterate\Transformer::register(\Closure::fromCallable('strtolower')),
```

> Будьте внимательны, поскольку трансформеры применяются при каждом вызове `Transliteration::make`.
> Будьте внимательны, поскольку трансформеры применяются при каждом вызове `Transliterator::make`.
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@
},
"hooks": {
"pre-commit": [
"php-cs-fixer fix . --rules=@Symfony"
"php-cs-fixer fix ."
]
}
},
"scripts": {
"test": "phpunit",
"check-style": "php-cs-fixer fix src/ --dry-run --diff --rules=@Symfony"
"check-style": "php-cs-fixer fix src/ --dry-run --diff"
}
}
Binary file modified example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 1 addition & 3 deletions src/Facade.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
* Class Facade.
*
* @author Eugene Dzhumak <[email protected]>
*
* @version 2.0.0
*/
class Facade extends BaseFacade
{
Expand All @@ -18,6 +16,6 @@ class Facade extends BaseFacade
*/
public static function getFacadeAccessor()
{
return 'Transliteration';
return 'Transliterator';
}
}
4 changes: 2 additions & 2 deletions src/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

/**
* Class Map.
*
* @author Eugene Dzhumak <[email protected]>
* @version 2.0.0
*/
abstract class Map
{
Expand All @@ -16,4 +16,4 @@ abstract class Map

public const DEFAULT = 'common';
public const GOST_7_79_2000 = 'GOST_7.79.2000';
}
}
4 changes: 1 addition & 3 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
* Class ServiceProvider.
*
* @author Eugene Dzhumak <[email protected]>
*
* @version 2.0.0
*/
class ServiceProvider extends BaseServiceProvider
{
Expand All @@ -34,7 +32,7 @@ public function register()

$this->mergeConfigFrom($configPath, 'transliterate');

$this->app->bind('Transliteration', function ($app) {
$this->app->bind('Transliterator', function ($app) {
return new Transliterator();
});
}
Expand Down
2 changes: 0 additions & 2 deletions src/Transformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
* Class Transformer.
*
* @author Eugene Dzhumak <[email protected]>
*
* @version 1.0.0
*/
final class Transformer
{
Expand Down
19 changes: 12 additions & 7 deletions src/Transliterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@
* Feel free to change it.
* Either by pull request or forking.
*
* Class Transliteration
* Class Transliterator
*
* @author Eugene Dzhumak <[email protected]>
*
* @version 2.0.0
*/
class Transliterator
{
Expand All @@ -34,7 +32,10 @@ public function __construct(string $lang = null, string $map = null)
}

/**
* @param string $lang
* Change transliterating text language.
*
* @param string $lang One of the Map::LANG_* constants or custom language.
*
* @return Transliterator
*/
public function from(string $lang): self
Expand All @@ -45,7 +46,10 @@ public function from(string $lang): self
}

/**
* @param string $map
* Change transliteration map
*
* @param string $map Name of the transliteration map.
*
* @return Transliterator
*/
public function useMap(string $map): self
Expand All @@ -67,7 +71,7 @@ public function make(string $text): string
$map = $this->getMap();
$transliterated = str_replace(array_keys($map), array_values($map), $text);

if (config('transliterate.remove_accents', false) === true) {
if (true === config('transliterate.remove_accents', false)) {
$transliterator = IntlTransliterator::create('Any-Latin; Latin-ASCII');
$transliterated = $transliterator->transliterate($transliterated);
}
Expand All @@ -79,6 +83,7 @@ public function make(string $text): string
* Create a slug by converting and removing all non-ascii characters.
*
* @param string $text
*
* @return string
*/
public function slugify(string $text): string
Expand Down Expand Up @@ -116,7 +121,7 @@ private function getMap(): array
throw new \InvalidArgumentException("The transliteration map '${path}' doesn't exist");
}

/** @noinspection PhpIncludeInspection */
/* @noinspection PhpIncludeInspection */
return require $path;
}

Expand Down
14 changes: 8 additions & 6 deletions src/config/transliterate.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use ElForastero\Transliterate\Map;

/** @noinspection PhpVoidFunctionResultUsedInspection */
return [
/*
Expand All @@ -8,20 +10,20 @@
|--------------------------------------------------------------------------
|
| This option specifies the transliteration map that will be used by default
| if no explicit one will be provided during Transliteration::make() call.
| if no another one will be provided during Transliteration::make() call.
|
*/
'default_map' => 'common',
'default_map' => Map::DEFAULT,

/*
|--------------------------------------------------------------------------
| Set default language
|--------------------------------------------------------------------------
| Language of transliterating text. Will be used unless no explicitly
| provided into Transliteration::from().
| The language of transliterating text.
| Will be used unless no explicitly provided.
|
*/
'default_lang' => 'ru',
'default_lang' => Map::LANG_RU,

/*
|--------------------------------------------------------------------------
Expand Down Expand Up @@ -61,7 +63,7 @@
|--------------------------------------------------------------------------
|
| Remove accents from letters using ICU rules.
| E.g. À, Ä, Â, etc. all become A.
| E.g. À, Ä, Â, etc. - all become A.
|
*/
'remove_accents' => true,
Expand Down
4 changes: 3 additions & 1 deletion src/maps/ru/GOST_7.79.2000.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php

/**
* Transliteration by ГОСТ 7.79-2000.
* Transliteration by GOST 7.79-2000.
*
* @see https://en.wikipedia.org/wiki/Romanization_of_Russian
*/
return [
'ж' => 'zh',
Expand Down
2 changes: 2 additions & 0 deletions src/maps/uk/common.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

/**
* Transliteration with commonly used map.
*
* @see https://en.wikipedia.org/wiki/Romanization_of_Ukrainian
*/
return [
'ж' => 'zh',
Expand Down
4 changes: 2 additions & 2 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ class TestCase extends \Orchestra\Testbench\TestCase
{
protected function getEnvironmentSetUp($app)
{
$config = require dirname(__DIR__) . '/src/config/transliterate.php';
$config = require dirname(__DIR__).'/src/config/transliterate.php';
$app['config']->set('transliterate', $config);

Transformer::override([
\Closure::fromCallable('trim'),
]);
}
}
}
4 changes: 2 additions & 2 deletions tests/TransformersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ protected function getEnvironmentSetUp($app)
public function testTransformers()
{
$initialString = ' Строка с пробелами ';
$transliterator = (new Transliterator)->from('ru')->useMap('common');
$transliterator = (new Transliterator())->from('ru')->useMap('common');

$this->assertEquals(
strtoupper(trim(' Stroka s probelami ')),
$transliterator->make($initialString)
);
}
}
}
4 changes: 2 additions & 2 deletions tests/TransliterationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ protected function getEnvironmentSetUp($app)

$app['config']->set('transliterate.custom_maps', [
'ru' => [
'test' => __DIR__ . '/fixtures/maps/test.php',
'test' => __DIR__.'/fixtures/maps/test.php',
],
]);
}
Expand All @@ -36,7 +36,7 @@ public function testSlugify()
$initialString = ' Съешь еще этих мягких французских булок, да выпей чаю! & 123';
$expectedString = 'sesh-eshhe-etih-myagkih-francuzskih-bulok-da-vipey-chayu-and-123';

$this->assertEquals($expectedString, (new Transliterator)->slugify($initialString));
$this->assertEquals($expectedString, (new Transliterator())->slugify($initialString));
}

public function testCustomMap()
Expand Down

0 comments on commit 5cb7506

Please sign in to comment.