From f695cedebdf4a3ee9e697f2f3d82c8803323266e Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 9 Jan 2019 13:53:29 +0100 Subject: [PATCH] Improve language handling when creating JSON files --- features/makejson.feature | 39 ++++++++++++++++++++++++++++++++++++++- src/MakeJsonCommand.php | 9 ++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/features/makejson.feature b/features/makejson.feature index 38f921cd..6345f7e1 100644 --- a/features/makejson.feature +++ b/features/makejson.feature @@ -514,7 +514,7 @@ Feature: Split PO files into JSON files. "messages": { "": { "domain": "messages", - "lang": "de_DE", + "lang": "de-DE", "plural-forms": "nplurals=2; plural=(n != 1);" }, "Foo Plugin": [ @@ -523,3 +523,40 @@ Feature: Split PO files into JSON files. } } """ + + Scenario: Should fall back to English for invalid locales. + Given an empty foo-plugin directory + And a foo-plugin/foo-plugin-invalid.po file: + """ + # Copyright (C) 2018 Foo Plugin + # This file is distributed under the same license as the Foo Plugin package. + msgid "" + msgstr "" + "Project-Id-Version: Foo Plugin\n" + "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/foo-plugin\n" + "Last-Translator: FULL NAME \n" + "Language-Team: LANGUAGE \n" + "Language: invalid\n" + "MIME-Version: 1.0\n" + "Content-Type: text/plain; charset=UTF-8\n" + "Content-Transfer-Encoding: 8bit\n" + "POT-Creation-Date: 2018-05-02T22:06:24+00:00\n" + "PO-Revision-Date: 2018-05-02T22:06:24+00:00\n" + "X-Domain: foo-plugin\n" + "Plural-Forms: nplurals=2; plural=(n != 1);\n" + + #: foo-plugin.js:15 + msgid "Foo Plugin" + msgstr "Foo Plugin" + """ + + When I run `wp i18n make-json foo-plugin` + Then STDOUT should contain: + """ + Success: Created 1 file. + """ + And the return code should be 0 + And the foo-plugin/foo-plugin-invalid-56746e49c6485323d16a717754b7447e.json file should contain: + """ + "lang":"en" + """ diff --git a/src/MakeJsonCommand.php b/src/MakeJsonCommand.php index 4843dcba..d8c8e9bd 100644 --- a/src/MakeJsonCommand.php +++ b/src/MakeJsonCommand.php @@ -155,7 +155,14 @@ function ( $reference ) { $mapping[ $source ] = new Translations(); // See https://core.trac.wordpress.org/ticket/45441 //$mapping[ $source ]->setDomain( $translations->getDomain() ); - $mapping[ $source ]->setLanguage( $translations->getLanguage() ); + + try { + $mapping[ $source ]->setLanguage( str_replace( '_', '-', $translations->getLanguage() ) ); + } catch ( \InvalidArgumentException $e ) { + // The locale had an invalid format. + $mapping[ $source ]->setLanguage( 'en' ); + } + $mapping[ $source ]->setHeader( 'PO-Revision-Date', $translations->getHeader( 'PO-Revision-Date' ) ); $plural_forms = $translations->getPluralForms();