Completed
Push — v5-dev ( a42eb3 )
by Oscar
01:56
created

Loader::readFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Gettext\Loader;
5
6
use Gettext\Translations;
7
use Gettext\Translation;
8
use Exception;
9
10
/**
11
 * Base class with common funtions 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 new Translations();
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
        $length = filesize($file);
49
50
        if (!($fd = fopen($file, 'rb'))) {
51
            throw new Exception("Cannot read the file '$file', probably permissions");
52
        }
53
54
        $content = $length ? fread($fd, $length) : '';
55
        fclose($fd);
56
57
        return $content;
58
    }
59
}
60