phplaraveltranslation

PHP Laravel, identify not used translations


I was thinking if there is a way to identify unused translation keys in laravel using regular underscore translation?


Solution

  • If you are using the translations in loop using some patterns, this won't work and you might end up deleting keys which were in use.

    One of the way would be to use grep

    First, open tinker

    php artisan tinker
    

    Then require the translation file and store it against a variable

    $translations = require resource_path('lang/en/app.php');
    

    The $translations variable would contain the array that is returned by the translation file.

    Loop through the array and use grep against each key

    $unused_keys = [];
    
    foreach ($translations as $key => $value) {
    
        // Here app is the name of the translation file
        // that was required in first step.
        // Replace app with the name of the translation file that is been required.
    
        $out = exec('echo $(grep -rn "app.' . $key . '" . --exclude-dir=vendor)');
    
        echo strlen($out) . " " . $key . "\n";
    
        if (strlen($out) <= 0) {
            $unused_keys[] = $key;
        }
    }
    
    // The $unused_keys array would contain the translation key that is not being used.