Coder Social home page Coder Social logo

amiranagram / localizator Goto Github PK

View Code? Open in Web Editor NEW
220.0 4.0 28.0 264 KB

Scan your Laravel project and generate language files ready to translate in language(s) of choosing.

License: Other

PHP 100.00%
laravel php laravel-package i18n locale locales-translation

localizator's Introduction

Localizator

Latest Version on Packagist Total Downloads GitHub Tests Action Status GitHub Code Style Action Status

Localizator is a small tool for Laravel that gives you the ability to extract untranslated string from your project files with one command.

Support

Buy Me A Coffee

DigitalOcean Referral Badge

Compatibility

Laravel Localizator
6.x LTS 0.3-0.12
8.x *
9.x ^0.8
10.x ^0.12
11.x ^0.13

Installation

You can install the package via composer:

composer require --dev amirami/localizator

This package makes use of Laravels package auto-discovery mechanism, which means if you don't install dev dependencies in production, it also won't be loaded.

If for some reason you want manually control this:

  • add the package to the extra.laravel.dont-discover key in composer.json, e.g.
    "extra": {
      "laravel": {
        "dont-discover": [
          "amirami/localizator"
        ]
      }
    }
  • Add the following class to the providers array in config/app.php:
    Amirami\Localizator\ServiceProvider::class,
    If you want to manually load it only in non-production environments, instead you can add this to your AppServiceProvider with the register() method:
    public function register()
    {
        if ($this->app->isLocal()) {
            $this->app->register(\Amirami\Localizator\ServiceProvider::class);
        }
        // ...
    }

Note: Avoid caching the configuration in your development environment, it may cause issues after installing this package; respectively clear the cache beforehand via php artisan cache:clear if you encounter problems when running the commands

You can publish the config file with:

php artisan vendor:publish --provider="Amirami\Localizator\ServiceProvider" --tag="config"

This is the contents of the published config file:

<?php

return [

    /**
     * Localize types of translation strings.
     */
    'localize' => [
        /**
         * Short keys. This is the default for Laravel.
         * They are stored in PHP files inside folders name by their locale code.
         * Laravel comes with default: auth.php, pagination.php, passwords.php and validation.php
         */
        'default' => true,

        /**
         * Translations strings as key.
         * They are stored in JSON file for each locale.
         */
        'json'    => true,
    ],

    /**
     * Search criteria for files.
     */
    'search'   => [
        /**
         * Directories which should be looked inside.
         */
        'dirs'      => ['resources/views'],
        
        /**
         * Subdirectories which will be excluded.
         * The values must be relative to the included directory paths.
         */
        'exclude' => [
            //
        ],

        /**
         * Patterns by which files should be queried.
         * The values can be a regular expression, glob, or just a string.
         */
        'patterns'  => ['*.php'],

        /**
         * Functions that the strings will be extracted from.
         * Add here any custom defined functions.
         * NOTE: The translation string should always be the first argument.
         */
        'functions' => ['__', 'trans', '@lang']
    ],

    /**
     * Should the localize command sort extracted strings alphabetically?
     */
    'sort'     => true,

];

Usage

To extract all the strings, it's as simple as running:

php artisan localize de,fr

