Skip to content

Extract the EmojiTransliterator to a dedicated package #49947

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/package-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:

- name: Find packages
id: find-packages
run: echo "packages=$(php .github/get-modified-packages.php $(find src/Symfony -mindepth 2 -type f -name composer.json -printf '%h\n' | grep -v src/Symfony/Component/Intl/Resources/emoji |jq -R -s -c 'split("\n")[:-1]') $(git diff --name-only origin/${{ github.base_ref }} HEAD | grep src/ | jq -R -s -c 'split("\n")[:-1]'))" >> $GITHUB_OUTPUT
run: echo "packages=$(php .github/get-modified-packages.php $(find src/Symfony -mindepth 2 -type f -name composer.json -printf '%h\n' | grep -v src/Symfony/Component/EmojiTransliterator/Resources/emoji |jq -R -s -c 'split("\n")[:-1]') $(git diff --name-only origin/${{ github.base_ref }} HEAD | grep src/ | jq -R -s -c 'split("\n")[:-1]'))" >> $GITHUB_OUTPUT

- name: Verify meta files are correct
run: |
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ jobs:
echo SYMFONY_DEPRECATIONS_HELPER=weak >> $GITHUB_ENV
cp composer.json composer.json.orig
echo -e '{\n"require":{'"$(grep phpunit-bridge composer.json)"'"php":"*"},"minimum-stability":"dev"}' > composer.json
php .github/build-packages.php HEAD^ $SYMFONY_VERSION $(find src/Symfony -mindepth 2 -type f -name composer.json -printf '%h\n' | grep -v src/Symfony/Component/Intl/Resources/emoji)
php .github/build-packages.php HEAD^ $SYMFONY_VERSION $(find src/Symfony -mindepth 2 -type f -name composer.json -printf '%h\n' | grep -v src/Symfony/Component/EmojiTransliterator/Resources/emoji)
mv composer.json composer.json.phpunit
mv composer.json.orig composer.json
fi
Expand Down
1 change: 1 addition & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
'Symfony/Bundle/FrameworkBundle/Resources/views/Form',
// explicit trigger_error tests
'Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/',
'Symfony/Component/EmojiTransliterator/Resources/data/',
'Symfony/Component/Intl/Resources/data/',
])
// Support for older PHPunit version
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"symfony/doctrine-bridge": "self.version",
"symfony/dom-crawler": "self.version",
"symfony/dotenv": "self.version",
"symfony/emoji-transliterator": "self.version",
"symfony/error-handler": "self.version",
"symfony/event-dispatcher": "self.version",
"symfony/expression-language": "self.version",
Expand Down
2 changes: 1 addition & 1 deletion psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<directory name="src/Symfony/*/*/Tests" />
<directory name="src/Symfony/*/*/*/Tests" />
<directory name="src/Symfony/*/*/*/*/Tests" />
<directory name="src/Symfony/Component/Intl/Resources/emoji/" />
<directory name="src/Symfony/Component/EmojiTransliterator/Resources/emoji/" />
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/EmojiTransliterator/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/Resources/emoji export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/EmojiTransliterator/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
8 changes: 8 additions & 0 deletions src/Symfony/Component/EmojiTransliterator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CHANGELOG
=========

6.3
---

* Extract the component from `symfony/intl`
* Add the special `strip` locale to `EmojiTransliterator` to strip all emojis from a string
166 changes: 166 additions & 0 deletions src/Symfony/Component/EmojiTransliterator/EmojiTransliterator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\EmojiTransliterator;

