From 11d1d344593e0374b35139b3d6f903cc9ea2eb6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=A3=E8=A8=80=E5=B0=B1=E6=98=AFSiam?= <59419979@qq.com> Date: Thu, 30 Dec 2021 11:59:12 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E6=96=B0=E5=A2=9Ehosts=20manage?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/siam/HostsManage.php | 127 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 src/siam/HostsManage.php diff --git a/src/siam/HostsManage.php b/src/siam/HostsManage.php new file mode 100644 index 0000000..8fc2d18 --- /dev/null +++ b/src/siam/HostsManage.php @@ -0,0 +1,127 @@ +file = $file; + if ($config_file) { + $this->configFile = $config_file; + } else { + $this->configFile = __FILE__ . '.ini'; + } + $this->initHosts() + ->initCfg(); + } + public function __destruct() { + $this->write(); + } + public function initHosts() { + $lines = file($this->file); + foreach ($lines as $line) { + $line = trim($line); + if (empty($line) || $line[0] == '#') { + continue; + } + $item = preg_split('/\s+/', $line); + $this->hosts[$item[1]] = $item[0]; + } + return $this; + } + public function initCfg() { + if (! file_exists($this->configFile)) { + $this->config = array(); + } else { + $this->config = (parse_ini_file($this->configFile, true)); + } + $this->domain = array_keys($this->config['domain'] ?? []); + $this->ip = $this->config['ip']?? ""; + return $this; + } + /** + * 删除配置文件里域的 hosts + */ + public function delAllGroup() { + foreach ($this->domain as $domain) { + $this->delRecord($domain); + } + } + /** + * 将域配置为指定 ip + * @param string $env + * @return static + */ + public function addGroup($env) { + if (! isset($this->ip[$env])) { + return $this; + } + foreach ($this->domain as $domain) { + $this->addRecord($domain, $this->ip[$env]); + } + return $this; + } + + /** + * 添加一条 host 记录 + * @param string $domain + * @param string $ip + * @return HostsManage + */ + function addRecord($domain, $ip) { + $this->hosts[$domain] = $ip; + return $this; + } + + /** + * 删除一条 host 记录 + * @param string $domain + * @return HostsManage + */ + function delRecord($domain) { + unset($this->hosts[$domain]); + return $this; + } + /** + * 写入 host 文件 + */ + public function write() { + $str = ''; + foreach ($this->hosts as $domain => $ip) { + $str .= $ip . "\t" . $domain . PHP_EOL; + } + file_put_contents($this->file, $str); + return $this; + } + + /** + * @return array + */ + public function getHosts(): array + { + return $this->hosts; + } + + /** + * @param array $hosts + */ + public function setHosts(array $hosts) + { + $this->hosts = $hosts; + } + + + +}