| 1 |
<?php |
| 2 |
declare(strict_types = 1); |
| 3 |
|
| 4 |
namespace Gettext\Loader; |
| 5 |
|
| 6 |
use Exception; |
| 7 |
use Gettext\Translation; |
| 8 |
use Gettext\Translations; |
| 9 |
|
| 10 |
/** |
| 11 |
* Base class with common functions for all loaders. |
| 12 |
*/ |
| 13 |
abstract class Loader implements LoaderInterface |
| 14 |
{ |
| 15 |
public function loadFile(string $filename, ?Translations $translations = null): Translations |
| 16 |
{ |
| 17 |
$string = static::readFile($filename); |
| 18 |
|
| 19 |
return $this->loadString($string, $translations); |
| 20 |
} |
| 21 |
|
| 22 |
public function loadString(string $string, ?Translations $translations = null): Translations |
| 23 |
{ |
| 24 |
return $translations ?: $this->createTranslations(); |
| 25 |
} |
| 26 |
|
| 27 |
protected function createTranslations(): Translations |
| 28 |
{ |
| 29 |
return Translations::create(); |
| 30 |
} |
| 31 |
|
| 32 |
protected function createTranslation(?string $context, string $original, ?string $plural = null): ?Translation |
| 33 |
{ |
| 34 |
$translation = Translation::create($context, $original); |
| 35 |
|
| 36 |
if (isset($plural)) { |
| 37 |
$translation->setPlural($plural); |
| 38 |
} |
| 39 |
|
| 40 |
return $translation; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Reads and returns the content of a file. |
| 45 |
*/ |
| 46 |
protected static function readFile(string $file): string |
| 47 |
{ |
| 48 |
$content = @file_get_contents($file); |
| 49 |
|
| 50 |
if (false === $content) { |
| 51 |
throw new Exception("Cannot read the file '$file', probably permissions"); |
| 52 |
} |
| 53 |
|
| 54 |
return $content; |
| 55 |
} |
| 56 |
} |
| 57 |
|