// TODO add a composer requirement in 7.0 instead
if (!class_exists(\Transliterator::class)) {
throw new \LogicException(sprintf('You cannot use the "%s\EmojiTransliterator" class as the "intl" extension is not installed. See https://php.net/intl.', __NAMESPACE__));
} else {
/**
* @internal
*/
trait EmojiTransliteratorTrait
{
private array $map;
private \Transliterator $transliterator;

public static function create(string $id, int $direction = self::FORWARD): self
{
$id = strtolower($id);

if (!isset(self::REVERSEABLE_IDS[$id]) && !str_starts_with($id, 'emoji-')) {
$id = 'emoji-'.$id;
}

if (self::REVERSE === $direction) {
if (!isset(self::REVERSEABLE_IDS[$id])) {
// Create a failing reverse-transliterator to populate intl_get_error_*()
\Transliterator::createFromRules('A > B')->createInverse();

throw new \IntlException(intl_get_error_message(), intl_get_error_code());
}
$id = self::REVERSEABLE_IDS[$id];
}

if (!preg_match('/^[a-z0-9@_\\.\\-]*$/', $id) || !is_file(__DIR__."/Resources/data/{$id}.php")) {
\Transliterator::create($id); // Populate intl_get_error_*()

throw new \IntlException(intl_get_error_message(), intl_get_error_code());
}

static $maps;

// TODO switch the code to use self::class instead of static::class once the class is actually final in Symfony 7.0
// Create an instance of \Transliterator with a custom id; that's the only way
if (\PHP_VERSION_ID >= 80200) {
static $newInstance;
$instance = ($newInstance ??= (new \ReflectionClass(static::class))->newInstanceWithoutConstructor(...))();
$instance->id = $id;
} else {
$instance = unserialize(sprintf('O:%d:"%s":1:{s:2:"id";s:%d:"%s";}', \strlen(static::class), static::class, \strlen($id), $id));
}

$instance->map = $maps[$id] ??= require __DIR__."/Resources/data/{$id}.php";

return $instance;
}

public function createInverse(): self
{
return self::create($this->id, self::REVERSE);
}

public function getErrorCode(): int|false
{
return $this->transliterator?->getErrorCode() ?? 0;
}

public function getErrorMessage(): string|false
{
return $this->transliterator?->getErrorMessage() ?? false;
}

public static function listIDs(): array
{
static $ids = [];

if ($ids) {
return $ids;
}

foreach (scandir(__DIR__.'/Resources/data/') as $file) {
if (str_ends_with($file, '.php')) {
$ids[] = substr($file, 0, -4);
}
}

return $ids;
}

public function transliterate(string $string, int $start = 0, int $end = -1): string|false
{
$quickCheck = ':' === array_key_first($this->map)[0] ? ':' : self::QUICK_CHECK;

if (0 === $start && -1 === $end && preg_match('//u', $string)) {
return \strlen($string) === strcspn($string, $quickCheck) ? $string : strtr($string, $this->map);
}

// Here we rely on intl to validate the $string, $start and $end arguments
// and to slice the string. Slicing is done by replacing the part if $string
// between $start and $end by a unique cookie that can be reliably used to
// identify which part of $string should be transliterated.

static $cookie;
static $transliterator;

$cookie ??= hash('xxh128', random_bytes(8));
$this->transliterator ??= clone $transliterator ??= \Transliterator::createFromRules('[:any:]* > '.$cookie);

if (false === $result = $this->transliterator->transliterate($string, $start, $end)) {
return false;
}

$parts = explode($cookie, $result);
$start = \strlen($parts[0]);
$length = -\strlen($parts[1]) ?: null;
$string = substr($string, $start, $length);

return $parts[0].(\strlen($string) === strcspn($string, $quickCheck) ? $string : strtr($string, $this->map)).$parts[1];
}
}
}

if (\PHP_VERSION_ID >= 80200) {
/**
* @final since 6.3
*/
class EmojiTransliterator extends \Transliterator
{
use EmojiTransliteratorTrait;

private const QUICK_CHECK = "\xA9\xAE\xE2\xE3\xF0";
private const REVERSEABLE_IDS = [
'emoji-github' => 'github-emoji',
'emoji-slack' => 'slack-emoji',
'github-emoji' => 'emoji-github',
'slack-emoji' => 'emoji-slack',
];

public readonly string $id;
}
} else {
/**
* @final since 6.3
*/
class EmojiTransliterator extends \Transliterator
{
use EmojiTransliteratorTrait;

private const QUICK_CHECK = "\xA9\xAE\xE2\xE3\xF0";
private const REVERSEABLE_IDS = [
'emoji-github' => 'github-emoji',
'emoji-slack' => 'slack-emoji',
'github-emoji' => 'emoji-github',
'slack-emoji' => 'emoji-slack',
];
}
}
19 changes: 19 additions & 0 deletions src/Symfony/Component/EmojiTransliterator/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2023-present Fabien Potencier

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.
14 changes: 14 additions & 0 deletions src/Symfony/Component/EmojiTransliterator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
EmojiTransliterator Component
=============================

The EmojiTransliterator component provides an ext-intl Transliterator that can
transliterate emojis to ASCII.

Resources
---------

* [Documentation](https://symfony.com/doc/current/components/emoji_transliterator.html)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

final class Builder
{
private const TARGET_DIR = __DIR__.'/../data/transliterator/emoji/';
private const TARGET_DIR = __DIR__.'/../data/';

public static function getEmojisCodePoints(): array
{
Expand Down
Loading