| 1 |
<?php |
| 2 |
|
| 3 |
require_once('lib/generator/common/AbstractSerializer.php'); |
| 4 |
|
| 5 |
abstract class Serializer extends AbstractSerializer |
| 6 |
{ |
| 7 |
private $file_location; |
| 8 |
|
| 9 |
private $length = 9999; |
| 10 |
|
| 11 |
private $data = array(); |
| 12 |
|
| 13 |
public static function clean($directory, $suffix, $filename='api') { |
| 14 |
$loc = $directory . '/' . $filename . '.' . $suffix; |
| 15 |
file_exists($loc) && unlink($loc); |
| 16 |
} |
| 17 |
|
| 18 |
public function __construct($directory, $suffix, $filename='api') { |
| 19 |
$this->file_location = $directory . '/' . $filename . '.' . $suffix; |
| 20 |
touch($this->file_location); |
| 21 |
$file = fopen($this->file_location, 'r'); |
| 22 |
$this->_readFromFile($file); |
| 23 |
fclose($file); |
| 24 |
} |
| 25 |
|
| 26 |
private function _readFromFile($file) { |
| 27 |
$id = null; |
| 28 |
while (!feof($file)) { |
| 29 |
$line = stream_get_line($file, $this->length, "\n"); |
| 30 |
if ($id) { |
| 31 |
$this->data[$id] .= $line . "\n"; |
| 32 |
if ($this->lineEnds($line)) { |
| 33 |
$id = null; |
| 34 |
} |
| 35 |
} |
| 36 |
elseif ($id = $this->lineStarts($line)) { |
| 37 |
$this->data[$id] = $line . "\n"; |
| 38 |
} |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
public function __destruct() { |
| 43 |
$tmp = fopen($this->file_location . '_tmp', 'w'); |
| 44 |
|
| 45 |
foreach ($this->header as $header_line) { |
| 46 |
fwrite($tmp, $header_line . "\n"); |
| 47 |
} |
| 48 |
foreach ($this->data as $id => $value) { |
| 49 |
fwrite($tmp, $value . "\n"); |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
foreach ($this->footer as $footer_line) { |
| 59 |
fwrite($tmp, $footer_line . "\n"); |
| 60 |
} |
| 61 |
|
| 62 |
fclose($tmp); |
| 63 |
|
| 64 |
unlink($this->file_location); |
| 65 |
|
| 66 |
rename($this->file_location . '_tmp', $this->file_location); |
| 67 |
} |
| 68 |
|
| 69 |
public function ids() { |
| 70 |
return array_keys($this->data); |
| 71 |
} |
| 72 |
|
| 73 |
protected function getString($id) { |
| 74 |
if(array_key_exists($id, $this->data)){ |
| 75 |
return $this->data[$id]; |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
public function set($id, $value) { |
| 80 |
if (!$id) { |
| 81 |
debug_print_backtrace(); |
| 82 |
die("Called set without an ID\n"); |
| 83 |
} |
| 84 |
|
| 85 |
$content = $this->toString($value, $id); |
| 86 |
|
| 87 |
$this->data[$id] = preg_replace('/^/m', $this->indent, $content); |
| 88 |
} |
| 89 |
} |