5da9c4a729b9d8fad77d7c2f239a1e10b354ec00
[shpub.git] / src / shpub / Config.php
1 <?php
2 namespace shpub;
3
4 class Config
5 {
6     public $hosts = [];
7
8     /**
9      * Currently selected host.
10      *
11      * @var Host
12      */
13     public $host;
14
15     protected function getConfigFilePath()
16     {
17         if (!isset($_SERVER['HOME'])) {
18             return false;
19         }
20
21         return $_SERVER['HOME'] . '/.config/shpub.ini';
22     }
23
24     public function load()
25     {
26         $cfgFile = $this->getConfigFilePath();
27         if ($cfgFile == false) {
28             return false;
29         }
30
31         if (!file_exists($cfgFile) || !is_readable($cfgFile)) {
32             return false;
33         }
34
35         $data = parse_ini_file($cfgFile, true);
36         foreach ($data as $key => $val) {
37             if (!is_array($val)) {
38                 continue;
39             }
40             $host = new Config_Host();
41             foreach ($val as $hostProp => $hostVal) {
42                 if (!property_exists($host, $hostProp)) {
43                     Log::err('Invalid config key "' . $hostProp . '"');
44                     exit(1);
45                 }
46                 $host->$hostProp = $hostVal;
47             }
48             $this->hosts[$key] = $host;
49         }
50     }
51
52     public function save()
53     {
54         $str = '';
55         foreach ($this->hosts as $hostName => $host) {
56             if ($str != '') {
57                 $str .= "\n";
58             }
59             $str .= '[' . $hostName . "]\n";
60             foreach ($host as $hostProp => $hostVal) {
61                 if ($hostProp == 'cache') {
62                     continue;
63                 }
64                 if ($hostVal == '') {
65                     continue;
66                 }
67                 $str .= $hostProp . '=' . $hostVal . "\n";
68             }
69         }
70         file_put_contents($this->getConfigFilePath(), $str);
71     }
72
73     public function getDefaultHost()
74     {
75         if (!count($this->hosts)) {
76             return null;
77         }
78         foreach ($this->hosts as $key => $host) {
79             if ($host->default) {
80                 return $host;
81             }
82         }
83         
84         reset($this->hosts);
85         return key($this->hosts);
86     }
87
88     public function getHostByName($keyOrServer)
89     {
90         if (!count($this->hosts)) {
91             return null;
92         }
93         foreach ($this->hosts as $key => $host) {
94             if ($key == $keyOrServer || $host->server == $keyOrServer) {
95                 return $key;
96             }
97         }
98         return null;
99     }
100 }
101 ?>