File tree Expand file tree Collapse file tree 2 files changed +46
-2
lines changed Expand file tree Collapse file tree 2 files changed +46
-2
lines changed Original file line number Diff line number Diff line change 1616/**
1717 * Replacement for PHP's native {@link \Locale} class.
1818 *
19- * The only method supported in this class is {@link getDefault}. This method
20- * will always return "en". All other methods will throw an exception when used.
19+ * The only methods supported in this class are ` getDefault` and `canonicalize`.
20+ * All other methods will throw an exception when used.
2121 *
2222 * @author Eriksen Costa <eriksen.costa@infranology.com.br>
2323 * @author Bernhard Schussek <bschussek@gmail.com>
@@ -57,6 +57,39 @@ public static function acceptFromHttp($header)
5757 throw new MethodNotImplementedException (__METHOD__ );
5858 }
5959
60+ /**
61+ * Returns a canonicalized locale string.
62+ *
63+ * This polyfill doesn't implement the full-spec algorithm. It only
64+ * canonicalizes locale strings handled by the `LocaleBundle` class.
65+ *
66+ * @param string $locale
67+ *
68+ * @return string
69+ */
70+ public static function canonicalize ($ locale )
71+ {
72+ $ locale = (string ) $ locale ;
73+
74+ if ('' === $ locale || '. ' === $ locale [0 ]) {
75+ return self ::getDefault ();
76+ }
77+
78+ if (!preg_match ('/^([a-z]{2})[-_]([a-z]{2})(?:([a-z]{2})(?:[-_]([a-z]{2}))?)?(?:\..*)?$/i ' , $ locale , $ m )) {
79+ return $ locale ;
80+ }
81+
82+ if (!empty ($ m [4 ])) {
83+ return strtolower ($ m [1 ]).'_ ' .ucfirst (strtolower ($ m [2 ].$ m [3 ])).'_ ' .strtoupper ($ m [4 ]);
84+ }
85+
86+ if (!empty ($ m [3 ])) {
87+ return strtolower ($ m [1 ]).'_ ' .ucfirst (strtolower ($ m [2 ].$ m [3 ]));
88+ }
89+
90+ return strtolower ($ m [1 ]).'_ ' .strtoupper ($ m [2 ]);
91+ }
92+
6093 /**
6194 * Not supported. Returns a correctly ordered and delimited locale code.
6295 *
Original file line number Diff line number Diff line change @@ -21,6 +21,17 @@ public function testAcceptFromHttp()
2121 $ this ->call ('acceptFromHttp ' , 'pt-br,en-us;q=0.7,en;q=0.5 ' );
2222 }
2323
24+ public function testCanonicalize ()
25+ {
26+ $ this ->assertSame ('en ' , $ this ->call ('canonicalize ' , '' ));
27+ $ this ->assertSame ('en ' , $ this ->call ('canonicalize ' , '.utf8 ' ));
28+ $ this ->assertSame ('fr_FR ' , $ this ->call ('canonicalize ' , 'FR-fr ' ));
29+ $ this ->assertSame ('fr_FR ' , $ this ->call ('canonicalize ' , 'FR-fr.utf8 ' ));
30+ $ this ->assertSame ('uz_Latn ' , $ this ->call ('canonicalize ' , 'UZ-lATN ' ));
31+ $ this ->assertSame ('uz_Cyrl_UZ ' , $ this ->call ('canonicalize ' , 'UZ-cYRL-uz ' ));
32+ $ this ->assertSame ('123 ' , $ this ->call ('canonicalize ' , 123 ));
33+ }
34+
2435 /**
2536 * @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException
2637 */
You can’t perform that action at this time.
0 commit comments