GithubHelp home page GithubHelp logo

contributte / translation Goto Github PK

View Code? Open in Web Editor NEW
71.0 11.0 30.0 543 KB

:tongue: Translations (symfony/translation) to Nette Framework (@nette)

Home Page: https://contributte.org/packages/contributte/translation.html

License: MIT License

PHP 99.28% Makefile 0.72%
contributte nette-framework translation symfony localization l10n i18n

translation's Introduction

Website 🚀 contributte.org | Contact 👨🏻‍💻 f3l1x.io | Twitter 🐦 @contributte

Usage

To install the latest version of contributte/translation use Composer.

composer require contributte/translation

Documentation

For details on how to use this package, check out our documentation.

Versions

State Version Branch PHP Symfony
stable ^2.0.0 master ^8.0 ^6.0|^7.0
stable ^1.0.0 php74_symfony5 ^7.4|^8.0 ^5.0

Development

See how to contribute to this package.

This package is currently maintaining by these authors.


Consider to support contributte development team. Also thank you for using this package.

translation's People

Contributors

adaamz avatar aleswita avatar emololftw avatar f3l1x avatar gappa avatar jiripudil avatar juniwalk avatar kubomikita avatar martinbohmcz avatar martinmystikjonas avatar matak avatar maxxa avatar petrparolek avatar radimvaculik avatar rixafy avatar roman3349 avatar solcik avatar spaze avatar thorewi avatar vitkutny avatar zeleznypa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

translation's Issues

"Live" config instead of Neon?

Hi, is there a way to config extension based on my db data instead of neon config?

What I mean - I have languages saved in DB and it´s possible to turn them on/off, but if config stays static from Neon file, it bugs out... Like if u turn off EN language, keep only CS, but config has whitelisted CS, EN, it keeps spamming errors for undefined EN from robot (etc.) access, because of language detection that thinks the EN lang is available. If I remove EN from whitelist, it fallbacks to CS and everything is ok.

DB - untranslated text

Hello, can you help me?
Doctrine 2 loading

I would like use this: When translator detect untranslated text, the code automaticaly create new db insert locale: message: "key.from.translate." and i can create easy code to find untranslated text in DB and translate it

And question - Where i cant catch unstranslated text?

<button> element in forms is not translated properly

When I use <button> element instead of <input>, it translates value parameter instead of the body of the button:

presenter:

$form->setTranslator($this->translator->createPrefixedTranslator('admin.myForm'));
$form->addSubmit('sub', 'update');

latte:

<input n:name="sub"> // generates <input type="submit" name="sub" value="Aktualizovat">

<button n:name="sub" /> // generates <button type="submit" name="sub" value="Aktualizovat">update</button>

PrefixedTranslator not working in forms after update to 0.9.x

When I updated to version 0.9.x, translations stopped being translated in forms with PrefixedTranslator.

The translation is in NEON file called admin.cs_CZ.neon and the form in latte is located inside {translator admin.domain} tag.

admin.cs_CZ.neon:

domain:
   myForm:
      sub: "Odeslat"

Form translator is defined this way:

$form->setTranslator($this->translator->createPrefixedTranslator('myForm'));

Works in 0.8.x. In 0.9.x it prints only the key sub.

Fallback locales list always contains extension default value

As of v0.7.0 the DI extension defines ['en_US'] as a default value for translation.locales.fallback.

Due to this issue / behavior of nette/schema, the default value is always present in the configured list of fallback locales. This is unwanted behavior as applications without en_US locale should never have it as a fallback.

Maybe fe0fae7 could be reverted to the previous implementation?

getDefaultLocale() and getLocale()

At Kdyby/Translator there were these two methots - getDefaultLocale() and getLocale().
I am using it, but i can not figure out how to get these variables now.

Thank you!

Chybějící překlady

Chci se zeptat, jak by jste optimálně řešili vytažení chybějících překladů, nyní by asi nebyl problém např. udělat funkci v translatoru, která by dávala chybějící překlady do tracy panelu + někam do pole v té třídě a následně to nějak vytáhnout nebo by jste měli jiné řešení ?

Díky

1.0.0 release, but tag says 0.9.4

Hi,

I've noticed that 1.0.0 has been released, w00t!

