diff --git a/CHANGELOG.md b/CHANGELOG.md index e6190f2..3953217 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # Release Notes for Craft Generator ## Unreleased +- Added `craft\generator\BaseGenerator::messageTwig()`. ([#25](https://github.com/craftcms/generator/pull/25)) - The plugin generator now ensures that the project’s `composer.json` file has `minimum-stability: dev` and `prefer-stable: true` set. ([#22](https://github.com/craftcms/generator/issues/22)) - Fixed a bug where the Service generator was suggesting adding a `config()` method which defined the service config, even when the target was a module. ([#24](https://github.com/craftcms/generator/issues/24)) diff --git a/src/BaseGenerator.php b/src/BaseGenerator.php index 7835b34..571040b 100644 --- a/src/BaseGenerator.php +++ b/src/BaseGenerator.php @@ -733,13 +733,45 @@ protected function namespacePath(string $namespace): string protected function messagePhp(string $message): string { $messagePhp = var_export($message, true); - $category = match (true) { + $category = $this->translationCategory(); + + return $category ? sprintf("Craft::t('%s', %s)", $category, $messagePhp) : $messagePhp; + } + + /** + * Places a string into a Twig translation statement. + * + * Output is not enclosed in any `{{ ... }}` or `{% ... %}` tags. + * + * @param string $message The string to output + * @return string Twig statement + * @since 1.6.0 + */ + protected function messageTwig(string $message): string + { + $messageTwig = var_export($message, true); + $category = $this->translationCategory(); + + return $category ? sprintf("'%1\$s\'|t('%2\$s\', %1\$s)", $category, $messageTwig) : $messageTwig; + } + + /** + * Resolves an appropriate translation category for the target module/component. + * + * The result is not guaranteed to be valid: + * - Modules can register translation categories with any handle/ID they like (and the ID of a module can change at any time); + * - Plugins may register additional translation categories (non-standard) that we don’t/can’t know about; + * - The `site` translation category used by the front-end (and some modules) is not taken into consideration; + * + * @return string|null Translation category handle + */ + private function translationCategory(): ?string + { + return match (true) { $this->module instanceof Application => 'app', $this->module instanceof PluginInterface => $this->module->id, default => null, }; - - return $category ? sprintf("Craft::t('%s', %s)", $category, $messagePhp) : $messagePhp; } /**