This command will create (if don't exist) de.json and fr.json files inside the resources/lang directory. If you have short keys enabled and used in your files (e.g. pagination.next) the localize command will create folders de and fr inside resources/lang directory and PHP files inside by the short key's prefix (e.g. pagination.php).

You can also run the artisan command without the country code arguments.

php artisan localize

In this case translation strings will be generated for the language specified in app.locale config.

Note: Strings you have already translated will not be overwritten.

Remove Missing Keys

By default, the strings inside the locale files will be preserved even if they are not present the next time you run the localize command. If you want to remove those keys that are not present in your files anymore you can append the --remove-missing option to the localize command.

php artisan localize --remove-missing

Key Sorting

By default, the strings generated inside those JSON files will be sorted alphabetically by their keys. If you wanna turn off this feature just set sort => false in the config file.

Searching

The way the strings are being extracted is simple.

We are looking inside the directories defined in search.dirs config, we match the files using patterns defined in search.patterns, and finally we look to extract strings which are the first argument of the functions defined in search.functions.

You are free to change any of these values inside the config file to suit you own needs.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

localizator's People

Contributors

amiranagram avatar asbiin avatar filip-nifti avatar musmanikram avatar rexlmanu avatar victorybiz 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  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

localizator's Issues

Integration in CI

Description

First of all, thanks a lot for this package, it saved me tons of time!

I was wondering if the command could be used on a CI, and would fail (e.g. return a non 0 code) if it finds new keys to translate, without adding them.

Proposal

The command signature could be (to discuss):

php artisan localize fr --dry-run --ci

--dry-run would instruct it to return the number of untranslated terms found by comparing what is already inside json/php files, and what the command was about to add. So the command will not really add the terms, just show what it is about to add.

--ci would return a non 0 code if some translations have been added (if not using in pair with --dry-run), or if some translations would have been added (if used with --dry-run). In this case we could prevent deploying in production pages not fully translated (at least I would use it all the times).

Notes

I could give it a try if you find this feature useful to add to the package.

JS Support

Hey, I used this package also for inertiajs with the https://github.com/xiCO2k/laravel-vue-i18n package.

I added $t to the pattern and it works but the regex don't check for examples like this:

$t(
     'some random translatable message'
)

I adjusted the regex and asking if I should make pr with that, if you planned support for js?

Ignore dot separated word/acronym

Hi. I have encoutered an issue with dot separated word/acronym. For example, @lang('F.A.Q') will generate a F.php file.

/* F.php */

<?php

return [
    'A' => [
        'Q' => '',
    ],
];

Since Laravel use dot syntax to map the language files. How do I ignore this specific word from being outputted as a file?

Vuejs and $t

Hello,

I'm using the laravel-vue-i18n package.

I put my configuration file like this :

'search' => [
        /**
         * Directories which should be looked inside.
         */
        'dirs' => [
            'app',
            'resources',
            'routes',
        ],

        /**
         * Subdirectories which will be excluded.
         * The values must be relative to the included directory paths.
         */
        'exclude' => [
            'vendor/cookie-consent',
        ],

        /**
         * Patterns by which files should be queried.
         * The values can be a regular expression, glob, or just a string.
         */
        'patterns' => ['*.php', '*.vue'],

        /**
         * Functions that the strings will be extracted from.
         * Add here any custom defined functions.
         * NOTE: The translation string should always be the first argument.
         */
        'functions' => ['__', 'trans', '@lang', 'trans_choice', '$t']
    ],

And yet, it doesn't bring out the values in me, such as:
<label for="new-message" class="form-label">{{ $t('Add a new message for this travel') }} :</label>

I also had to ignore the spatie/laravel-cookie-consent package because it crashes due to the following strings:
{!! trans('cookie-consent::texts.message') !!}

Thank you for your help

lang folder moved in laravel 9.x

the lang folder is no longer under resources, so the following line in helpers.php is incorrect for laravel 9.x installs.

return resource_path('lang'.($path !== '' ? DIRECTORY_SEPARATOR.$path : ''));

Keep translated strings empty

Excellent package!
A minor change needed, when generating lists for languages other than the default one, keep the translated string empty.

Example

default lang = en
__('Account settings')
en.json
"Account settings": "Account settings",

de.json
"Account settings": "",

instead of

de.json
"Account settings": "Account settings",

Keep "declare" statements on top of file

I have a php-cs-fixer rule that automatically fix my files to add the declare(strict_types=1); directive on top of my files, including translations files (auth.php, validation.php, ...).

The package keeps removing them, when I want to keep them. Is it possible to keep this directive?

Keep Laravel default language when using --remove-missing

Hi thanks for this package, it's pretty great.

Laravel comes with a bunch of messages used at core for validation, auth, pagination, and passwords, we can get a default set of languages using: https://github.com/Laravel-Lang/lang

if we use something like trans("validation.color") and then run

php artisan localize en --remove-missing

the validation.php file will be emptied, this probably can be solved using search.dirs in the config, any idea what the dirs should be? I don't think it would be as easy as that actually. for instance $this->translator->get was used at vendor/laravel/framework/src/Illuminate/Validation/Concerns/FormatsMessages.php

Anyways I think this should be supported by default maybe.

Delete a key that no longer exists

Hello.

Is it possible that the extraction script automatically deletes the keys that no longer exist?

Example: A .blade.php file contained a string 'test'. This string doesn't exist anymore (it has been deleted from balde.php). Is it possible that it is automatically removed from the lang files so that we have a version that is always up to date and does not have a key that no longer exists?

Quotes Being Stripped From "Integer" Keys in PHP Arrays

Hi @musmanikram . Thanks for the great localization package.

For key based translations, when i have this;

'401' => [
        'title' => '401 - Unauthorized',
        'message' => 'Sorry, you are not authorized to view this page.',
    ],

and then run localize it is being converted to this;

401 => [
        'title' => '401 - Unauthorized',
        'message' => 'Sorry, you are not authorized to view this page.',
    ],

Changing string keys into integers causes issues for me with BabelEdit because it requires all keys be strings.

Not sure if it's just a side effect of the key conversion, but the indentation also gets messed up;

    'default' => [
        'title' => 'Error Response',
        'message' => 'Sorry, something went wrong. Please go to the start page.',
    ],
  404 => [
        'title' => '404 - Not Found',
        'message' => 'The requested page could not be found. Please go to the start page.',
    ],
  500 => [
        'title' => '500 - Internal Server Error',
        'message' => 'Please try again later.',
    ],

quotation marks are not escaped if a comma is directly after it in the string

When translating the following test-strings:
{{__('This is a "Test", followed by some text')}}
{{__("This is another \"Test\", followed by more text")}}

They both result in wrong keys. They keys are as follows:
"This is a \"Test": "",
"This is another \"Test": "",

I was about to do a pull request but i cant seem to figure out the regexp rules in the parser... Its not my strong suit....

Anyway here is a link to the regepx rules and tester, would really appreciate some help :)

