-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFluency.module.php
executable file
·1319 lines (1157 loc) · 45.3 KB
/
Fluency.module.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// FileCompiler=0
declare(strict_types=1);
namespace ProcessWire;
$namespaces = [
'Fluency\App' => '/app',
'Fluency\Caching' => '/app/Caching',
'Fluency\Components' => '/app/Components',
'Fluency\DataTransferObjects' => '/app/DataTransferObjects',
'Fluency\Engines' => '/app/Engines',
'Fluency\Functions' => '/app/Functions',
'Fluency\Services' => '/app/Services',
];
foreach ($namespaces as $namespace => $directory) {
wire('classLoader')->addNamespace($namespace, __DIR__ . $directory);
}
require_once __DIR__ . '/app/Functions/fluencyEngineConfigNames.php';
use Fluency\App\{
FluencyLocalization as Localization,
FluencyMarkup as Markup,
FluencyErrors as Errors,
};
use Fluency\Caching\{ TranslationCache, EngineLanguagesCache };
use Fluency\Components\{
FluencyApiUsageTableFieldset as ApiUsageTableFieldset,
FluencyStandaloneTranslatorFieldset as StandaloneTranslatorFieldset,
};
use Fluency\DataTransferObjects\{
AllConfiguredLanguagesData,
ConfiguredLanguageData,
EngineApiUsageData,
EngineInfoData,
EngineLanguageData,
EngineTranslatableLanguagesData,
EngineTranslationData,
FluencyConfigData,
TranslationRequestData,
};
use Fluency\Engines\FluencyEngine;
use Fluency\Services\FluencyProcessWireFileTranslator as ProcessWireFileTranslator;
use InvalidArgumentException;
use ProcessWire\FluencyConfig;
use RuntimeException;
use stdClass;
use function Fluency\Functions\{
arrayContainsOnlyInstancesOf,
arrayContainsOnlyType,
createLanguageConfigName,
};
/**
* #pw-summary The complete translation suite module for ProcessWire
*
* #pw-body =
*
* Fluency provides translation service integrations via ProcessWire admin pages and Inputfields for
* use by users, a module interface for ProcessWire developers anywhere, and a RESTful API that can
* be used by developers within the admin. Fluency utilizes Data Transfer Objects as the method used
* to pass data to, and receive data from, methods throughout the Fluency codebase. References are
* provided for each function in this documentation where they are used and should be expected as
* return values.
*
* Fluency is modular and provides a framework for adding additional translation services as
* Translation Engines. Each engine is a self-contained set of classes that provides information
* about the Translation Engine, individual configurations, and the translator implementation itself.
*
* For more information regarding Translation Engine development, reference the documentation file
* at `Fluency/app/Engines/DEVDOC.md`
*
* #pw-body
*
*/
final class Fluency extends Process implements Module, ConfigurableModule {
/**
* The attribute applied to fields at render time where translation is disabled
*/
private const TRANSLATION_DISABLED_FIELD_ATTR = 'data-ft-disable-translation';
private ?FluencyEngine $translationEngine = null;
private ?EngineInfoData $translationEngineInfo = null;
private ?FluencyConfigData $fluencyConfig = null;
private ?TranslationCache $translationCache = null;
private ?EngineLanguagesCache $engineLanguagesCache = null;
private ?ProcessWireFileTranslator $processWireFileTranslator = null;
/**
* Memoizing Fluency::getConfiguredLanguages() output
*/
private ?AllConfiguredLanguagesData $configuredLanguages = null;
/**
* Path to Fluency JS scripts
*/
private ?string $moduleJsPath = null;
/**
* Path to Fluency CSS files
*/
private ?string $moduleCssPath = null;
/**
* Make Fluency available globally via $fluency
*
* @return void
*/
public function init() {
$this->fluencyConfig = (new FluencyConfig())->getConfigData();
if (!$this->translationEngineIsReady()) {
return;
}
// Create global $fluency variable
$this->wire->set('fluency', $this);
$this->moduleJsPath = "{$this->urls->$this}assets/scripts/";
$this->moduleCssPath = "{$this->urls->$this}assets/styles/";
$this->initializeCaches();
$this->initializeTranslationEngine();
$this->processWireFileTranslator = new ProcessWireFileTranslator($this);
}
/**
* Executes admin UI when PW is ready
* @return void
*/
public function ready() {
if (!$this->moduleShouldInitInAdmin()) {
return false;
}
$this->registerFieldConfigurationHooks();
$this->registerFieldRenderHooks();
$this->insertAdminAssets();
}
/**
* ProcessWire languages are configured within Fluency and translation is available for admin Inputfields
*
* Requires that:
* - The default ProcessWire language has been configured in Fluency
* - At least one additional language has been configured in Fluency
* - The Translation Engine has been configured and is ready to process requests
*
* #pw-notes Requires that ProcessWire languages are configured in Fluency
*
* #pw-group-Translation-Readiness
*
* @return bool
*/
public function inputfieldTranslationIsReady(): bool {
return $this->translationEngineIsReady() && count($this->getConfiguredLanguages()) >= 2;
}
/**
* Translation Engine has been configured and is ready to process requests
*
* This indicates that the Translation Engine authenticates and is able to send and receive data
* via the corresponding translation service API. This is separate from
* Fluency::inputfieldTranslationIsReady() in that it does not indicate whether languages have
* been configured within Fluency.
*
* Requires that:
*
* - A Translation Engine is selected in Fluency
* - The Translation Engine is configured in Fluency and ready
* - The translation service API used by the engine successfuly accepts/returns requests
*
* #pw-notes Does not require ProcessWire languages to be configured in Fluency
*
* #pw-group-Translation-Readiness
*
* @return bool
*/
public function translationEngineIsReady(): bool {
return $this->fluencyConfig?->translation_api_ready ?? false;
}
/**
* Adds ability to disable translation per-field when configuring multi-language fields
*/
private function registerFieldConfigurationHooks(): void {
$localization = Localization::getFor('fieldConfiguration');
// Adds a "Disable Fluency" checkbox for a hooked field configuration
$addCheckbox = function(HookEvent $e) use ($localization): void {
$field = $e->arguments(0);
$checkbox = $this->modules->InputfieldCheckbox;
$checkbox->icon = 'language';
$checkbox->attr('name', 'ftDisableTranslation');
$checkbox->label = $localization->checkboxTitle;
$checkbox->checkboxLabel = $localization->checkboxLabel;
$checkbox->checkedValue = 1;
$checkbox->uncheckedValue = 0;
$checkbox->checked((bool) $field->get('ftDisableTranslation'));
$e->return->add($checkbox);
};
$this->wire->addHookAfter("FieldtypeTextLanguage::getConfigInputfields", $addCheckbox);
$this->wire->addHookAfter("FieldtypeTextAreaLanguage::getConfigInputfields", $addCheckbox);
}
/**
* Renders multi-language fields without translation abilities where configured
*/
private function registerFieldRenderHooks(): void {
$disableTranslation = function(HookEvent $e): void {
$inputfield = $e->object;
if (!$inputfield->useLanguages || !$inputfield->hasField?->ftDisableTranslation) {
return;
}
$e->object->setAttribute(self::TRANSLATION_DISABLED_FIELD_ATTR, '');
};
$this->wire->addHookBefore("InputfieldTextArea::render", $disableTranslation);
$this->wire->addHookBefore("InputfieldText::render", $disableTranslation);
}
/**
* Determine if module should initialize
*/
private function moduleShouldInitInAdmin(): bool {
return $this->page->name !== 'login' && $this->userIsAuthorized() && !!$this->fluencyConfig;
}
/**
* Creates the Translation Engine, engine config, and engine info objects for the module
*/
private function initializeTranslationEngine(): void {
$selectedEngine = $this->fluencyConfig?->selected_engine;
if (!$selectedEngine) {
return;
}
$this->translationEngine = new $selectedEngine->engineClass($this->fluencyConfig);
$this->translationEngineInfo = $selectedEngine->info();
}
/**
* Create instances of cachaes
*/
private function initializeCaches(): void {
$this->translationCache = new TranslationCache();
$this->engineLanguagesCache = new EngineLanguagesCache();
}
/**
* User is authorized to use Fluency and translation features
*/
private function userIsAuthorized(): bool {
return $this->user->isSuperuser() || $this->user->hasPermission('fluency-translate');
}
/**
* Inserts required assets into admin pages on load.
*/
private function insertAdminAssets(): void {
if ($this->page->rootParent->id !== 2 ) {
return;
}
$this->config->js('fluency', $this->getClientData());
match ($this->page->name) {
'module' => $this->insertFluencyConfigPageAssets(),
'language-translator' => $this->insertProcessWireLanguageTranslatorAssets(),
default => $this->insertCoreAssets(),
};
}
/**
* Insert core styles and scripts for use on pages where Inputfield translation is desired
*/
private function insertCoreAssets(): void {
$this->config->styles->add("{$this->moduleCssPath}fluency_core.min.css");
$this->config->scripts->add("{$this->moduleJsPath}fluency.bundle.js");
}
/**
* Insert config page assets, only does if the config page is Fluency
*/
private function insertFluencyConfigPageAssets(): void {
if ($this->input->get->name === 'Fluency') {
$this->config->styles->add("{$this->moduleCssPath}fluency_module_config.min.css");
$this->config->scripts->add("{$this->moduleJsPath}fluency_module_config.bundle.js");
}
}
/**
* Inserts assets for use on ProcessWire's Language Support translation pages
*/
private function insertProcessWireLanguageTranslatorAssets(): void {
if ($this->input->urlSegment(1) === 'add') {
return;
}
$this->config->js('fluency', $this->getClientData());
$this->config->styles->add("{$this->moduleCssPath}fluency_core.min.css");
$this->config->scripts->add("{$this->moduleJsPath}fluency_language_translator.bundle.js");
}
/**
* Insert styles and scripts for use by the Standalone Translator
*
* #pw-internal
*/
public function insertStandaloneTranslatorAssets(): void {
$this->config->js('fluency', $this->getClientData());
$this->config->scripts->add("{$this->moduleJsPath}fluency_standalone_translator.bundle.js");
$this->config->styles->add("{$this->moduleCssPath}fluency_standalone_translator.min.css");
}
/**
* Insert styles and scripts for use by the API Usage Table
*
* #pw-internal
*/
public function insertApiUsageTableFieldsetAssets(): void {
$this->config->js('fluency', $this->getClientData());
$this->config->scripts->add("{$this->moduleJsPath}fluency_api_usage.bundle.js");
$this->config->styles->add("{$this->moduleCssPath}fluency_api_usage.min.css");
}
/**
* Module actions and Translation Engine interfaces
*/
/**
* Get all ProcessWire languages configured in Fluency
* Return AllConfiguredLanguagesData object contains methods to access specific configured
* languages by property/value
*
* #pw-group-Fluency-Module-Configuration-Data
*
* @return AllConfiguredLanguagesData
*
* Reference `Fluency/app/DataTransferObjects/AllConfiguredLanguagesData.php`
* and `Fluency/app/DataTransferObjects/ConfiguredLanguageData.php`
*/
public function getConfiguredLanguages(): AllConfiguredLanguagesData {
$engineInfo = $this->translationEngineInfo;
if (!$engineInfo?->configId) {
return AllConfiguredLanguagesData::fromArray([
'languages' => []
]);
}
if (!is_null($this->configuredLanguages)) {
return $this->configuredLanguages;
}
$createConfiguredLanguage = function($configured, Language $pwLanguage) {
$configuredLanguage = $this->getConfiguredLanguageByProcessWireId($pwLanguage->id);
// If this ProcessWire language is not configured in Fluency, skip.
if (!$configuredLanguage) {
return $configured;
}
$configured[] = $configuredLanguage;
return $configured;
};
$processWireLanguages = array_values($this->languages->getIterator()->getArray());
$languages = array_reduce($processWireLanguages, $createConfiguredLanguage, []);
// Create an array of Fluency configured language object from an array of ProcessWire languages
return $this->configuredLanguages = AllConfiguredLanguagesData::fromArray([
'languages' => $languages,
]);
}
/**
* Gets a language configured in Fluency using it's ProcessWire ID. Internal use only.
*
* To get a Fluency configured langauge via it's ProcessWire ID, please use:
* $fluency->getConfiguredLanguages()->getLangaugeByProcessWireId(int $id);
*
* #pw-internal
*
* @param int $processWireId ProcessWire language ID
* @return ConfiguredLanguageData|null Null if language is not configured within Fluency
*
* Reference `Fluency/app/DataTransferObjects/ConfiguredLanguageData.php`
*/
private function getConfiguredLanguageByProcessWireId(
int $processWireId
): ?ConfiguredLanguageData {
if (!$this->translationEngineInfo) {
return null;
}
$configuredLanguage = $this->{createLanguageConfigName($processWireId, $this->translationEngineInfo)};
// If this ProcessWire language is not configured in Fluency, skip.
if (!$configuredLanguage) {
return null;
}
$pwLanguage = $this->languages->get($processWireId);
$pwTitle = $pwLanguage->title;
$userLanguage = $this->user->language;
// ProcessWire\Language::$title may return an object depending on context.
is_object($pwTitle) && $pwTitle = $pwLanguage->title->getLanguageValue($userLanguage);
return ConfiguredLanguageData::fromArray([
'id' => $processWireId,
'title' => $pwTitle,
'default' => $pwLanguage->name === 'default',
'engineLanguage' => EngineLanguageData::fromJson($configuredLanguage),
'isCurrentLanguage' => $pwLanguage === $userLanguage
]);
}
/**
* Get an array of ProcessWire language IDs that are not configured in Fluency
*
* #pw-group-Fluency-Module-Configuration-Data
*
* @return array<int>
*/
public function getUnconfiguredLanguages(): array {
if ($this->unconfiguredLanguages) {
return $this->unconfiguredLanguages;
}
$languageIds = array_map(
fn($language) => $language->id,
array_values($this->languages->getIterator()->getArray())
);
$configuredLanguages = $this->getConfiguredLanguages();
$unconfiguredLanguages = array_filter(
$languageIds,
fn($languageId) => !$configuredLanguages->getByProcessWireId($languageId)
);
return $this->unconfiguredLanguages = array_values($unconfiguredLanguages);
}
/**
* Gets all configuration data in one object. Can be passed into the ProcessWire JavaScript
* config object
*
* #pw-group-Fluency-Module-Configuration-Data
*
* @return stdClass All data needed by client UI scripts.
*/
public function getClientData(): stdClass {
return (object) [
'apiEndpoints' => $this->getApiEndpoints(),
'configuredLanguages' => $this->getConfiguredLanguages()->languages,
'unconfiguredLanguages' => $this->getUnconfiguredLanguages(),
'localization' => Localization::getAll(),
'engine' => $this->getTranslationEngineInfo(),
'interface' => [
'inputfieldTranslationAction' => $this->fluencyConfig?->inputfield_translation_action,
'translationDisabledFieldAttr' => self::TRANSLATION_DISABLED_FIELD_ATTR,
],
];
}
/**
* Developer Tools
*/
/**
* Translate files used by ProcessWire to one or more languages
*
* Translate any file that ProcessWire uses such as templates, modules, or any where the `__()`
* translation function is present. These may be located anywhere on the filesystem including in
* `site/*` and `wire/*`. This will parse the files passed to the method, find all untranslated
* strings, create default language translation files where they exist, and add strings found to
* them. Then all values translated to the specified languages.
*
* **Note:** This has the potential to be an "expensive" operation with high API usage. It is
* important to be aware of the amount of translations that will occur and the number of strings
* in files.
*
* **Important:** this relies the internal `translator()` method on the ProcessWire `Language`
* object. This feature in Fluency is considered stable however is subject to ProcessWire core
* changes. Please report any problems by filing an issue on the Fluency Github repository.
*
* ~~~~~
* // Files must be the full file name with path from the root directory
*
* // A single file to all languages
* $fluency->translateProcessWireFiles('site/templates/home.php');
*
* // Multiple files to all languages
* $fluency->translateProcessWireFiles([
* 'site/templates/home.php',
* 'site/modules/FieldtypeRepeaterMatrix/InputfieldRepeaterMatrix.module',
* 'wire/modules/Inputfield/InputfieldText/InputfieldText.module',
* ]);
*
* // Using one or more ProcessWire IDs languages
* $fluency->translateProcessWireFiles([
* 'site/templates/home.php',
* 'site/modules/FieldtypeRepeaterMatrix/InputfieldRepeaterMatrix.module',
* ], [1028, 1032]);
*
* // Create the required default language files before translating
* $fluency->translateProcessWireFiles([
* 'site/templates/home.php',
* 'site/modules/FieldtypeRepeaterMatrix/InputfieldRepeaterMatrix.module',
* ], [1028, 1032], true);
*
* // Using one or more ConfiguredLanguageData objects
* $targetLanguages = $fluency->getConfiguredLanguages()->getByProcessWireTitle(['French', 'German']);
*
* $fluency->translateProcessWireFiles('site/templates/home.php', $targetLanguages);
* ~~~~~
*
*
* #pw-group-Developer-Tools
*
* @param string|array<string> $files ProcessWire file(s) to translate, with path from root
* @param int|ConfiguredLanguageData|null $targetLanguages Language(s) to translate files to. Must
* not be or include the default language
* @param bool $createDefaultFiles Create default files required for translating first
* @return stdClass Object containing the number of files translated and target languages
* @throws RuntimeException
* @throws InvalidArgumentException
*/
public function translateProcessWireFiles(
string|array $files,
int|ConfiguredLanguageData|array|null $targetLanguages = null,
bool $overwriteExistingTranslations = false
): stdClass {
!$this->inputfieldTranslationIsReady() && throw new RuntimeException(
Errors::getMessage(Errors::FLUENCY_NOT_CONFIGURED)
);
$configuredLanguages = $this->getConfiguredLanguages()->withoutDefault();
$files = (array) $files;
$targetLanguages = (array) $targetLanguages ?: $configuredLanguages->languages;
$targetsAreIds = arrayContainsOnlyType($targetLanguages, 'integer');
$targetsDTOs = arrayContainsOnlyInstancesOf($targetLanguages, ConfiguredLanguageData::class);
// Handle array of incorrect target language values
!$targetsAreIds && !$targetsDTOs && throw new InvalidArgumentException(
Errors::getMessage(Errors::FLUENCY_PW_FILE_INVALID_TARGET_LANGUAGE)
);
$targetsAreIds && $targetLanguages = $configuredLanguages->getByProcessWireId($targetLanguages);
$targetLanguageIds = array_map(fn($language) => $language->id, $targetLanguages);
$defaultLanguageId = $this->getConfiguredLanguages()->getDefault()->id;
in_array($defaultLanguageId, $targetLanguageIds) && throw new InvalidArgumentException(
Errors::getMessage(Errors::FLUENCY_PW_FILE_TO_DEFAULT_LANGUAGE)
);
return $this->processWireFileTranslator->translateForProcessWire(
$files,
$targetLanguages,
$overwriteExistingTranslations
);
}
/**
* Get a language code by ProcessWire language ID, falls back to current language without ID
*
* The language code returned is defined by the translation service. The format and style may
* differ depending on the Translation Engine currently in use
*
* #pw-group-Developer-Tools
*
* @param int $processWireId ProcessWire language ID
* @param string $languageSource 'fluency' to render using Fluency configured languages or
* 'processwire' to render using all languages in processwire
* Default: 'fluency'
* @return string|null
* @throws InvalidArgumentException
*/
public function getLanguageCode(
?int $processWireId = null,
string $languageSource = 'fluency'
): ?string {
$pwId = $processWireId ?? $this->user->language->id;
return array_reduce(
$this->getLanguagesForMarkup($languageSource),
fn ($code, $language) => $code = $language->id === $pwId ? strtolower($language->code) : $code
);
}
/**
* Render alt language meta tags for use in the document <head> element
*
* Increases page SEO quality and adherance to HTML standards
*
* By default this outputs HTML tags only for languages configured within Fluency as the language
* codes needed are acquired through the
*
* To use ProcessWire languages it is necessary to add an additional text field called
* `language_code` to the `language` system template and provide values for each language.
* Languages without a value will not be rendered in the markup.
*
* ~~~~~
* <link rel="alternate" hreflang="https://awesomewebsite.com/" href="x-default" />
* <link rel="alternate" hreflang="https://awesomewebsite.com/" href="en-us" />
* <link rel="alternate" hreflang="https://awesomewebsite.com/fr/" href="fr" />
* <link rel="alternate" hreflang="https://awesomewebsite.com/de/" href="de" />
* <link rel="alternate" hreflang="https://awesomewebsite.com/it/" href="it" />
* <link rel="alternate" hreflang="https://awesomewebsite.com/es/" href="es" />
* ~~~~~
*
* #pw-group-Developer-Tools
*
* @param string $languageSource 'fluency' to render using Fluency configured languages or
* 'processwire' to render using all languages in processwire
* Default: 'fluency'
* @return string
* @throws InvalidArgumentException
*/
public function renderAltLanguageMetaLinkTags(string $languageSource = 'fluency'): string {
$languages = $this->getLanguagesForMarkup($languageSource);
$allTags = array_map(
fn($language) => Markup::altLanguageLink(
href: $this->page->localHttpUrl($this->languages->get($language->id)),
hrefLang: strtolower($language->code)
),
$languages
);
$defaultTag = Markup::altLanguageLink(
hrefLang: $this->page->localHttpUrl($this->languages->get('name=default')),
href: 'x-default'
);
array_unshift($allTags, $defaultTag);
return implode("\n", $allTags);
}
/**
* Render an accessible language select element with options for each language. Options array
* allows additional configuration. Optional inline JS that navigates to page in language on
* select can be added.
*
* By default, select options are created only for languages configured within Fluency as the
* language codes needed are acquired through the Translation Engine
*
* To use ProcessWire languages as the `$languageSource` it is necessary to add an additional text
* field called `language_code` to the `language` system template and provide values for each.
* Languages without a value will not be rendered in the markup.
*
* #pw-group-Developer-Tools
*
* @param bool $addInline Include inline JS that navigates on select
* @param string $id Optional value for `<select>` id attribute
* @param string|array $classes Optional value for `<select>` id attribute
* @param string $languageSource Pass 'fluency' to render using Fluency configured languages or
* 'processwire' to render using all languages in processwire
* Default: 'fluency'
* @return string
* @throws InvalidArgumentException
*/
public function renderLanguageSelect(
bool $addInlineJs = true,
string $id = '',
string|array $classes = [],
string $languageSource = 'fluency'
): string {
// Create option elements from language IDs
$options = array_reduce(
$this->getLanguagesForMarkup($languageSource),
fn($tags, $language) => $tags .= Markup::selectOption(
value: $this->page->localUrl($language->id),
selected: $language->isCurrentLanguage,
label: $language->title
),
''
);
return Markup::languageSelect(
classes: $classes,
addInlineJs: $addInlineJs,
options: $options,
id: $id
);
}
/**
* Render an unordered list of links that change the language shown on the current page
*
* By default, select options are created only for languages configured within Fluency as the
* language codes needed are acquired through the Translation Engine
*
* To use ProcessWire languages it is necessary to add an additional text field called
* `language_code` to the `language` system template and provide values for each language.
* Languages without a value will not be rendered in the markup.
*
* #pw-group-Developer-Tools
*
* @param string|array|null $classes Classes to add to <ul> element
* @param string $id ID to add to <ul> element
* @param string $activeClass Class added to the <li> element containing the link for the
* current page.
* @param string $divider String wrapped in <li> added between link <li> elements
* @param string $languageSource 'fluency' to render using Fluency configured languages or
* 'processwire' to render using all languages in processwire
* Default: 'fluency'
* @return string
*/
public function renderLanguageLinks(
string|array|null $classes = null,
string $id = '',
string $divider = null,
?string $activeClass = 'active',
string $languageSource = 'fluency',
): string {
$languages = $this->getLanguagesForMarkup($languageSource);
$divider && $divider = Markup::li(content: $divider, classes: 'divider');
$items = array_reduce($languages, function($tags, $language) use ($activeClass, $divider) {
$tags[] = Markup::li(
classes: $language->isCurrentLanguage ? $activeClass : null,
content: Markup::a(
href: $this->page->localUrl($language->id),
content: $language->title,
)
);
$divider && $tags[] = $divider;
return $tags;
}, []);
end($items) === $divider && array_pop($items);
return Markup::ul(items: $items, classes: $classes ?? '', id: $id);
}
/**
* Gets languages for markup
*
* NOTE: If 'processwire' is passed, a field with the name 'code' must be added to the language
* system template. Passing 'fluency' will automatically use the language codes provided by the
* translation service.
*
* @param string $source Either 'fluency' or 'processwire'
* @throws InvalidArgumentException
*/
private function getLanguagesForMarkup(string $source = 'fluency'): array {
return match ($source) {
'fluency' => $this->getFluencyLanguagesForMarkup(),
'processwire' => $this->getProcessWireLanguagesForMarkup(),
default => throw new InvalidArgumentException(
"Argument passed must be either 'fluency' or 'processwire', '{$source}' given"
),
};
}
/**
* Creates an array of data used by getLanguagesForMarkup
*/
private function getProcessWireLanguagesForMarkup(): array {
$this->fields->get('language_code');
$languageFields = $this->templates->get('name=language')->fields;
$fieldNames = array_values($this->fieldgroups->getFieldNames($languageFields));
if (!in_array('language_code', $fieldNames)) {
throw new InvalidArgumentException(
"Failed to render alt language link tags for ProcessWire languages. A text field with " .
"the name 'code' must be added to the ProcessWire 'language' system template"
);
}
$languages = array_map(
fn($language) => !$language->code ? null : (object) [
'id' => $language->id,
'code' => $language->code,
'title' => $language->title,
'isCurrentLanguage' => $language->id === $this->user->language->id
],
$this->languages->getIterator()->getArray()
);
return array_filter($languages);
}
/**
* Creates an array of data used by getLanguagesForMarkup
*/
private function getFluencyLanguagesForMarkup(): array {
return array_map(
fn($language) => (object) [
'id' => $language->id,
'code' => $language->engineLanguage->targetCode,
'title' => $language->title,
'isCurrentLanguage' => $language->id === $this->user->language->id
],
$this->getConfiguredLanguages()->languages
);
}
/**
* Fluency Caching
*/
/**
* Get the number of translations in cache for currently selected Translation Engine
*
* #pw-group-Caching
*
* @return int
*/
public function getCachedTranslationsCount(): int {
return $this->translationCache->count();
}
/**
* Clear all cached translations for the currently selected Translation Engine
*
* #pw-group-Caching
*
* @return int The number of cached translations, zero indicates success
*/
public function clearTranslationCache(): int {
return $this->translationCache->clear();
}
/**
* Clear cached translatable languages list for the currently selected Translation Engine
*
* Cached language lists are never automatically cleared. If a translation service has
* released new languages but are not appearing within Fluency as avalable, clear this cache.
*
* #pw-group-Caching
*
* @return int Number of cached translatable languages, zero indicates success
*/
public function clearTranslatableLanguagesCache(): int {
return $this->engineLanguagesCache->clear();
}
/**
* Determine if translatable languages are currently cached
*
* #pw-group-Caching
*
* @return bool
*/
public function translatableLanguagesAreCached(): bool {
return (bool) $this->engineLanguagesCache->count();
}
/**
* Deletes all caches used by Fluency
*
* #pw-group-Caching
*
* @return int Number of items remaining in cache, zero indicates success
*/
public function clearAllCaches(): int {
$translatableLanguages = $this->clearTranslatableLanguagesCache();
$translations = $this->clearTranslationCache();
return $translatableLanguages + $translations;
}
/**
* Translation Engine Interfaces
*/
/**
* Translate content from one language to another
*
* ~~~~~
* $result = $fluency->translate('EN', 'DE', 'How do you do, fellow developers?');
*
* // Access data using their properties
* $result->translations; // => ['Wie geht es Ihnen, liebe Entwicklerfreunde?']
* $result->content; // => ['How do you do, fellow developers?']
* $result->error; // => null or Fluency\App\Errors constant value
* $result->fromCache; // => false
* $result->retrievedAt; // => '2023-08-25T23:35:09+00:00'
*
* // This also contains an EngineLanguageData object for both source and target languages
* $result->sourceLanguage->sourceCode; // => DE
* $result->sourceLanguage->sourceName; // => German
* $result->sourceLanguage->targetCode; // => DE
* $result->sourceLanguage->targetName; // => German
* $result->sourceLanguage->meta; // => [] (Usage varies by Translation Engine)
*
* // Return object can be converted to an array
* $result->toArray();
*
* // Return object can be directly converted to json
* $json = json_encode($result);
*
* // The number of translations can be found using count
* $translationCount = count($result)
* ~~~~~
*
* #pw-group-Translation-Engine-Interface
*
* @param string $sourceLanguage Translation language code
* @param string $targetLanguage Translation language code
* @param string|array $content Multiple translations in an array are per-Engine based on translation service
* @param array $options Additional options defined and used by the Translation Engine
* @param bool $caching Can override module config per-request
* @return EngineTranslationData
*
* Reference `Fluency/app/DataTransferObjects/EngineTranslationData.php`
* and `Fluency/app/DataTransferObjects/EngineLanguageData.php`
* and `Fluency/App/Errors.php`
*/
public function translate(
string $sourceLanguage = '',
string $targetLanguage = '',
array|string $content = [],
?array $options = [],
?bool $caching = null
): EngineTranslationData {
$source = $this->getTranslatableLanguages()->bySourceCode($sourceLanguage);
$target = $this->getTranslatableLanguages()->byTargetCode($targetLanguage);
$requestData = [
'sourceLanguage' => $source?->sourceCode ?? $sourceLanguage,
'targetLanguage' => $target?->targetCode ?? $targetLanguage,
'content' => (array) $content,
'options' => $options ?? []
];
$request = TranslationRequestData::fromArray($requestData);
if (!$source || !$target) {
$error = !$source ? Errors::FLUENCY_UNKNOWN_SOURCE
: Errors::FLUENCY_UNKNOWN_TARGET;
return EngineTranslationData::fromArray(['request' => $request, 'error' => $error]);
}
// If caching is overridden in this method call, if null fall back to module config setting
if ($caching ?? $this->fluencyConfig->translation_cache_enabled) {
return $this->translationCache->getOrStoreNew(
$request,
fn() => $this->translationEngine->translate($request)
);
}
return $this->translationEngine->translate($request);
}
/**
* Gets the current translation API usage
*
* If this feature is not available via the translation service API, the return object will
* contain FluencyError::FLUENCY_NOT_IMPLEMENTED for the error property
*
* // Return object can be converted to an array
* $result->toArray();
*
* // Return object can be directly converted to json
* $json = json_encode($result);
*
* #pw-group-Translation-Engine-Interface
*
* @return EngineApiUsageData
*
* Reference `Fluency/app/DataTransferObjects/EngineApiUsageData.php`
* and `Fluency/app/Errors.php`
*/
public function getTranslationApiUsage(): EngineApiUsageData {
return $this->translationEngine->getApiUsage();
}