1: <?php
2:
3: namespace Budabot\Core;
4:
5: 6: 7: 8:
9: class ConfigFile {
10:
11: private $filePath;
12: private $vars;
13:
14: 15: 16: 17: 18:
19: public function __construct($filePath) {
20: $this->filePath = $filePath;
21: $this->vars = array();
22: }
23:
24: 25: 26:
27: public function getFilePath() {
28: return $this->filePath;
29: }
30:
31: 32: 33:
34: public function load() {
35: $this->copyFromTemplateIfNeeded();
36: require $this->filePath;
37: $this->vars = $vars;
38: }
39:
40: 41: 42:
43: public function save() {
44: $vars = $this->vars;
45: $this->copyFromTemplateIfNeeded();
46: $lines = file($this->filePath);
47: forEach ($lines as $key => $line) {
48: if (preg_match("/^(.+)vars\[('|\")(.+)('|\")](.*)=(.*)\"(.*)\";(.*)$/si", $line, $arr)) {
49: $lines[$key] = "$arr[1]vars['$arr[3]']$arr[5]=$arr[6]\"{$vars[$arr[3]]}\";$arr[8]";
50: unset($vars[$arr[3]]);
51: } else if (preg_match("/^(.+)vars\[('|\")(.+)('|\")](.*)=([ ]+)([0-9]+);(.*)$/si", $line, $arr)) {
52: $lines[$key] = "$arr[1]vars['$arr[3]']$arr[5]=$arr[6]{$vars[$arr[3]]};$arr[8]";
53: unset($vars[$arr[3]]);
54: }
55: }
56:
57: unset($vars['module_load_paths']);
58:
59:
60:
61: if (!empty($vars)) {
62: $lines []= "<?php\n";
63: forEach ($vars as $name => $value) {
64: if (is_string($value)) {
65: $lines []= "\$vars['$name'] = \"$value\";\n";
66: } else {
67: $lines []= "\$vars['$name'] = $value;\n";
68: }
69: }
70: $lines []= "\n";
71: }
72:
73: file_put_contents($this->filePath, $lines);
74: }
75:
76: 77: 78:
79: public function getVars() {
80: return $this->vars;
81: }
82:
83: 84: 85: 86: 87:
88: public function getVar($name) {
89: if (isset($this->vars[$name])) {
90: return $this->vars[$name];
91: }
92: return null;
93: }
94:
95: 96: 97: 98: 99: 100:
101: public function insertVars($vars) {
102: $this->vars = array_merge($this->vars, $vars);
103: }
104:
105: 106: 107: 108: 109: 110:
111: public function setVar($name, $value) {
112: $this->vars[$name] = $value;
113: }
114:
115: 116: 117:
118: private function copyFromTemplateIfNeeded() {
119: $templatePath = __DIR__ . '/../conf/config.template.php';
120: if (!file_exists($this->filePath)) {
121: copy($templatePath, $this->filePath) or LegacyLogger::log('ERROR', 'StartUp', "could not create config file: {$this->filePath}");
122: }
123: }
124: }
125: