forked from johnnoel/php-ass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ass.php
100 lines (77 loc) · 2.17 KB
/
Ass.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
/**
* @version 1.0
* @author John Noel <[email protected]>
* @package ASSREADER
*/
namespace chaostangent\Ass;
class Ass
{
protected $blocks = array();
protected $currentBlock = null;
public function __construct() { }
public static function fromFile($filename)
{
if (!file_exists($filename)) {
throw new \Exception('Unable to find file');
}
$ret = new self();
$fh = fopen($filename, 'r');
// check whether there's a UTF8 BOM
$a = unpack('h*', fread($fh, 3));
$utf8bom = reset($a);
if (strtolower($utf8bom) != 'febbfb') {
fseek($fh, 0);
}
while (feof($fh) !== true) {
$line = fgets($fh, 8192);
$ret->parseLine($line);
}
$ret->blocks[] = $ret->currentBlock;
return $ret;
}
public static function fromString($contents)
{
$ret = new self();
$lines = explode(PHP_EOL, $contents);
foreach ($lines as $line) {
$ret->parseLine($line);
}
$ret->blocks[] = $ret->currentBlock;
return $ret;
}
public function getBlocks() { return $this->blocks; }
public function getBlock($idx)
{
if (!array_key_exists($idx, $this->blocks)) {
throw new \Exception('Index '.$idx.' does not exists');
}
return $this->blocks[$idx];
}
public function findBlocks($name)
{
return array_filter($this->blocks, function($a) use ($name) {
return ($a->getName() == $name);
});
}
protected function parseLine($line)
{
// comment line, continue
if (substr($line, 0, 1) == ';') {
return;
}
// block
if (substr($line, 0, 1) == '[') {
if ($this->currentBlock !== null) {
$this->blocks[] = $this->currentBlock;
}
$blockName = substr(trim($line), 1, -1);
$this->currentBlock = new Block($blockName);
return;
}
if ($this->currentBlock === null) {
return;
}
$this->currentBlock->addLine($line);
}
}