Default writer not working

Hello,
thank you for this nice package.
in the configuration file i have default=true and when i run the command:

php artisan localize de

In the ressource/lang there is just json file not .php ?

I have missing something ?

Existing nested translations are dropped

When a path-based namespace is used, e.g. {{ __('module/submodule/messages.Test')}} and a file xx/module/submodule/messages.php exists with keys

<?php

return [
	'Test' => 'Test Message',
	'Another' => 'Another Message',
];

After running php artisan localize xx the file is overwritten with empty key values

<?php

return [
	'Test' => '',
	'Another' => '',
];

Installation error

Tried to install with that command:
composer require --dev amirami/localizator
Error:

                                                                                                                                     
  Could not find a version of package amirami/localizator matching your minimum-stability (stable). Require it with an explicit ve   
  rsion constraint allowing its desired stability.                                                                                   
                                                                                                                                     

require [--dev] [--dry-run] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--fixed] [--no-suggest] [--no-progress] [--no-update] [--no-install] [--no-audit] [--audit-format AUDIT-FORMAT] [--update-no-dev] [-w|--update-with-dependencies] [-W|--update-with-all-dependencies] [--with-dependencies] [--with-all-dependencies] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--] [<packages>...]```

Write default php translations to json

I am not sure if this is something others would want to make use of:

Scenario:
To simplify the translation task I want to be able to send a single file to my translator in json format.

  • I have strings throughout the code - these are successfully scanned and added to lang/xx.json (xx is the short code for the target language)
  • I have strings in lang/en/auth.php, lang/en/validation.php etc. - these get exported for translation to lang/xx/auth.php, lang/xx/validation.php etc. - I would like these added to lang/xx.json

Current solution:
I can see from the source code that by overriding the binding of localizator.writers.default in my AppServiceProvider I am able to achieve this

        $this->app->bind('localizator.writers.default', JsonWriter::class);

I have put the above solution in place, but it would be nice to have this as an option in the configuration?

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.