odionk's avatar

replace all string to @lang()

Hello Artisan in my laravel blade file i have my string as e.g {{__('test string')}} and some as Test string without bracket, my question is there any way i can use vscode to update all string to into @lang('test string') in all blade file?

0 likes
3 replies
Snapey's avatar

How could it possibly know what needs changing?

odionk's avatar
odionk
OP
Best Answer
Level 1

@snapey this simple function i create did all the magic in speed

public function generateKey(){
    // Set the path to your views folder
    $viewsPath = resource_path('views');

    // Find all files in the views folder and its subdirectories
    $allFiles = File::allFiles($viewsPath);

    // Initialize an array to store translation keys and their translations
    $translationData = [];

    // Iterate through each file
    foreach ($allFiles as $file) {
        // Read the contents of the file
        $contents = File::get($file->getPathname());

        // Use a regular expression to find @lang occurrences
        preg_match_all('/@lang\([\'"]([^\'"]+)[\'"]\)/', $contents, $matches);

        // Iterate through found translation keys
        foreach ($matches[1] as $key) {
            // Check if the key is not already in the array
            if (!array_key_exists($key, $translationData)) {
                // Translate the key using the translate function
                $translatedValue = $this->translate($key);

                // Add the translation data to the array
                $translationData[$key] = $translatedValue;
            }
        }
    }

    // Convert the array to JSON format
    $jsonContent = json_encode($translationData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

    // Save the JSON to a file (adjust the path as needed)
    File::put(resource_path('lang/keys.json'), $jsonContent);

    echo "Translation keys have been saved to keys.json\n";
}

public function translate($sourceText) {
    $sourceLang = 'en';
    $targetLang = 'es';

    $url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=".$sourceLang."&tl=".$targetLang."&dt=t&q=".urlencode($sourceText);

    // Use Laravel HTTP client to make the API request
    $response = Http::get($url);

    // Decode the JSON response
    $data = $response->json();

    // Extract the translated text
    $translatedText = $data[0][0][0];

    // Return the translated text 
    return $translatedText;
}

first it get all the @lang() in all blade file , then store them in json file unique and also translate to any language easily ,just a get route URL to call the function and it did the magic for me

Snapey's avatar

Check your question. Thats not what you asked about.

1 like

Please or to participate in this conversation.