├── .gitignore
├── LICENSE
├── composer.json
├── config
└── translation-db.php
├── database
└── migrations
│ └── 2015_06_10_144817_add_translations_table.php
├── readme.md
├── resources
└── lang
│ ├── en
│ └── manager.php
│ └── nl
│ └── manager.php
├── src
├── Console
│ └── Commands
│ │ ├── DumpCommand.php
│ │ └── FetchCommand.php
├── Controllers
│ └── TranslationsController.php
├── DataCollector
│ └── TranslationCollector.php
├── DatabaseLoader.php
├── ServiceProvider.php
├── TranslationException.php
└── Translator.php
└── views
├── index.blade.php
├── javascript.blade.php
└── style.blade.php
/.gitignore:
--------------------------------------------------------------------------------
1 | /vendor
2 | composer.lock
3 | .idea
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "hpolthof/laravel-translations-db",
3 | "description": "A database translations implementation for Laravel 5.",
4 | "license": "GPL2",
5 | "keywords": ["laravel", "translation", "localization", "database"],
6 | "authors": [
7 | {
8 | "name": "Paul Olthof",
9 | "email": "hpolthof@gmail.com"
10 | }
11 | ],
12 | "require": {
13 | "php": ">=5.4.0",
14 | "illuminate/translation": "5.*",
15 | "illuminate/database": "5.*",
16 | "illuminate/cache": "5.*",
17 | "stichoza/google-translate-php": "~3.1"
18 | },
19 |
20 | "autoload": {
21 | "psr-4": {
22 | "Hpolthof\\Translation\\": "src"
23 | }
24 | },
25 | "extra": {
26 | "branch-alias": {
27 | "dev-master": "0.4.x-dev"
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/config/translation-db.php:
--------------------------------------------------------------------------------
1 | true,
9 |
10 | /**
11 | * This setting enables or disables the web interface and its routes.
12 | */
13 | 'webinterface' => true,
14 |
15 | /**
16 | * This is the prefix for on which URI the Translations Manager will
17 | * be available. You can leave it just as is in most cases.
18 | */
19 | 'route_prefix' => '_translations',
20 |
21 | /**
22 | * If your using the Laravel Debugbar provided by Barryvdh\Debugbar
23 | * you might want to disable this in the Translations Manager.
24 | * This interface can generate a bunch of Ajax calls that will slow
25 | * the translation process down.
26 | * You can however turn it on, the choice is yours.
27 | */
28 | 'disable_debugbar' => true,
29 |
30 | /**
31 | * - Force translations to be cached, even in Debug Mode.
32 | * - And disables the collection of new keys.
33 | * This can be used to prevent lots of queries from
34 | * happening.
35 | */
36 | 'minimal' => false,
37 |
38 | /**
39 | * Use locales from files as a fallback option. Be aware that
40 | * locales are loaded as groups. When just one locale of a group
41 | * exists in the database, a file will never be used.
42 | * To use some files, keep these groups fully out of your database.
43 | */
44 | 'file_fallback' => false,
45 | ];
46 |
--------------------------------------------------------------------------------
/database/migrations/2015_06_10_144817_add_translations_table.php:
--------------------------------------------------------------------------------
1 | increments('id');
18 | $table->string('locale');
19 | $table->string('group');
20 | $table->string('name');
21 | $table->text('value')->nullable();
22 | $table->timestamp('viewed_at')->nullable();
23 | $table->timestamps();
24 |
25 | $table->index(['locale', 'group']);
26 | $table->unique(['locale', 'group', 'name']);
27 | });
28 | }
29 |
30 | /**
31 | * Reverse the migrations.
32 | *
33 | * @return void
34 | */
35 | public function down()
36 | {
37 | Schema::drop('translations');
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | ## Localization from a database
2 |
3 | [](https://packagist.org/packages/hpolthof/laravel-translations-db)
4 | [](https://packagist.org/packages/hpolthof/laravel-translations-db)
5 | [](https://packagist.org/packages/hpolthof/laravel-translations-db)
6 |
7 | This package was created, as an **in-place replacement** for the default TranslationServiceProvider and mend for everyone who got tired of collecting translations in language files and maintaining dozens
8 | of arrays, filled with lots and lots of keys. Keys will be added to the database **automatically**, so no more hussling with
9 | adding your keys to the translations file, automatic translation with **Google Translate** is also supported. You'll never forget to translate a key anymore! In production your keys will be **cached** to ensure the localization stays blazing fast!
10 |
11 | 
12 |
13 |
14 | ## Installation
15 |
16 | Require this package with composer:
17 |
18 | ```
19 | composer require hpolthof/laravel-translations-db
20 | ```
21 | > Like to live on the edge?
22 | > Use: ```composer require 'hpolthof/laravel-translations-db:*@dev'```
23 |
24 | After updating composer, we'll have to replace the TranslationServiceProvider the our ServiceProvider in config/app.php.
25 |
26 | Find:
27 | ```
28 | 'Illuminate\Translation\TranslationServiceProvider',
29 | ```
30 | and Replace this with:
31 | ```
32 | 'Hpolthof\Translation\ServiceProvider',
33 | ```
34 |
35 | The ServiceProvider will now be loaded. To use this package properly you'll also need the create a table in your database,
36 | this can be achieved by publishing the config and migration of this package.
37 |
38 | Run the following command:
39 | ```
40 | php artisan vendor:publish --provider='Hpolthof\Translation\ServiceProvider'
41 | ```
42 | and afterwards run your migrations:
43 | ```
44 | php artisan migrate
45 | ```
46 |
47 | And that's all there is to it!
48 |
49 | ## Usage
50 | You can just start using translations as you would normaly do with the Laravels default package. The functions ```trans()``` and ```Lang::get()``` can be used as you normaly would.
51 | > For more information about Localization and the usage of these functions, please refer to the [Documentation](http://laravel.com/docs/5.1/localization) on the mather.
52 |
53 | ### Files are still possible
54 | The usage of translation files is however still possible. Every translation prefixed by a namespace is parsed through the old
55 | TranslationServiceProvider. This is needed for external packages that come with there own translation files. But in general
56 | you shouldn't be bothered by this.
57 |
58 | ## Web interface
59 | To prevent you from having to access the database for every translation, a web interface is available to manager your
60 | translations.
61 |
62 | Direct your browser to:
63 | ```
64 | http://{projectUrl}/_translations
65 | ```
66 | > This location can also be changed in the ```translation-db.php``` config file.
67 |
68 | ### Configure your workset
69 | At the Translations Manager you'll have to select a certain group, as well as a locale. The first locale you'll select
70 | represents the language you'll be using as a reference to create your translations.
71 | In the textfield you should enter the locale you want to create or edit.
72 | > The locale you should enter in the textfield, can be any locale. There is no need to predefine anything. The entries will be created just as you submit your translations.
73 | After selecting these settings, just hit the Load button and all the collected translations will be listed.
74 |
75 | ### Editing
76 | After your translation keys are loaded, a textbox will appear on each row. You can just type in your translation, when
77 | the textbox loses it's focus, the translation will be saved.
78 | > The saving takes place through some Ajax calls. If you are using the [Laravel Debugbar](https://github.com/barryvdh/laravel-debugbar)
79 | > it will be advised to disable the Debugbar as every Ajax request slows your browser down. By default de Debugbar will
80 | > therefor be disabled, it the Debugbar is used. If you want to leave the Debugbar on, you can just enable it within
81 | > the ```translation-db.php``` config file.
82 |
83 | ### Google Translate integration
84 | As of version 0.4.0 support integration with Google Translate is included. In the Translations Manager a button has been added for Google Translate. All blank and currently opened translations will then be processed through Google Translate and be written into the textbox.
85 | > These translations are not yet stored into the database and need to be reviewed manually. As soon as the textbox loses it's
86 | > focus the translation will be stored. To prevent you from being blocked by Google there is an interval of 500 miliseconds between each request.
87 |
88 | ### Turn it off
89 | If you don't want any additional routes forced into your application, you can disable the whole web interface by
90 | changing the ```translation-db.webinterface``` config from ```TRUE``` to ```FALSE```.
91 |
92 | ## Importing and exporting
93 | To ease the proces of migrating to translations in the database, two commands are available since version 0.3.
94 | ### Import
95 | To import all translations out of your current language files, you can use the command:
96 | ```
97 | php artisan translation:fetch
98 | ```
99 | This will import all available translations in language files into the database.
100 | > To import just some specifics you can also make use of the options ```--locale``` and ```--group```.
101 |
102 | ### Export
103 | To dump the translations from your database back to your filesystem, use:
104 | ```
105 | php artisan translation:dump
106 | ```
107 | > The options ```--locale``` and ```--group``` are also available for this command.
108 | > **Caution**: all current files will be **overwritten**, so use with care!
109 |
--------------------------------------------------------------------------------
/resources/lang/en/manager.php:
--------------------------------------------------------------------------------
1 | 'Translations Manager',
4 | 'help' => 'Select your preferred group and locale below and start translating.',
5 | 'locale_placeholder' => 'Enter the locale you wish to edit. (example: en)',
6 | 'button' => 'Load',
7 | 'google' => 'Google Translate',
8 | 'delete' => 'Delete',
9 | ];
--------------------------------------------------------------------------------
/resources/lang/nl/manager.php:
--------------------------------------------------------------------------------
1 | 'Vertalingen beheer',
4 | 'help' => 'Selecteer de groep en de taal van uw voorkeur en start met vertalen.',
5 | 'locale_placeholder' => 'Geef de taal op die uw wilt bewerken. (bijvoorbeeld: nl)',
6 | 'button' => 'Inladen',
7 | 'google' => 'Google Translate',
8 | 'delete' => 'Verwijderen',
9 | ];
--------------------------------------------------------------------------------
/src/Console/Commands/DumpCommand.php:
--------------------------------------------------------------------------------
1 | select('locale', 'group', 'name', 'value');
34 | $this->addOptionToQuery($query, 'locale');
35 | $this->addOptionToQuery($query, 'group');
36 | $results = $query->get();
37 |
38 | // Reorder the data
39 | $dump = [];
40 | foreach($results as $result) {
41 | $dump[$result->locale][$result->group][$result->name] = $result->value;
42 | }
43 | $this->write($dump);
44 | }
45 |
46 | /**
47 | * Get the console command arguments.
48 | *
49 | * @return array
50 | */
51 | protected function getArguments()
52 | {
53 | return [];
54 | }
55 |
56 | /**
57 | * Get the console command options.
58 | *
59 | * @return array
60 | */
61 | protected function getOptions()
62 | {
63 | return [
64 | ['locale', 'l', InputOption::VALUE_OPTIONAL, 'Specify a locale.', null],
65 | ['group', 'g', InputOption::VALUE_OPTIONAL, 'Specify a group.', null],
66 | ];
67 | }
68 |
69 | /**
70 | * @param Builder $query
71 | * @param string $option
72 | */
73 | protected function addOptionToQuery(Builder $query, $option)
74 | {
75 | if ($this->option($option) !== null) {
76 | $query->where($option, $this->option($option));
77 | }
78 | }
79 |
80 | protected function write($dump)
81 | {
82 | $lang_path = base_path().'/resources/lang';
83 | $date = date_create()->format('Y-m-d H:i:s');
84 | foreach($dump as $locale => $groups) {
85 | foreach($groups as $group => $content) {
86 | $path = $lang_path."/{$locale}";
87 | if(!\File::exists($path)) {
88 | \File::makeDirectory($path, 0755, true);
89 | }
90 |
91 | $file = $path."/{$group}.php";
92 | $content = $this->fixNulledValues($content);
93 | $data = $this->getFileTemplate($content, $locale, $group, $date);
94 |
95 | // Display the results
96 | if(\File::put($file, $data)) {
97 | $this->info("Dumped: {$file}");
98 | } else {
99 | $this->error("Failed to dump: {$file}");
100 | }
101 | }
102 | }
103 | }
104 |
105 | private function assignArrayByPath(&$arr, $path, $value) {
106 | $keys = explode('.', $path);
107 |
108 | while ($key = array_shift($keys)) {
109 | $arr = &$arr[$key];
110 | if(is_array($arr)) ksort($arr);
111 | }
112 |
113 | $arr = $value;
114 | }
115 |
116 | /**
117 | * @param $content
118 | * @param $locale
119 | * @param $group
120 | * @return string
121 | */
122 | protected function getFileTemplate($content, $locale, $group, $date)
123 | {
124 | $content = $this->convertToOrderedNestedArray($content);
125 |
126 | $array_text = var_export($content, true);
127 | $array_text = $this->getArrayText($content);
128 |
129 |
130 | $data = <<getMaxKeyLength($arr);
146 |
147 | foreach($arr as $key => $value) {
148 |
149 | $filler = str_repeat(' ', $max_key_length - strlen($key));
150 |
151 | if(is_array($value)) {
152 | $result .= $ident.str_repeat(' ', $ident_size)."'{$key}' => ";
153 | $result .= $this->getArrayText($value, $ident_size, $level+1);
154 | } else {
155 | $result .= $ident.str_repeat(' ', $ident_size)."'{$key}'{$filler} => ";
156 | $result .= var_export($value, true);
157 | }
158 | $result .= ",\n";
159 | }
160 | $result .= $ident.")";
161 |
162 | //if($level > 0) $result .= ",\n";
163 |
164 | return $result;
165 | }
166 |
167 | /**
168 | * @param $content
169 | * @return mixed
170 | */
171 | protected function fixNulledValues($content)
172 | {
173 | foreach ($content as $key => $value) {
174 | if ($value === null) {
175 | $content[$key] = $key;
176 | }
177 | }
178 | return $content;
179 | }
180 |
181 | /**
182 | * @param $content
183 | * @return array
184 | */
185 | private function convertToOrderedNestedArray($content)
186 | {
187 | $new_content = array();
188 | foreach ($content as $key => $value) {
189 | // Quick fix, see: https://github.com/hpolthof/laravel-translations-db/issues/13
190 | //$this->assignArrayByPath($new_content, $key, $value);
191 | if($value){
192 | array_set($new_content, $key, $value);
193 | }
194 | ksort($new_content);
195 | }
196 | $content = $new_content;
197 | return $content;
198 | }
199 |
200 | /**
201 | * @param $arr
202 | * @return int
203 | */
204 | private function getMaxKeyLength($arr)
205 | {
206 | $keys = array_keys($arr);
207 | usort($keys, function ($a, $b) {
208 | return strlen($a) < strlen($b);
209 | });
210 | $max_key_length = strlen(array_shift($keys));
211 | return $max_key_length;
212 | }
213 |
214 | }
215 |
--------------------------------------------------------------------------------
/src/Console/Commands/FetchCommand.php:
--------------------------------------------------------------------------------
1 | lang_path = base_path().'/resources/lang';
32 | parent::__construct();
33 | }
34 |
35 |
36 | /**
37 | * Execute the console command.
38 | *
39 | * @return mixed
40 | */
41 | public function fire()
42 | {
43 | if(!$this->validate()) return false;
44 |
45 | $locales = $this->usableLocales();
46 | foreach($locales as $locale) {
47 | $groups = $this->usableGroups($locale);
48 | foreach($groups as $group) {
49 | $this->storeGroup($locale, $group);
50 | }
51 | }
52 | }
53 |
54 | protected function flattenArray($keys, $prefix = '') {
55 | $result = [];
56 | foreach($keys as $key => $value) {
57 | if(is_array($value)) {
58 | $result = array_merge($result, $this->flattenArray($value, $prefix.$key.'.'));
59 | } else {
60 | $result[$prefix.$key] = $value;
61 | }
62 | }
63 | return $result;
64 | }
65 |
66 | protected function cleanLocaleDir($item) {
67 | return str_replace($this->lang_path.'/', '', $item);
68 | }
69 |
70 | protected function cleanGroupDir($item, $locale) {
71 | $clean = str_replace($this->lang_path."/{$locale}/", '', $item);
72 | if (preg_match('/^(.*?)\.php$/sm', $clean, $match)) {
73 | return $match[1];
74 | }
75 | return FALSE;
76 | }
77 |
78 | /**
79 | * Get the console command arguments.
80 | *
81 | * @return array
82 | */
83 | protected function getArguments()
84 | {
85 | return [];
86 | }
87 |
88 | /**
89 | * Get the console command options.
90 | *
91 | * @return array
92 | */
93 | protected function getOptions()
94 | {
95 | return [
96 | ['locale', 'l', InputOption::VALUE_OPTIONAL, 'Specify a locale.', null],
97 | ['group', 'g', InputOption::VALUE_OPTIONAL, 'Specify a group.', null],
98 | ];
99 | }
100 |
101 | /**
102 | * @return array|null
103 | */
104 | protected function getLocales()
105 | {
106 | if ($this->locales === null) {
107 | $locales = \File::directories($this->lang_path);
108 | $this->locales = array_map([$this, 'cleanLocaleDir'], $locales);
109 | }
110 | $locales = $this->locales;
111 | return $locales;
112 | }
113 |
114 | /**
115 | * @param $locale
116 | * @return bool
117 | */
118 | protected function hasLocale($locale)
119 | {
120 | $result = false;
121 | if (array_search($locale, $this->getLocales()) !== FALSE) {
122 | $result = true;
123 | }
124 | return $result;
125 | }
126 |
127 | protected function hasGroup($locale, $group)
128 | {
129 | $result = false;
130 | $file = $this->lang_path."/{$locale}/{$group}.php";
131 | if(\File::exists($file)) {
132 | $result = true;
133 | }
134 | return $result;
135 | }
136 |
137 | /**
138 | * @return array|null
139 | */
140 | protected function getGroups($locale)
141 | {
142 | $path = $this->lang_path."/{$locale}";
143 | $groups = \File::files($path);
144 | foreach($groups as &$group) {
145 | $group = $this->cleanGroupDir($group, $locale);
146 | }
147 | return $groups;
148 | }
149 |
150 | /**
151 | * @param $locale
152 | * @param $group
153 | */
154 | protected function validateGroup($locale, $group)
155 | {
156 | if (!$this->hasGroup($locale, $group)) {
157 | $this->error("The file '{$group}.php' was not found within locale '{$locale}'.");
158 | }
159 | }
160 |
161 | /**
162 | * @return bool
163 | */
164 | protected function validate()
165 | {
166 | $locale = $this->option('locale');
167 | if ($locale !== null) {
168 | if (!$this->hasLocale($locale)) {
169 | $this->error("The locale '{$locale}' was not found.");
170 | return false;
171 | }
172 | }
173 |
174 | $group = $this->option('group');
175 | if ($group !== null) {
176 | if ($locale === null) {
177 | foreach ($this->getLocales() as $locale) {
178 | $this->validateGroup($locale, $group);
179 | }
180 | } else $this->validateGroup($locale, $group);
181 | }
182 | return true;
183 | }
184 |
185 | /**
186 | * @return array|null
187 | */
188 | protected function usableLocales()
189 | {
190 | $locales = [];
191 | if ($this->option('locale') !== null) {
192 | $locales[] = $this->option('locale');
193 | return $locales;
194 | } else {
195 | $locales = $this->getLocales();
196 | return $locales;
197 | }
198 | }
199 |
200 | /**
201 | * @param $locale
202 | * @return array|null
203 | */
204 | protected function usableGroups($locale)
205 | {
206 | $groups = [];
207 | if ($this->option('group') !== null) {
208 | $groups[] = $this->option('group');
209 | return $groups;
210 | } else {
211 | $groups = $this->getGroups($locale);
212 | return $groups;
213 | }
214 | }
215 |
216 | /**
217 | * @param $locale
218 | * @param $group
219 | * @param $name
220 | * @param $inserted
221 | * @param $updated
222 | * @return array
223 | */
224 | protected function storeTranslation($locale, $group, $name, $value, $inserted, $updated)
225 | {
226 | $item = \DB::table('translations')
227 | ->where('locale', $locale)
228 | ->where('group', $group)
229 | ->where('name', $name)->first();
230 | $data = compact('locale', 'group', 'name', 'value');
231 | $data = array_merge($data, [
232 | 'updated_at' => date_create(),
233 | ]);
234 |
235 | if ($item === null) {
236 | $data = array_merge($data, [
237 | 'created_at' => date_create(),
238 | ]);
239 | \DB::table('translations')->insert($data);
240 | $inserted++;
241 | return array($inserted, $updated);
242 | } else {
243 | \DB::table('translations')->where('id', $item->id)->update($data);
244 | $updated++;
245 | return array($inserted, $updated);
246 | }
247 | }
248 |
249 | /**
250 | * @param $locale
251 | * @param $group
252 | */
253 | protected function storeGroup($locale, $group)
254 | {
255 | $keys = require $this->lang_path . "/{$locale}/{$group}.php";
256 | $keys = $this->flattenArray($keys);
257 |
258 | $updated = 0;
259 | $inserted = 0;
260 | foreach ($keys as $name => $value) {
261 | list($inserted, $updated) = $this->storeTranslation($locale, $group, $name, $value, $inserted, $updated);
262 | }
263 |
264 | $this->flushCache($locale, $group);
265 |
266 | $this->info("Fetched {$locale}/{$group}.php [New: {$inserted}, Updated: {$updated}]");
267 | }
268 |
269 | /**
270 | * @param $locale
271 | * @param $group
272 | */
273 | protected function flushCache($locale, $group)
274 | {
275 | \Cache::forget('__translations.'.$locale.'.'.$group);
276 | }
277 | }
278 |
--------------------------------------------------------------------------------
/src/Controllers/TranslationsController.php:
--------------------------------------------------------------------------------
1 | offsetExists('debugbar') && $app['config']->get('translation-db.disable_debugbar')) {
15 | $app['debugbar']->disable();
16 | }
17 | }
18 |
19 | public function getIndex() {
20 | return view('translation::index');
21 | }
22 |
23 | public function getGroups() {
24 | $query = \DB::table('translations')
25 | ->select('group')
26 | ->distinct()
27 | ->orderBy('group');
28 |
29 | return ServiceProvider::pluckOrLists($query, 'group');
30 | }
31 |
32 | public function getLocales() {
33 | $query = \DB::table('translations')
34 | ->select('locale')
35 | ->distinct()
36 | ->orderBy('locale');
37 |
38 | return ServiceProvider::pluckOrLists($query, 'locale');
39 | }
40 |
41 | public function postItems(Request $request) {
42 | if(strlen($request->get('translate')) == 0) throw new TranslationException();
43 |
44 | $base = \DB::table('translations')
45 | ->select('name', 'value')
46 | ->where('locale', $request->get('locale'))
47 | ->where('group', $request->get('group'))
48 | ->orderBy('name')
49 | ->get();
50 | $new = \DB::table('translations')
51 | ->select('name', 'value')
52 | ->where('locale', strtolower($request->get('translate')))
53 | ->where('group', $request->get('group'))
54 | ->orderBy('name');
55 | $new = ServiceProvider::pluckOrLists($new, 'value', 'name');
56 |
57 | foreach($base as &$item) {
58 | $translate = null;
59 |
60 | if(array_key_exists($item->name, $new)) {
61 | $translate = $new[$item->name];
62 | }
63 | $item->translation = $translate;
64 | }
65 |
66 | return $base;
67 | }
68 |
69 | public function postStore(Request $request) {
70 | $item = \DB::table('translations')
71 | ->where('locale', strtolower($request->get('locale')))
72 | ->where('group', $request->get('group'))
73 | ->where('name', $request->get('name'))->first();
74 |
75 | $data = [
76 | 'locale' => strtolower($request->get('locale')),
77 | 'group' => $request->get('group'),
78 | 'name' => $request->get('name'),
79 | 'value' => $request->get('value'),
80 | 'updated_at' => date_create(),
81 | ];
82 |
83 | if($item === null) {
84 | $data = array_merge($data, [
85 | 'created_at' => date_create(),
86 | ]);
87 | $result = \DB::table('translations')->insert($data);
88 | } else {
89 | $result = \DB::table('translations')->where('id', $item->id)->update($data);
90 | }
91 |
92 | if(!$result) {
93 | throw new TranslationException('Database error...');
94 | }
95 | return 'OK';
96 | }
97 |
98 | public function postTranslate(Request $request) {
99 | $text = TranslateClient::translate($request->input('origin'), $request->input('target'), $request->input('text'));
100 | $key = $request->input('key');
101 | return compact('key', 'text');
102 | }
103 |
104 | public function postDelete(Request $request)
105 | {
106 | \DB::table('translations')
107 | ->where('name', strtolower($request->get('name')))->delete();
108 | return 'OK';
109 | }
110 | }
--------------------------------------------------------------------------------
/src/DataCollector/TranslationCollector.php:
--------------------------------------------------------------------------------
1 | collect_data = $collectData;
18 | $this->name = 'translation';
19 | $this->items = array();
20 | $this->exporter = new ValueExporter();
21 | }
22 |
23 | public function getName()
24 | {
25 | return 'translation';
26 | }
27 |
28 | public function getWidgets()
29 | {
30 | return array(
31 | 'views' => array(
32 | 'icon' => 'leaf',
33 | 'widget' => 'PhpDebugBar.Widgets.TemplatesWidget',
34 | 'map' => 'translation',
35 | 'default' => '[]'
36 | ),
37 | 'views:badge' => array(
38 | 'map' => 'translation.count',
39 | 'default' => 0
40 | )
41 | );
42 | }
43 |
44 | public function addTranslation($translation)
45 | {
46 | $this->items[] = $translation;
47 | }
48 |
49 | public function collect()
50 | {
51 | $items = $this->items;
52 | return array(
53 | 'count' => count($items),
54 | 'translation' => $items,
55 | );
56 | }
57 | }
--------------------------------------------------------------------------------
/src/DatabaseLoader.php:
--------------------------------------------------------------------------------
1 | _app = $app;
13 | }
14 |
15 | /**
16 | * Load the messages for the given locale.
17 | *
18 | * @param string $locale
19 | * @param string $group
20 | * @param string $namespace
21 | * @return array
22 | */
23 | public function load($locale, $group, $namespace = null)
24 | {
25 | $query = \DB::table('translations')
26 | ->where('locale', $locale)
27 | ->where('group', $group);
28 |
29 | return ServiceProvider::pluckOrLists($query, 'value', 'name');
30 | }
31 |
32 | /**
33 | * Add a new namespace to the loader.
34 | * This function will not be used but is required
35 | * due to the LoaderInterface.
36 | * We'll just leave it here as is.
37 | *
38 | * @param string $namespace
39 | * @param string $hint
40 | * @return void
41 | */
42 | public function addNamespace($namespace, $hint) {}
43 |
44 | /**
45 | * Adds a new translation to the database or
46 | * updates an existing record if the viewed_at
47 | * updates are allowed.
48 | *
49 | * @param string $locale
50 | * @param string $group
51 | * @param string $name
52 | * @return void
53 | */
54 | public function addTranslation($locale, $group, $key)
55 | {
56 | if(!\Config::get('app.debug') || \Config::get('translation-db.minimal')) return;
57 |
58 | // Extract the real key from the translation.
59 | if (preg_match("/^{$group}\.(.*?)$/sm", $key, $match)) {
60 | $name = $match[1];
61 | } else {
62 | throw new TranslationException('Could not extract key from translation.');
63 | }
64 |
65 | $item = \DB::table('translations')
66 | ->where('locale', $locale)
67 | ->where('group', $group)
68 | ->where('name', $name)->first();
69 |
70 | $data = compact('locale', 'group', 'name');
71 | $data = array_merge($data, [
72 | 'viewed_at' => date_create(),
73 | 'updated_at' => date_create(),
74 | ]);
75 |
76 | if($item === null) {
77 | $data = array_merge($data, [
78 | 'created_at' => date_create(),
79 | ]);
80 | \DB::table('translations')->insert($data);
81 | } else {
82 | if($this->_app['config']->get('translation-db.update_viewed_at')) {
83 | \DB::table('translations')->where('id', $item->id)->update($data);
84 | }
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/ServiceProvider.php:
--------------------------------------------------------------------------------
1 | mergeConfigFrom(__DIR__.'/../config/translation-db.php', 'translation-db');
28 |
29 | $this->registerDatabase();
30 | $this->registerLoader();
31 |
32 | $this->commands($this->commands);
33 |
34 | $this->app->singleton('translator', function($app)
35 | {
36 | $loader = $app['translation.loader'];
37 | $database = $app['translation.database'];
38 |
39 | // When registering the translator component, we'll need to set the default
40 | // locale as well as the fallback locale. So, we'll grab the application
41 | // configuration so we can easily get both of these values from there.
42 | $locale = $app['config']['app.locale'];
43 |
44 | $trans = new Translator($database, $loader, $locale, $app);
45 |
46 | $trans->setFallback($app['config']['app.fallback_locale']);
47 |
48 | return $trans;
49 | });
50 |
51 |
52 | }
53 |
54 | public function boot()
55 | {
56 | $this->publishes([
57 | __DIR__.'/../database/migrations/' => database_path('/migrations')
58 | ], 'migrations');
59 |
60 | $this->publishes([
61 | __DIR__.'/../config/translation-db.php' => config_path('translation-db.php'),
62 | ]);
63 |
64 | $this->loadViewsFrom(__DIR__.'/../views', 'translation');
65 | $this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'translation');
66 |
67 | // Only in debug mode the translations interface should be available.
68 | if($this->app['config']->get('app.debug') && $this->app['config']->get('translation-db.webinterface')) {
69 | $routeConfig = [
70 | 'namespace' => 'Hpolthof\Translation\Controllers',
71 | 'prefix' => $this->app['config']->get('translation-db.route_prefix'),
72 | ];
73 | $this->app['router']->group($routeConfig, function($router) {
74 | $router->get('/', [
75 | 'uses' => 'TranslationsController@getIndex',
76 | 'as' => 'translations.index',
77 | ]);
78 | $router->get('/groups', [
79 | 'uses' => 'TranslationsController@getGroups',
80 | 'as' => 'translations.groups',
81 | ]);
82 | $router->get('/locales', [
83 | 'uses' => 'TranslationsController@getLocales',
84 | 'as' => 'translations.locales',
85 | ]);
86 | $router->post('/items', [
87 | 'uses' => 'TranslationsController@postItems',
88 | 'as' => 'translations.items',
89 | ]);
90 | $router->post('/store', [
91 | 'uses' => 'TranslationsController@postStore',
92 | 'as' => 'translations.store',
93 | ]);
94 | $router->post('/translate', [
95 | 'uses' => 'TranslationsController@postTranslate',
96 | 'as' => 'translations.translate',
97 | ]);
98 | $router->post('/delete', [
99 | 'uses' => 'TranslationsController@postDelete',
100 | 'as' => 'translations.delete',
101 | ]);
102 | });
103 | }
104 |
105 | $this->app['translation.database']->addNamespace(null, null);
106 | }
107 |
108 | /**
109 | * Register the translation line loader.
110 | *
111 | * @return void
112 | */
113 | protected function registerLoader()
114 | {
115 | $this->app->singleton('translation.loader', function($app)
116 | {
117 | return new FileLoader($app['files'], $app['path.lang']);
118 | });
119 | }
120 |
121 | protected function registerDatabase()
122 | {
123 | $this->app->singleton('translation.database', function($app)
124 | {
125 | return new DatabaseLoader($app);
126 | });
127 | }
128 |
129 | /**
130 | * Get the services provided by the provider.
131 | *
132 | * @return array
133 | */
134 | public function provides()
135 | {
136 | return array('translator', 'translation.loader', 'translation.database');
137 | }
138 |
139 | /**
140 | * Alternative pluck to stay backwards compatible with Laravel 5.1 LTS.
141 | *
142 | * @param Builder $query
143 | * @param $column
144 | * @param null $key
145 | * @return array|mixed
146 | */
147 | public static function pluckOrLists(Builder $query, $column, $key = null)
148 | {
149 | if(\Illuminate\Foundation\Application::VERSION < '5.2') {
150 | $result = $query->lists($column, $key);
151 | } else {
152 | $result = $query->pluck($column, $key);
153 | }
154 |
155 | return $result;
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/src/TranslationException.php:
--------------------------------------------------------------------------------
1 | database = $database;
14 | $this->app = $app;
15 | parent::__construct($loader, $locale);
16 | }
17 |
18 | protected static function isNamespaced($namespace)
19 | {
20 | return !(is_null($namespace) || $namespace == '*');
21 | }
22 |
23 | /**
24 | * Get the translation for the given key.
25 | *
26 | * @param string $key
27 | * @param array $replace
28 | * @param string $locale
29 | * @param bool $fallback
30 | * @return string
31 | */
32 | public function get($key, array $replace = array(), $locale = null, $fallback = true)
33 | {
34 | list($namespace, $group, $item) = $this->parseKey($key);
35 |
36 | // Here we will get the locale that should be used for the language line. If one
37 | // was not passed, we will use the default locales which was given to us when
38 | // the translator was instantiated. Then, we can load the lines and return.
39 | foreach ($this->parseLocale($locale) as $locale)
40 | {
41 | $this->load($namespace, $group, $locale);
42 |
43 | $line = $this->getLine(
44 | $namespace, $group, $locale, $item, $replace
45 | );
46 |
47 | // If we cannot find the translation group in the database nor as a file
48 | // an entry in the database will be added to the translations.
49 | // Keep in mind that a file cannot be used from that point.
50 | if(!self::isNamespaced($namespace) && is_null($line)) {
51 | // Database stuff
52 | $this->database->addTranslation($locale, $group, $key);
53 | }
54 |
55 | if ( ! is_null($line)) break;
56 | }
57 |
58 | // If the line doesn't exist, we will return back the key which was requested as
59 | // that will be quick to spot in the UI if language keys are wrong or missing
60 | // from the application's language files. Otherwise we can return the line.
61 | if ( ! isset($line)) return $key;
62 |
63 | return $line;
64 | }
65 |
66 | public function load($namespace, $group, $locale)
67 | {
68 | if ($this->isLoaded($namespace, $group, $locale)) return;
69 |
70 | // If a Namespace is give the Filesystem will be used
71 | // otherwise we'll use our database.
72 | // This will allow legacy support.
73 | if(!self::isNamespaced($namespace)) {
74 | // If debug is off then cache the result forever to ensure high performance.
75 | if(!\Config::get('app.debug') || \Config::get('translation-db.minimal')) {
76 | $that = $this;
77 | $lines = \Cache::rememberForever('__translations.'.$locale.'.'.$group, function() use ($that, $locale, $group, $namespace) {
78 | return $that->loadFromDatabase($namespace, $group, $locale);
79 | });
80 | } else {
81 | $lines = $this->loadFromDatabase($namespace, $group, $locale);
82 | }
83 | } else {
84 | $lines = $this->loader->load($locale, $group, $namespace);
85 | }
86 | $this->loaded[$namespace][$group][$locale] = $lines;
87 | }
88 |
89 | /**
90 | * @param $namespace
91 | * @param $group
92 | * @param $locale
93 | * @return array
94 | */
95 | protected function loadFromDatabase($namespace, $group, $locale)
96 | {
97 | $lines = $this->database->load($locale, $group, $namespace);
98 |
99 | if (count($lines) == 0 && \Config::get('translation-db.file_fallback', false)) {
100 | $lines = $this->loader->load($locale, $group, $namespace);
101 | return $lines;
102 | }
103 |
104 | return $lines;
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/views/index.blade.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | {{ trans('translation::manager.title') }}
8 |
9 |
10 |
11 |
12 | @include('translation::javascript')
13 | @include('translation::style')
14 |
15 |
16 |
17 |