├── .github ├── issue_template.md └── workflows │ ├── publish.yml │ └── tests.yml ├── .phpunit.result.cache ├── .release-it.json ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── Makefile ├── README.md ├── babel.config.json ├── composer.json ├── config └── matice.php ├── jest.config.json ├── package-lock.json ├── package.json ├── src ├── BladeTranslationsGenerator.php ├── Commands │ └── TranslationsGeneratorCommand.php ├── Exceptions │ └── LocaleTranslationsFileOrDirNotFoundException.php ├── Facades │ └── Matice.php ├── Helpers.php ├── MaticeServiceProvider.php └── js │ ├── Localization │ ├── MaticeLocalizationConfig.ts │ └── core.ts │ └── matice.ts ├── tsconfig.json └── webpack.config.js /.github/issue_template.md: -------------------------------------------------------------------------------- 1 | ### Expected behavior 2 | 3 | 4 | 5 | ### Current behavior 6 | 7 | 8 | 9 | 10 | 11 | 12 | ### Versions 13 | 14 | - **Laravel**: #.#.# 15 | - **Matice**: #.#.# 16 | 17 | ### Transalations 18 | 19 | 20 | 21 | ```php 22 | ['greet' => 'It greets the wrong way.'] 23 | 24 | trans('greet') // Something strange. 25 | ``` 26 | 27 | ### Contents of `Matice.translations` 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | publish: 9 | name: Publish to NPM 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v2 15 | 16 | - name: Set up NPM 17 | uses: actions/setup-node@v1 18 | with: 19 | node-version: '12.x' 20 | registry-url: 'https://registry.npmjs.org' 21 | 22 | - name: Build and publish 23 | env: 24 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 25 | run: | 26 | npm install 27 | npm --no-git-tag-version version $(git describe --tags) --allow-same-version 28 | npm publish --access public 29 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | - 1.x 9 | 10 | jobs: 11 | test: 12 | name: PHP ${{ matrix.php }}, Laravel ${{ matrix.laravel }} 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2] 19 | laravel: [6.*, 7.*, 8.*, 9.*] 20 | exclude: 21 | # Laravel >= 6.0 doesn't support PHP 7.2 or >= 8.1 22 | - laravel: 6.* 23 | php: 8.1 24 | - laravel: 6.* 25 | php: 8.2 26 | 27 | # Laravel >= 7.0 doesn't support PHP 7.2 or >= 8.1 28 | - laravel: 7.* 29 | php: 8.1 30 | - laravel: 7.* 31 | php: 8.2 32 | 33 | # Laravel >= 8.0 doesn't support PHP 7.2 or >= 8.2 34 | - laravel: 8.* 35 | php: 7.2 36 | - laravel: 8.* 37 | php: 8.2 38 | 39 | # Laravel >= 9.0 doesn't support PHP <= 7.4 40 | - laravel: 9.* 41 | php: 7.2 42 | - laravel: 9.* 43 | php: 7.3 44 | - laravel: 9.* 45 | php: 7.4 46 | 47 | include: 48 | - laravel: 6.* 49 | testbench: 4.* 50 | - laravel: 7.* 51 | testbench: 5.* 52 | - laravel: 8.* 53 | testbench: 6.* 54 | - laravel: 9.* 55 | testbench: 7.* 56 | 57 | steps: 58 | - name: Checkout 59 | uses: actions/checkout@v2 60 | 61 | - name: Set up PHP 62 | uses: shivammathur/setup-php@v2 63 | with: 64 | php-version: ${{ matrix.php }} 65 | 66 | - name: Cache Composer dependencies 67 | uses: actions/cache@v1 68 | with: 69 | path: ~/.composer/cache/files 70 | key: php-${{ matrix.php }}-laravel-${{ matrix.laravel }}-composer-${{ hashFiles('**/composer.lock') }} 71 | restore-keys: php-${{ matrix.php }}-laravel-${{ matrix.laravel }}-composer- 72 | 73 | - name: Cache npm dependencies 74 | uses: actions/cache@v1 75 | with: 76 | path: ~/.npm 77 | key: npm-${{ hashFiles('**/package-lock.json') }} 78 | restore-keys: npm- 79 | 80 | - name: Install dependencies 81 | run: | 82 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 83 | composer update --prefer-dist --no-interaction --no-progress --no-suggest 84 | npm install 85 | 86 | - name: Build 87 | run: npm run build 88 | 89 | - name: Run PHPUnit tests 90 | run: vendor/bin/phpunit --testdox --colors=always 91 | 92 | - name: Run Jest tests 93 | run: npm test 94 | -------------------------------------------------------------------------------- /.phpunit.result.cache: -------------------------------------------------------------------------------- 1 | {"version":1,"defects":{"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_load_translations":3,"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_load_translations_from_additional_json_paths":3},"times":{"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_load_translations":0.043,"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_generate_translation_js":0.003,"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_namespaces_can_be_excepted":0.003,"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_only_certain_namespaces_can_be_exported":0.003,"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_only_namespaces_can_be_both_exported_and_excepted":0.003,"Genl\\Matice\\Tests\\Unit\\ManageTranslationTest::test_load_translations_from_additional_json_paths":0.003}} -------------------------------------------------------------------------------- /.release-it.json: -------------------------------------------------------------------------------- 1 | { 2 | "npm": { 3 | "publish": true 4 | }, 5 | "hooks": { 6 | "before:init": ["yarn test", "yarn build"] 7 | }, 8 | "github": { 9 | "release": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `matice` will be documented in this file 4 | 5 | ## 1.0.0 - 201X-XX-XX 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) GENL 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | rnpm: ## Release the package and publish on npm -- DEPRECATED 2 | release-it --dry-run 3 | 4 | publish: # publish on npm publish package on NPM. 5 | npm publish 6 | 7 | test-front: 8 | yarn test 9 | 10 | 11 | test-back: 12 | vendor/bin/phpunit --testdox --colors=always -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Use your Laravel translations in JavaScript 2 | 3 | [](https://packagist.org/packages/genl/matice) 4 | [](https://npmjs.com/package/matice) 5 | [](https://github.com/GENL/matice/actions/workflows/tests.yml) 6 | [](https://packagist.org/packages/genl/matice/stats) 7 | [](https://www.npmjs.com/package/matice) 8 | 9 |  10 | 11 | Matice creates a Blade directive that you can include in your views. 12 | It will export a JavaScript object of your Laravel application's translations, 13 | keyed by their names (aliases, lang, filenames, folders name), 14 | as well as globals trans(), __() and transChoice() helper 15 | functions which you can use to access your translations in your JavaScript. 16 | 17 | 18 | - [Installation](#installation) 19 | - [Usage](#usage) 20 | - [Examples](#examples) 21 | - [trans](#trans) 22 | - [Update locale](#update-locale) 23 | - [Pluralization](#pluralization) 24 | - [Trans Choice](#trans-choice) 25 | - [underscore function](#underscore-function) 26 | - [Default Values](#default-values) 27 | - [Retrieve the current locale](#retrieve-the-current-locale) 28 | - [Force locale](#force-locale) 29 | - [Filtering translations](#filtering-translations) 30 | - [Filtering namespaces](#filtering-namespaces) 31 | - [Use with SPA](#use-with-spa) 32 | - [Using with Vue Components](#using-with-vue-components) 33 | - [Dive Deeper](#dive-deeper) 34 | 35 | ## Installation 36 | 37 | You can install the package via composer: 38 | 39 | ```bash 40 | composer require genl/matice 41 | ``` 42 | 43 | 1. ##### Include our Blade directive (`@translations`) somewhere in your template before your main application JavaScript is loaded—likely in the header somewhere. 44 | 1. ##### Publish the vendor if you want to customize config: 45 | ```bash 46 | php artisan vendor:publish --provider="Genl\Matice\MaticeServiceProvider" 47 | ``` 48 | 49 | Matice is available as an NPM `matice` package 50 | which exposes the `trans()` function for use in frontend applications 51 | that do not use Blade. 52 | You can install the NPM package with: 53 | ```bash 54 | // With yarn 55 | yarn add matice 56 | 57 | With npm 58 | npm install matice 59 | ``` 60 | 61 | or load it from a CDN: 62 | ```html 63 | 64 | 65 | ``` 66 | 67 | * Note that the JavaScript package only contains the translations logic. You have to generate your translations file and make 68 | it available to your frontend app. The blade directive `@translations` will do it for you anytime you reload the page. 69 | 70 | **TypeScript support** 71 | 72 | Matice is fully written in TypeScript so, it's compatible with TypeScript projects. 73 | 74 | 75 | 76 | ## Usage 77 | 78 | * ##### Core concepts 79 | 80 | Matice comes with almost the same localization concepts as Laravel. 81 | Read more about [Laravel localization](https://laravel.com/docs/localization) 82 | 83 | This package uses the `@translations` directive to inject a JavaScript object containing all of your application's translations, keyed by their names. This collection is available globally on the client side in the `window.Matice` object. 84 | The `@translations` directive accepts a list of locales to be loaded under th form of an array or a comma seperated string. 85 | If no locales are given, all the translations will be loaded. 86 | 87 | #### Examples 88 | 89 | import the `trans()` function like follow: 90 | ```php 91 | @translations(['en', 'fr']) 92 | 93 | or 94 | 95 | @translations('en, fr') 96 | ``` 97 | 98 | 99 | The package also creates an optional `trans()` JavaScript helper which works like Laravel's PHP `trans()` helper to retrieve translation strings. 100 | 101 | 102 | #### Examples 103 | 104 | import the `trans()` function like follow: 105 | ```javascript 106 | import { trans } from "matice"; 107 | ``` 108 | 109 | Let's assume we have this translations file: 110 | 111 | ```php 112 | // resources/lang/en/custom.php 113 | 114 | return [ 115 | 'greet' => [ 116 | 'me' => 'Hello!', 117 | 'someone' => 'Hello :name!', 118 | 'me_more' => 'Hello Ekcel Henrich!', 119 | 'people' =>'Hello Ekcel!|Hello everyone!', 120 | ], 121 | 'balance' => "{0} You're broke|[1000, 5000] a middle man|[1000000,*] You are awesome :name, :count Million Dollars" 122 | ]; 123 | ``` 124 | 125 | ```php 126 | // resources/lang/fr/custom.php 127 | 128 | return [ 129 | 'greet' => [ 130 | 'me' => 'Bonjour!' 131 | ] 132 | ]; 133 | ``` 134 | 135 | #### trans 136 | 137 | Retrieve a text: 138 | ```javascript 139 | let sentence = '' 140 | 141 | sentence = trans('greet.me') // Hello! 142 | 143 | // With parameters 144 | sentence = trans('greet.someone', {args: {name: "Ekcel"}}) // Hello Ekcel! 145 | ``` 146 | 147 | #### Update locale 148 | 149 | Matice exposes `setLocale` function to change the locale that is used by the `trans` function. 150 | ```javascript 151 | import { setLocale } from "matice" 152 | 153 | // update the locale 154 | setLocale('fr') 155 | const sentence = trans('greet.me') // Bonjour! 156 | ``` 157 | 158 | #### Pluralization 159 | 160 | On pluralization, the choice depends on the `count` argument. To activate pluralization 161 | pass the argument `pluralize` to true. 162 | 163 | ```javascript 164 | // Simple pluralization 165 | sentence = trans('greet.people', {args: {count: 0}, pluralize: true}) // Hello Ekcel! 166 | sentence = trans('greet.people', {args: {count: 2}, pluralize: true}) // Hello everyone! 167 | 168 | // Advanced pluralization with range. Works the same way. 169 | // [balance => '{0} You're broke|[1000, 5000] a middle man|[1000000,*] You are awesome :name, :count Million Dollars'] 170 | sentence = trans('balance', {args: {count: 0}, pluralize: true}) // You're broke 171 | sentence = trans('balance', {args: {count: 3000}, pluralize: true}) // a middle man 172 | ``` 173 | 174 | #### Trans Choice 175 | 176 | Matice provides a helper function for pluralization 177 | 178 | ```javascript 179 | import { transChoice } from "matice" 180 | 181 | let sentence = transChoice('balance', 17433085, {name: 'Ekcel'}) // You are awesome Ekcel, 17433085 Million Dollars 182 | ``` 183 | 184 | 185 | #### Underscore function 186 | * As well of the `trans()` function, Matice provide `__()` that does the same as the `trans()` function but with this particularity 187 | not to throw an error when the key is not found but returns the key itself. 188 | 189 | `transChoice()` always throws an error if the key is not found. To change this behaviour, use `__(key, {pluralize: true})` 190 | 191 | ```js 192 | sentence = trans('greet.unknown') // -> throws an error with a message. 193 | sentence = __('greet.unknown') // greet.unknown 194 | ``` 195 | 196 | #### Default values 197 | 198 | Matice uses your current app locale `app()->getLocale()` as the default locale when generating the translation object with the blade directive `@translations`. 199 | Same applies when generating with command line. 200 | 201 | When Matice does not find a key, it falls back to the default locale and search again. The fallback is the 202 | same you define in your `config.app.fallback_locale`. 203 | 204 | ```php 205 | // config/app.php 206 | 207 | 'locale' => 'fr', 208 | 'fallback_locale' => 'en', 209 | ``` 210 | 211 | #### Retrieve the current locale 212 | Matice exposes the `MaticeLocalizationConfig` class : 213 | ```js 214 | import { MaticeLocalizationConfig } from "matice" 215 | 216 | const locale = MaticeLocalizationConfig.locale // 'en' 217 | 218 | const fallbackLocale = MaticeLocalizationConfig.fallbackLocale // 'en' 219 | 220 | const locales = MaticeLocalizationConfig.locales // ['en', 'fr'] 221 | ``` 222 | 223 | Matice also provides helpers to deal with locales information: 224 | ```js 225 | import { setLocale, getLocale, locales } from "matice" 226 | 227 | // Update the locale 228 | setLocale('fr') // 229 | 230 | const locale = getLocale() // 'fr' 231 | 232 | const locales = locales() // ['en', 'fr'] 233 | ``` 234 | 235 | #### Force locale 236 | With the version 1.1.4, it is possible to force the locale for a specific translation WITHOUT changing the global local. 237 | ```js 238 | setLocale('en') // Set the current locale to English. 239 | 240 | trans('greet.me') // "Hello!" 241 | trans('greet.me', { locale: 'fr' }) // "Bonjour!" 242 | trans('greet.me', { args: {}, locale: 'fr' }) // "Bonjour!" 243 | 244 | __('greet.me', { locale: 'fr' }) // "Bonjour!" 245 | 246 | transChoice('greet.me', 1, undefined, 'fr') // "Bonjour!" 247 | transChoice('greet.me', 1, {}, 'fr') // "Bonjour!" 248 | ``` 249 | 250 | 251 | ## Filtering translations 252 | Matice supports filtering the translations it makes available to your JavaScript, which is great to control the size of your 253 | data your translations become too large with thousands of lines. 254 | 255 | #### Filtering namespaces 256 | To set up namespace translations filtering, update in your config file either an `only` or `except` setting as an array of translations folders or files. 257 | `Note: Setting the same namespace both 'only' and 'except' will result to 'except'. But in the other cases, 'only' takes precedence over 'except'` 258 | 259 | ```php 260 | // config/matice.php 261 | 262 | return [ 263 | // Export only 264 | 'only' => [ 265 | 'fr/', // Take all the 'fr' directory with his children 266 | 'es', // Take all the 'es' directory with his children 267 | 'en/auth', // With or without the file extension 268 | 'en/pagination.php', 269 | 'en/validations', 270 | ], 271 | 272 | // Or... export everything except 273 | 'except' => [ 274 | 'en/passwords', 275 | 'en\\validations', 276 | ], 277 | ]; 278 | ``` 279 | 280 | The base directory is the lang_directory defined in the config file: `config('matice.lang_directory')`. 281 | 282 | ## Use with SPA 283 | Matice registers an Artisan console command to generate a `matice_translations.js` translations file, which can be used (or not) as part of an asset pipeline such as [Laravel Mix](https://laravel.com/docs/mix). 284 | 285 | You can run `php artisan matice:generate --no-export` in your project to generate a static translations file without the export statement in `resources/assets/js/matice_translations.js`. 286 | You can customize the generation path in the `config/matice.php` file. 287 | 288 | ```sh 289 | php artisan matice:generate --no-export 290 | ``` 291 | 292 | An example of `matice_translations.js`, where auth translations exist in `resources/lang/en/auth.php`: 293 | 294 | ```php 295 | // resources/lang/en/auth.php 296 | 297 | return [ 298 | 'failed' => 'These credentials do not match our records.', 299 | 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', 300 | ]; 301 | ``` 302 | 303 | ```js 304 | // matice_translations.js 305 | 306 | const Matice = { 307 | locale: 'en', 308 | fallbackLocale: 'en', 309 | translations: { 310 | en: { 311 | auth: { 312 | failed: 'These credentials do not match our records.', 313 | throttle: 'Too many login attempts. Please try again in :seconds seconds.' 314 | } 315 | } 316 | } 317 | }; 318 | 319 | ``` 320 | 321 | At this point you can use in javascript this translations file like usual, paste in your html as well. 322 | 323 | This is useful if your laravel and js app are separated like with SPA or PWA. So you can 324 | link the generated translations file with your JS App. If you're not in the case of SPA, WPA... 325 | you might never have to generate the translations manually because `@translations` directive already does 326 | it for you when the app environment is 'production' to improve performance. 327 | 328 | ```html 329 | 330 | 331 | 332 |
333 |{{ $trans('greet.me') }}
389 | ``` 390 | 391 | ## Dive Deeper 392 | 393 | Matice extends the Laravel `Translator` class. Use `Translator::list()` to return 394 | an array representation of all of your app translations. 395 | 396 | If you want to load only translations of a specific locale, use the matice facade: 397 | ```php 398 | use GENL\Matice\Facades\Matice; 399 | 400 | // Loads all the translations 401 | $translations = Matice::translations(); 402 | 403 | // Or loads translations for a specific locale. 404 | $translations = Matice::translations($locale); 405 | ``` 406 | 407 | 408 | **Environment-based loading of minified matice helper file** 409 | 410 | When using the `@translations` Blade directive, Matice detects the current environment and minify the output if `APP_ENV` is `production`. 411 | 412 | In development, `@translations` loops into the lang directory to generate the matice object each time the page reloads, and doesn't generate`matice_translations.js` file. 413 | In production, `@translations` generate the `matice_translations.js` file for you when your app is open for the first time then the generated file is used every time the page reloads. 414 | The Matice object is not generated every time, so it has no effect on performances in production. 415 | This behavior can be disabled in the `config/matice.php` file, set `use_generated_translations_file_in_prod` to false. 416 | 417 | ######**Note: Matice supports json translation files as well as php files.**, 418 | 419 | 420 | ### Testing 421 | 422 | ``` bash 423 | // -- laravel test -- 424 | composer test 425 | 426 | // -- js test -- 427 | 428 | // With yarn 429 | yarn test 430 | 431 | // With npm 432 | npm run test 433 | ``` 434 | 435 | ### Changelog 436 | 437 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 438 | 439 | ## Contributing 440 | 441 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 442 | 443 | ### Security 444 | 445 | If you discover any security related issues, please email bigcodole@gmail.com instead of using the issue tracker. 446 | 447 | ## Credits 448 | 449 | - [GENL](https://github.com/GENL/matice) 450 | - [All Contributors](../../contributors) 451 | - This package was largely inspired by [Ziggy](https://github.com/tighten/ziggy) 452 | 453 | ## License 454 | 455 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 456 | 457 | ## Laravel Package Boilerplate 458 | 459 | This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com). 460 | -------------------------------------------------------------------------------- /babel.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-typescript" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "genl/matice", 3 | "description": "Use your Laravel translations in JavaScript. Generates a Blade directive exporting all of your Laravel translations and provides a nice trans() helper function in JavaScript.", 4 | "keywords": [ 5 | "matice", 6 | "laravel", 7 | "translations" 8 | ], 9 | "homepage": "https://github.com/genl/matice", 10 | "license": "MIT", 11 | "type": "library", 12 | "authors": [ 13 | { 14 | "name": "Ekcel Ekoumelong", 15 | "email": "bigcodole@gmail.com", 16 | "homepage": "https://ekcel-portofolio.firebaseapp.com" 17 | } 18 | ], 19 | "require": { 20 | "laravel/framework": ">=6.0@dev" 21 | }, 22 | "require-dev": { 23 | "orchestra/testbench": "^4.10||^5.0||^6.0||^7.0" 24 | }, 25 | "autoload": { 26 | "psr-4": { 27 | "Genl\\Matice\\": "src" 28 | } 29 | }, 30 | "autoload-dev": { 31 | "psr-4": { 32 | "Genl\\Matice\\Tests\\": "tests" 33 | } 34 | }, 35 | "scripts": { 36 | "test": "vendor/bin/phpunit", 37 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 38 | 39 | }, 40 | "config": { 41 | "sort-packages": true 42 | }, 43 | "extra": { 44 | "laravel": { 45 | "providers": [ 46 | "Genl\\Matice\\MaticeServiceProvider" 47 | ], 48 | "aliases": { 49 | "Matice": "Genl\\Matice\\Facades\\Matice" 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /config/matice.php: -------------------------------------------------------------------------------- 1 | function_exists('lang_path') ? lang_path() : resource_path('lang'), 13 | 14 | /* 15 | |-------------------------------------------------------------------------- 16 | | Use existing generated file in prod 17 | |-------------------------------------------------------------------------- 18 | | 19 | | Whether @translations should always use the generated translations in production. 20 | | If false, the @translations directive will always regenerate the translations. 21 | | 22 | */ 23 | 'use_generated_translations_file_in_prod' => true, 24 | 25 | /* 26 | |-------------------------------------------------------------------------- 27 | | generated translations file name 28 | |-------------------------------------------------------------------------- 29 | | 30 | | The place where to generate translations file. 31 | | 32 | */ 33 | 'generate_translations_path' => resource_path('assets/js/matice_translations.js'), 34 | 35 | /* 36 | |-------------------------------------------------------------------------- 37 | | Restrictions 38 | |-------------------------------------------------------------------------- 39 | | 40 | | Specify which translation namespaces must(only) be exported. 41 | | It could be the paths to the folders or files you want to exported to the client. 42 | 43 | | The base directory is the "lang_directory" 44 | | 45 | */ 46 | 'only' => [ 47 | // 48 | ], 49 | 50 | /* 51 | |-------------------------------------------------------------------------- 52 | | Restrictions 53 | |-------------------------------------------------------------------------- 54 | | 55 | | Specify which translation namespaces must NOT be exported. 56 | | It could be the paths to the folders or files you want to exported to the client. 57 | 58 | | The base directory is the "lang_directory" 59 | | 60 | */ 61 | 'except' => [ 62 | // 63 | ], 64 | 65 | ]; 66 | -------------------------------------------------------------------------------- /jest.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "verbose": true, 3 | "rootDir": "tests/js", 4 | "preset": "ts-jest", 5 | "testEnvironment": "node" 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "matice", 3 | "version": "1.2.0", 4 | "description": "Matice - Use your Laravel translations in JavaScript", 5 | "main": "dist/matice.js", 6 | "types": "dist/matice.d.ts", 7 | "directories": { 8 | "test": "jest" 9 | }, 10 | "files": [ 11 | "dist" 12 | ], 13 | "scripts": { 14 | "test": "jest", 15 | "build": "tsc && webpack", 16 | "prepare": "npm run build --production" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/GENL/matice.git" 21 | }, 22 | "keywords": [ 23 | "matice", 24 | "laravel", 25 | "translations" 26 | ], 27 | "author": "Ekcel Ekoumelong", 28 | "license": "MIT", 29 | "bugs": { 30 | "url": "https://github.com/GENL/matice/issues" 31 | }, 32 | "homepage": "https://github.com/GENL/matice#readme", 33 | "devDependencies": { 34 | "@babel/preset-typescript": "^7.26.0", 35 | "@types/jest": "^29.5.14", 36 | "@types/node": "^22.10.1", 37 | "jest": "^29.7.0", 38 | "release-it": "^17.10.0", 39 | "ts-jest": "^29.2.5", 40 | "ts-loader": "^9.5.1", 41 | "typescript": "^5.7.2", 42 | "webpack": "^5.97.1", 43 | "webpack-cli": "^5.1.4" 44 | }, 45 | "dependencies": { 46 | "global": "^4.4.0", 47 | "uglify-js": "^3.19.3" 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/BladeTranslationsGenerator.php: -------------------------------------------------------------------------------- 1 | unique()->toArray() : 52 | $locales; 53 | // when $useCache is set to true, $wrapInHtml also has to be true. 54 | // TODO: make it possible to return the matice object without wrapping the it 55 | // in the HTML script when $useCache === true. 56 | abort_if( 57 | $useCache && !$wrapInHtml, 58 | 400, 59 | 'Cannot generate translations because when $useCache is true, $wrapInHtml also has to be true.' 60 | ); 61 | $path = config('matice.generate_translations_path'); 62 | // Use the cache if the translation file exists 63 | if ($useCache) { 64 | if (File::exists($path)) { 65 | $generatedTranslationFileContent = File::get($path); 66 | return $this->makeMaticeHtml( 67 | $generatedTranslationFileContent, 68 | true, 69 | "Matice Laravel Translations generated", "Using cached translations" 70 | ); 71 | } 72 | Log::warning("Trying to use the cached matice translations file but the file was not found."); 73 | error_log("Trying to use the cached matice translations file but the file was not found."); 74 | } 75 | if ($wrapInHtml) { 76 | return $this->makeMaticeHtml( 77 | $this->makeMaticeJSObject($locales), 78 | true, 79 | "Matice Laravel Translations generated" 80 | ); 81 | } else { 82 | return $this->makeMaticeJSObject($locales, $hasExport); 83 | } 84 | } 85 | 86 | /** 87 | * @param string[] $locales 88 | * @param bool $hasExport 89 | * @return string 90 | * @throws LocaleTranslationsFileOrDirNotFoundException 91 | */ 92 | private function makeMaticeJSObject(array $locales, bool $hasExport=true): string 93 | { 94 | $translations = json_encode($this->translations($locales)); 95 | $appLocale = $locale ?? app()->getLocale(); 96 | $fallbackLocale = config('app.fallback_locale'); 97 | $exportStatement = $hasExport ? "\n$this->maticeExportStatement" : ''; 98 | return <<