Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Translation Tool Bundle Laravel Package

afe/translation-tool-bundle

Symfony bundle providing CLI tools to audit translation keys: detect duplicated translation codes and find unused keys by scanning Twig/HTML/PHP/JS sources and YAML translation files. Configurable include/exclude paths, locales, and file masks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require afe/translation-tool-bundle:dev-master
    

    Register the bundle in AppKernel.php:

    new Afe\TranslationToolBundle\AfeTranslationToolBundle(),
    
  2. Configure: Add minimal config in config/packages/afe_translation_tool.yaml (or config.yml):

    afe_translation_tool:
        translation_files_dir_path: "%kernel.root_dir%/../translations"
        translation_files_locale: "en"
        src_dir_path: "%kernel.root_dir%/../src"
    
  3. First Use Case: Run the duplicate check command:

    php bin/console afe:translation:check:codes
    

    This will scan your translation files for duplicate keys and display results.


Implementation Patterns

Workflows

  1. Translation Maintenance Workflow:

    • Pre-merge: Run afe:translation:check:codes and afe:translation:check:unused before merging PRs to catch issues early.
    • Post-update: After updating translations, run the commands to identify unused keys for cleanup.
  2. Integration with CI: Add commands to your CI pipeline (e.g., GitHub Actions) to fail builds if duplicates/unused keys exceed thresholds:

    - name: Check translations
      run: |
        php bin/console afe:translation:check:codes --format=json | jq '.duplicates | length' -r > duplicates_count.txt
        if [ $(cat duplicates_count.txt) -gt 0 ]; then exit 1; fi
    
  3. Local Development:

    • Use the --format=json flag for programmatic access:
      php bin/console afe:translation:check:unused --format=json > unused_keys.json
      
    • Parse results in PHP to automate fixes (e.g., remove unused keys via script).

Integration Tips

  • Symfony Flex: If using Symfony Flex, place config in config/packages/afe_translation_tool.yaml.
  • Custom Directories: Override translation_files_dir_path to target non-standard paths (e.g., ../custom/translations).
  • Multi-Locale: Run checks per locale by updating translation_files_locale in config or via environment variables.
  • Exclusions: Use excluded_translation_file_mask to ignore legacy or auto-generated files (e.g., ["messages.*.yml"]).

Gotchas and Tips

Pitfalls

  1. Performance:

    • Large projects may slow down due to file scanning. Exclude directories like vendor and node_modules to improve speed.
    • Fix: Add to config:
      excluded_directories: ["vendor", "node_modules", "var/cache"]
      
  2. False Positives:

    • Dynamic translation keys (e.g., {{ key }} in Twig) may trigger "unused" warnings.
    • Fix: Exclude files with dynamic content:
      excluded_file_mask: ["*.twig", "*.js"]
      
  3. YAML-Only Support:

    • Only .yml files are processed. JSON/other formats require manual checks.
    • Workaround: Convert files to YAML or use excluded_translation_file_mask to skip unsupported formats.
  4. Case Sensitivity:

    • Duplicate checks are case-sensitive. home.welcome and HOME.WELCOME are treated as distinct.
    • Tip: Standardize key casing (e.g., snake_case) in your team’s style guide.
  5. Command Output:

    • Console output lacks color/formatting. Pipe to grep/jq for better readability:
      php bin/console afe:translation:check:unused | grep -E "unused|warning"
      

Debugging

  • Verbose Mode: Use --verbose to debug file paths:
    php bin/console afe:translation:check:codes --verbose
    
  • Dry Run: Test config changes without modifying files by redirecting output to a file:
    php bin/console afe:translation:check:unused > unused_report.txt
    

Extension Points

  1. Custom Validators: Extend the bundle by creating a custom command to validate keys against a schema (e.g., regex patterns):

    // src/Command/ValidateTranslationKeysCommand.php
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class ValidateTranslationKeysCommand extends Command {
        protected function execute(InputInterface $input, OutputInterface $output) {
            $keys = $this->getTranslationKeys(); // Implement logic to fetch keys
            foreach ($keys as $key) {
                if (!preg_match('/^[a-z_]+\.[a-z_]+$/', $key)) {
                    $output->writeln("<error>Invalid key: $key</error>");
                }
            }
        }
    }
    
  2. Post-Processing: Automate fixes by parsing JSON output and updating files:

    $unusedKeys = json_decode(file_get_contents('unused_keys.json'), true);
    foreach ($unusedKeys['unused'] as $file => $keys) {
        $translationFile = sprintf('%s/translations/%s/%s.yml', $rootDir, $locale, $file);
        $translations = yaml_parse(file_get_contents($translationFile));
        foreach ($keys as $key) {
            unset($translations[$key]);
        }
        file_put_contents($translationFile, yaml_emit($translations));
    }
    
  3. Event Listeners: Trigger checks on file changes (e.g., via FileSystemEvents):

    // src/EventListener/TranslationListener.php
    use Symfony\Component\Filesystem\Filesystem;
    use Symfony\Component\HttpKernel\Event\KernelEvent;
    
    class TranslationListener {
        public function onKernelRequest(KernelEvent $event) {
            if ($event->isMainRequest()) {
                $fs = new Filesystem();
                if ($fs->exists('translations/fr/messages.yml')) {
                    $this->runTranslationChecks();
                }
            }
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor