Skip to content

Commit a2ecc7f

Browse files
committed
new tests, bug fixes, errors handling
1 parent 461c4dd commit a2ecc7f

File tree

2 files changed

+54
-11
lines changed

2 files changed

+54
-11
lines changed

src/LocalizationHelper.php

+12-11
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ public function trans($key, $default = null, $placeholders = [])
4343

4444
$filename = $path[0];
4545

46+
if (! isset($path[1])) return __($key, $placeholders);
47+
4648
$this->translator->addLines([$key => $default], $fallbackLocale);
4749

4850
$this->writeToLangFile(
@@ -87,18 +89,17 @@ private function writeToLangFile($locale, $translations, $filename)
8789

8890
$language_file = $this->basePath . "/{$locale}/{$filename}.php";
8991

90-
if (($fp = fopen($language_file, 'w')) !== FALSE) {
91-
92-
fputs($fp, $header . $this->var_export54($translations) . ";\n");
92+
try {
93+
if (($fp = fopen($language_file, 'w')) !== FALSE) {
9394

94-
fclose($fp);
95-
96-
return true;
97-
98-
} else {
99-
return false;
100-
}
101-
}
95+
fputs($fp, $header . $this->var_export54($translations) . ";\n");
96+
97+
fclose($fp);
98+
99+
return true;
100+
}
101+
} catch (\Exception $e) {
102+
return false;}}
102103

103104
/**
104105
* var_export to php5.4 array syntax

tests/UsageTest.php

+42
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,48 @@ public function testReturnsKeyIfNotAbleToAddNewStringBecauseIsArray()
203203

204204
$this->assertEquals(_p($key, uniqid()), $key);
205205
}
206+
207+
public function testThrowsErrorIfLocalizationFileCantBeOpened()
208+
{
209+
$key = ($filename = uniqid()) . '.' . uniqid();
210+
211+
vfsStream::newFile($filename . '.php', 0000)
212+
->withContent($content = 'notoverwritten')
213+
->at($this->root->getChild('root/resources/lang/en'));
214+
215+
$value = uniqid();
216+
217+
_p($key, $value);
218+
219+
$this->assertEquals($content, $this->root->getChild('root/resources/lang/en/'. $filename . '.php')->getContent());
220+
}
221+
222+
public function testExportsFileIfContentsBoolean()
223+
{
224+
$key = ($filename = uniqid()) . '.' . uniqid();
225+
226+
$value = true;
227+
228+
_p($key, $value);
229+
230+
$this->assertStringStartsWith('<?php', $this->root->getChild('root/resources/lang/en/'. $filename . '.php')->getContent());
231+
}
232+
233+
public function testExportsFileIfContentsObject()
234+
{
235+
$key = ($filename = uniqid()) . '.' . uniqid();
236+
237+
$value = new \stdClass;
238+
239+
_p($key, $value);
240+
241+
$this->assertStringStartsWith('<?php', $this->root->getChild('root/resources/lang/en/'. $filename . '.php')->getContent());
242+
}
243+
244+
public function testHandlesCallsWithRootNameOnly()
245+
{
246+
$this->assertEquals('name', _p('name', 'test'));
247+
}
206248

207249
protected function getContents($filename)
208250
{

0 commit comments

Comments
 (0)