I have a translate("")
function and I want PhpStorm to start suggesting values from a JSON file when I start typing between the quotes.
The idea is that I have a JSON file with translation strings and when I start typing it should suggest translations which are already included in that json file, based on the characters I already typed of course.
After some research, I do not think this is currently possible in PhpStorm, but maybe someone here has an idea or an alternative.
Thanks!
I made it work using PhpStorm advanced metadata.
I created a .phpstorm.meta.php
file in the project root, this will add auto completion/suggestions for the first (0
) argument of the translate
method:
<?php
namespace PHPSTORM_META {
expectedArguments(
\App\Helper\TranslationHelper::translate(),
0,
/* Generated */
"Auto completion result",
"This is also a suggested result",
"Give me more suggestions PhpStorm",
/* Generated */
);
}
And then wrote a Symfony command that takes strings from my translation file and includes them between the two /* Generated */
comments:
$translations = json_decode(file_get_contents($this->parameterBag->get('app.project.path') . '/resources/translations/de.json'), true);
$metadataPath = $this->parameterBag->get('app.project.path') . '/.phpstorm.meta.php';
$identifier = "/* Generated */";
$regexIdentifier = $this->escape($identifier);
$regex = "/$regexIdentifier(.*?)$regexIdentifier/s";
// Build the arguments string that will be written into the metadata file
$translationsAsArguments = "$identifier\n";
foreach ($translations as $translation) {
$translationsAsArguments .= "\t\t\"$translation\",\n";
}
$translationsAsArguments .= "\t\t$identifier";
// Write to disk
$translationsMetadata = preg_replace($regex, $translationsAsArguments, file_get_contents($metadataPath));
file_put_contents($metadataPath, $translationsMetadata);
This solution was written with PHP using Symfony 6.3