1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gettext\Extractors; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use InvalidArgumentException; |
7
|
|
|
use Gettext\Translations; |
8
|
|
|
|
9
|
|
|
abstract class Extractor implements ExtractorInterface |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* {@inheritdoc} |
13
|
|
|
*/ |
14
|
|
|
public static function fromFile($file, Translations $translations, array $options = []) |
15
|
|
|
{ |
16
|
|
|
foreach (self::getFiles($file) as $file) { |
17
|
|
|
$options['file'] = $file; |
18
|
|
|
static::fromString(self::readFile($file), $translations, $options); |
19
|
|
|
} |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Checks and returns all files. |
24
|
|
|
* |
25
|
|
|
* @param string|array $file The file/s |
26
|
|
|
* |
27
|
|
|
* @return array The file paths |
28
|
|
|
*/ |
29
|
|
|
protected static function getFiles($file) |
30
|
|
|
{ |
31
|
|
|
if (empty($file)) { |
32
|
|
|
throw new InvalidArgumentException('There is not any file defined'); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if (is_string($file)) { |
36
|
|
|
if (!is_file($file)) { |
37
|
|
|
throw new InvalidArgumentException("'$file' is not a valid file"); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if (!is_readable($file)) { |
41
|
|
|
throw new InvalidArgumentException("'$file' is not a readable file"); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return [$file]; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
if (is_array($file)) { |
48
|
|
|
$files = []; |
49
|
|
|
|
50
|
|
|
foreach ($file as $f) { |
51
|
|
|
$files = array_merge($files, self::getFiles($f)); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $files; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
throw new InvalidArgumentException('The first argumet must be string or array'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Reads and returns the content of a file. |
62
|
|
|
* |
63
|
|
|
* @param string $file |
64
|
|
|
* |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
|
|
protected static function readFile($file) |
68
|
|
|
{ |
69
|
|
|
$length = filesize($file); |
70
|
|
|
|
71
|
|
|
if (!($fd = fopen($file, 'rb'))) { |
72
|
|
|
throw new Exception("Cannot read the file '$file', probably permissions"); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$content = $length ? fread($fd, $length) : ''; |
76
|
|
|
fclose($fd); |
77
|
|
|
|
78
|
|
|
return $content; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|