Not sure this is intentional but it seems that it's still tagged as 0.9.4:
chrome_2022-02-15_01-38-09
(the diff link doesn't work)

Because of the 0.9.4 tag, composer thinks this is a patch/minor release:
image

If not intentional, do you think you can create a new tag and edit the release so it's using the new tag if possible?

Always shows Czech translation even on `/en/` version of the site

Everything was working as it should, the default locale was en and you could change to cs or ru by redirecting to site.com/en or site.com/ru.

But today I needed to update some Nette packages and I foolishly ran composer update which updated everything including some translation packages:

  - Upgrading symfony/translation-contracts (v2.3.0 => v2.5.1): Extracting archive
  - Upgrading symfony/translation (v5.2.3 => v5.4.9): Extracting archive
  - ...

And now everything is in Czech, no matter what language I select. Also after checking Tracy, it seems there is some Header listed in Locale resolvers which is always set to cs and is listed last, so I assume it overrides all the resolvers before. What is this Header resolver and how do I get rid of it, so the locales are changed based on the Router parameter again?

Tracy screenshot:

Snímek obrazovky 2022-06-01 v 21 38 53


EDIT: Okay, after further digging, it seems that on every request there is this header Accept-Language: cs-cz, which might be the cause of the problem. Why it didn't matter before is beyond me - was it even sent before the update?

Anyways, how do I get rid of either the header itself or (preferably) the Header resolver or at least lower its priority below Route parameter?

Latte 3 support

Current version does not support Latte 3.

Is there any work in progress on Latte support already? If not should I try to prepare PR with it?

Config - locales - fallback - default value

Hello,

There is the default value for fallback in the configuration set to en_US on this line:

https://github.com/contributte/translation/blob/master/src/di/TranslationExtension.php#L39

I thought that when I specify my fallback I would overwrite the default one, but it is not the case.

extensions:
    contributte.translation: Contributte\Translation\DI\TranslationExtension

contributte.translation:
    debug: %debugMode%
    locales:
        whitelist: %languages%
        default: %languages.0%
        fallback:
            - cs_CZ
            - cs
    dirs:
        - %rootDir%/src/resources/lang

It got my eye when I was checking the output of cache file. I did not expect en_US to be there at all. There should be only de and cs, but not en.

<?php

use Symfony\Component\Translation\MessageCatalogue;

$catalogue = new MessageCatalogue('de', array ());
$catalogueDe_DE = new MessageCatalogue('de_DE', array ());
$catalogue->addFallbackCatalogue($catalogueDe_DE);
$catalogueEn_US = new MessageCatalogue('en_US', array ());
$catalogueDe_DE->addFallbackCatalogue($catalogueEn_US);
$catalogueCs_CZ = new MessageCatalogue('cs_CZ', array ());
$catalogueEn_US->addFallbackCatalogue($catalogueCs_CZ);
$catalogueCs = new MessageCatalogue('cs', array ());
$catalogueCs_CZ->addFallbackCatalogue($catalogueCs);

return $catalogue;

I debugged it and found out, that it is working as expected since nette\schema is working that way as per https://github.com/nette/schema/blob/master/tests/Schema/Expect.array.phpt#L46

So I suggest removing the default value for the fallback array.

It is not compatible with symfony/translation >=5.0.0

Hey it is not comaptible with symfony/translation >=5.0.0.
image

Same problem is in DatabaseAbstract.

I see two solutions:

  • Drop support for symfony/translation < 5.0.0
  • Remove symfony/translation >=5.0.0 from supported version

how to use it on forms

hi there is no information of how to use on forms by example i have this

locale.en.neon

email_username: "Email / Username"
please_enter_yout_username: "Please enter your username"
remember_me: "Remember me"

form

/** @var Nette\Localization\Translator @inject */
	public $translator;

protected function create()
	{
		$form = new Form;
		$form->setTranslator($this->translator);
               $form->addCheckbox('remember', 'locale.remember_me') // <-- the translate key
		return $form;
	}

on nette form translate says that if i put setTranslator it will auto put the translate parts refer but when it render just print the key, but i cant make that this works with checkbox

Unable to redirect to English version

Hi,
I have a problem when changing the language I expect redirection to the English version according to Routa.

neco.cz/en/

but when redirecting it throws me a 404 error that the page does not exist ..
Screen

What am I doing wrong?

$router->addroute('[<locale=cs cs|en>/]kontakt', 'Contact:default');
        $router->addRoute('[<locale=cs cs|en>/]<action>[/<url>]', [
            'presenter' => [
                Route::VALUE => 'Page'
            ],
            'action' => [
                Route::FILTER_STRICT => true,
                Route::FILTER_TABLE => [
                    'stranky' => 'default',
                    'stranka' => 'detail',
                ],
            ],
        ]);
		$router->addRoute('[<locale=cs cs|en>/]<action>', [
            'presenter' => [
                Route::VALUE => 'User'
            ],
            'action' => [
                Route::FILTER_TABLE => [
                    'profil' => 'default',
                    'prihlaseni' => 'login',
                    'zapomenute-heslo' => 'lostPassword',
                    'odhlasit' => 'logout',
                    'registrace' => 'register'
                ],
            ],
        ]);

		$router->addRoute('[<locale=cs cs|en>/]<presenter>/<action>[/<id>]', 'Homepage:default');

Presenter:

/**
     * @throws Nette\Application\AbortException
     */
    public function handleChangeLocale(): void
    {
        $language = $this->getHttpRequest()->getPost();
        $this->translatorSessionResolver->setLocale($language['language']);
        $this->redirect('this', ['locale' => $language['language']]);
    }

Thx for help

setLocalesWhitelist

Hello, where are settings for setLocalesWhitelist? I Session doesnt return locale value.

Translation of text with spaces is taken from messages.local.neon

I've issue with translation of text with spaces. For example $translator->translate('Kočka leze dírou, pes oknem'); is looking for string "Kočka leze dírou, pes oknem" in default messages.local.neon even if I hade set different domain by $translator->setPrefix(['customModule.status']); I don't know if it is error or behavior by design.

My idea is to replace spaces with underscores in messages, because it's still readable in case of missing translate in neon.
And the best way in my opinion is in Translator.php :

public function translate($message, ...$parameters): string // @comment

{

        $message = str_ireplace(" ","_",$message);


Nice would be if user can set on or off this replacing space by underscore. What do you think?

Wrong DB table example?

In docs, there is this DB table example:

CREATE TABLE `messages` (
    `id` varchar(191) NOT NULL,
    `locale` char(5) NOT NULL,
    `message` varchar(191) NOT NULL,
    UNIQUE KEY `id` (`id`),
    KEY `locale` (`locale`),
    KEY `message` (`message`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

But maybe the UNIQUE KEY should be multi-column (id, locale)? This example would work for only one language.

Also, why the varchars are set to exactly 191 chars?

Locale cannot be changed during request?

Hello, I have a CLI script that sends e-mails to users. Each user obviously can have a different preferred locale.

I am using the $localeResolver->setLocale() trick.

But each e-mail sent is translated according to the first e-mails locale of the batch.

I tried to debug a little and it looks like although i call setLocale many times, the resolve function is called only once.

I cannot workaround the problem by calling trans with optional locale argument. I need the translation to work in latte.

How to disable translate not existing translations?

For example

$form->addSelect("email", $emails)

obviously there is no emails translations, but translator automatically expect that info@example is domain and cz is message, so finally is rendered only CZ word.

Thats very strange behaviour, how to disable it? I know that you can use NoTranslate element, but it is impossible to fix all these places.

translate fails on object message

Thanks for the quick fix of #2. I encountered another issue related to that:

Translator::translate accepts mixed message arguments. With Kdyby\Translation, we could use Nette\Utils\Html, which was useful since it allowed us to avoid double translation of strings we wanted to pass to method:

$form->addError(Html::el()->setText($this->translator->translate('messages.team.error.too_few_members', $minMembers, ['category' => $category])));

In this case, we can just do addError(…, false) but in other cases like Control caption, this is not possible so we rely on null HTML element.

However, Contributte\Translation fails when object is passed to translate method:

Argument 1 passed to Contributte\Translation\Helpers::extractMessage() must be of the type string or null, object given, called in …/vendor/contributte/translation/src/Translator.php on line 345

(Before 0.2.1, it failed the same way as #2; now the failure has been moved few lines down to extractMessage.)

What should translating object do?

In Nette 2.x there were no typehints in ITranslator::translate so Kdyby\Translation could get away with returning the original object:

https://github.com/Kdyby/Translation/blob/6b0721c767a7be7f15b2fb13c529bea8536230aa/src/Translator.php#L147-L149

Now that it expects to return string, we do not have many sensible choices for semantics:

  • stringify the object if it has __toString method, and return the result
  • stringify and translate
  • print the class name https://github.com/nette/forms/blob/v3.0.0/tests/Forms/Controls.translate().phpt#L20 🤡
  • throw an exception
  • add NoTranslate class that would be stringified and other classes would be handled in one of the aforementioned ways (exception)
  • do nothing, users can create Translator subclass and override translate method that handles NoTranslate class
  • allow users to hook into translator and override object handling

Translation empty string

Hello,

if you are trying to translate an empty string "", an error is displayed in Tracy because the translation does not exist.

When trying to translate an empty string, it would be better to return an empty string.

Thx

Translator returns untranslated message even though the translation exists

In the situation when the translation is not available in the default locale but exists in the requested locale, translator returns an untranslated message (if returnOriginalMessage=true). I think it's caused by this change e78977e#diff-eacdee021952408874fa89f5f706adcbc864deb46dc1b18bfb042beaad944b85R345

Shouldn't we pass the $locale parameter to the getCatalogue() call in the translation existence check to use the catalogue of the requested locale?

neon loader does not work until specified in translation.loaders

The documentation says By default the extension will look for .neon files..

But, unless you specify loaders in config.neon (translation.loaders), no resources are loaded. As soon as I define any other loader - in my case the other loader was YAML - loaders work as expected.

In other words:

Setting which loaded no resource

translation:
	locales:
		whitelist: [en, cs]
		default: cs
		fallback: [cs]
	dirs:
		- %appDir%/locale
		- %appDir%/FrontModule/locale
	localeResolvers:
		- Contributte\Translation\LocalesResolvers\Router

Setting which loaded NEON and YAML files

translation:
	locales:
		whitelist: [en, cs]
		default: cs
		fallback: [cs]
	dirs:
		- %appDir%/locale
		- %appDir%/FrontModule/locale
	loaders:
		yml: Symfony\Component\Translation\Loader\YamlFileLoader
	localeResolvers:
		- Contributte\Translation\LocalesResolvers\Router

In my opinion, no code changes are required. Only a slight modification of the docs saying that the required config for this component contains at least this:

translation:
	loaders:
		neon: Contributte\Translation\Loaders\Neon

Nelze volat DI Translator

Chtěl bych se zeptat, proč nejde volat třída Translator globálně stejně jako u Kdyby viz chyba ?

Service of type Contributte\Translation\Translator needed by $translator in __construct() not found. Did you register it in configuration file?

Neměla by být dostupná po zavolání rozšíření v config.neon ?

Druhá věc je, že tu vůbec není v dokumentaci vysvětleno, jak si třeba udělat rozšíření přímo na DB nikoliv podle souboru, což díky Translatoru v Kdyby bylo možné.

Díky

Can't set config option localeResolvers

When I set localeResolvers option in config.neon, I see this error:

Service 'translation.localeResolverRouter' has already been added.

My full config:

extensions:
    translation: Contributte\Translation\DI\TranslationExtension

translation:
    locales:
        whitelist: [cs, en]
        default: cs
        fallback: [en]
    dirs:
        - %appDir%/Lang
    localeResolvers:
        - Contributte\Translation\LocalesResolvers\Router
        - Contributte\Translation\LocalesResolvers\Parameter

Unsupported returnOriginalMessage

Hi,

when I put returnOriginalMessage: true into configuration file, I get an exception:

Nette\DI\InvalidConfigurationException

Unexpected item 'translation › returnOriginalMessage'.

Is this configuration value still valid?

Thank you for any feedback.

skyo

Version of packages:

chillerlan/php-qrcode             4.3.2     A QR code generator. PHP 7.4+
chillerlan/php-settings-container 2.1.2     A container class for immutable...
contributte/application           v0.5.1    Extra contrib to nette/application
contributte/translation           v0.8.3    Symfony/Translation integration...
firebase/php-jwt                  v5.5.1    A simple library to encode and ...
guzzlehttp/guzzle                 7.4.1     Guzzle is a PHP HTTP client lib...
guzzlehttp/promises               1.5.1     Guzzle promises library
guzzlehttp/psr7                   2.1.0     PSR-7 message implementation th...
james-heinrich/getid3             v1.9.21   PHP script that extracts useful...
latte/latte                       v2.10.7   ☕ Latte: the intuitive and fa...
league/oauth2-client              2.6.1     OAuth 2.0 Client Library
nette/application                 v3.1.5    🏆 Nette Application: a full-...
nette/bootstrap                   v3.1.2    🅱  Nette Bootstrap: the simp...
nette/caching                     v3.1.2    ⏱ Nette Caching: library with...
nette/component-model             v3.0.2    ⚛ Nette Component Model
nette/database                    v3.1.4    💾 Nette Database: layer with...
nette/di                          v3.0.12   💎 Nette Dependency Injection...
nette/finder                      v2.5.3    🔍 Nette Finder: find files a...
nette/forms                       v3.1.6    📝 Nette Forms: generating, v...
nette/http                        v3.1.5    🌐 Nette Http: abstraction fo...
nette/mail                        v3.1.8    📧 Nette Mail: handy email cr...
nette/neon                        v3.3.2    🍸 Nette NEON: encodes and de...
nette/php-generator               v3.6.5    🐘 Nette PHP Generator: gener...
nette/robot-loader                v3.4.1    🍀 Nette RobotLoader: high pe...
nette/routing                     v3.0.2    Nette Routing: two-ways URL con...
nette/schema                      v1.2.2    📐 Nette Schema: validating d...
nette/security                    v3.1.5    🔑 Nette Security: provides a...
nette/tester                      v2.4.1    Nette Tester: enjoyable unit te...
nette/utils                       v3.2.6    🛠  Nette Utils: lightweight ...
paragonie/random_compat           v9.99.100 PHP 5.x polyfill for random_byt...
psr/http-client                   1.0.1     Common interface for HTTP clients
psr/http-factory                  1.0.1     Common interfaces for PSR-7 HTT...
psr/http-message                  1.0.1     Common interface for HTTP messages
ralouphie/getallheaders           3.0.3     A polyfill for getallheaders.
symfony/config                    v5.4.0    Helps you find, load, combine, ...
symfony/deprecation-contracts     v3.0.0    A generic function and conventi...
symfony/filesystem                v6.0.0    Provides basic utilities for th...
symfony/polyfill-ctype            v1.23.0   Symfony polyfill for ctype func...
symfony/polyfill-intl-grapheme    v1.23.1   Symfony polyfill for intl's gra...
symfony/polyfill-intl-normalizer  v1.23.0   Symfony polyfill for intl's Nor...
symfony/polyfill-mbstring         v1.23.1   Symfony polyfill for the Mbstri...
symfony/polyfill-php80            v1.23.1   Symfony polyfill backporting so...
symfony/polyfill-php81            v1.23.0   Symfony polyfill backporting so...
symfony/property-access           v5.4.0    Provides functions to read and ...
symfony/property-info             v6.0.0    Extracts information about PHP ...
symfony/string                    v6.0.1    Provides an object-oriented API...
symfony/translation               v4.4.26   Provides tools to international...
symfony/translation-contracts     v2.5.0    Generic abstractions related to...
thenetworg/oauth2-azure           v2.0.1    Azure Active Directory OAuth 2....
tracy/tracy                       v2.9.0    😎  Tracy: the addictive tool...
ublaboo/datagrid                  v6.9.2    DataGrid for Nette Framework: f...

Expose Symfony's TranslatorInterface?

Hi there, I am working on contributte/validator and one of its features is the translation of constraint violation messages via Symfony/Translation. I'd like to autowire the translator if it exists in the container, but Symfony's ValidatorBuilder only requires the translator to implement Symfony\Contracts\Translation\TranslatorInterface — which is logical from its viewpoint.

However, the Translator service as registered here is only autowire-able by Nette's ITranslator interface, as discussed in #4. Could you please make it autowire-able by Symfony's TranslatorInterface as well? That would be a quick fix and would allow the integration of this package and contributte/validator to work out-of-the-box.

Thanks for your consideration!

Possibility to change format of translation key

Will it be possible please to use a separate function to assemble translation key?

$tmp['%' . $k1 . '%'] = $v1;

Currently the translation key have format %key%, but for example Laravel use the format :key.

When the DevStack consist some parts, that expect different format, it will be useful to have possibility to unify the format across the project.

To solve this now I have to overload whole translate function with all other logic.

BC breaks in the 0.9 branch

After upgrading to the 0.9 branch, strange things started happening.

We used the following notation:

{foreach $messages as $message}
    <div class="alert alert-{$message->getType()->getValue()}">
        {_$message->getContent()}
    </div>
{/foreach}

Where $message is an object with the getContent() method returning string|Contributte\Translation\Wrappers\Message.

Since version 0.9 I started to get an error
Call to a member function getContent() on string
at echo LR\Filters::escapeHtmlText(call_user_func($this->filters->translate, $message . $message->getContent()));

The problem is that my $message variable is overwritten by the extension's internal code using the same variable name.

If I rename the variable, e.g. to $messageA, a related problem occurs.

Object of class Contributte\Translation\Wrappers\Message could not be converted to string at
echo LR\Filters::escapeHtmlText(call_user_func($this->filters->translate, $message . $messageA->getContent()));

In this case (I believe, but it may not be true) the newly added concat with the $message variable is to blame since Contributte\Translation\Wrappers\Message does not have a __toString magic method. Or does it mean that now it is not possible to use Contributte\Translation\Wrappers\Message objects in latte macros?

if I downgrade the library to the 0.8.3 version the everything works fine.

Question about cyrillic

I have simple question sorry for created issue.
Is supported cyrillic ? Because i want create russian translate in my project.

Thanks for your answer.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.