Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Lib;
- use App\Application;
- class ServerManager
- {
- protected $app = null;
- public function __construct(Application $app)
- {
- $this->app = $app;
- if (empty($this->app['config']['path'])) {
- throw new \Exception('Invalid or empty server path!');
- }
- if (empty($this->app['config']['file'])) {
- throw new \Exception('Invalid or empty server file!');
- }
- }
- public function getStartCommand()
- {
- if (isset($this->app['config']['commands']) && isset($this->app['config']['commands']['start'])) {
- return $this->parse($this->app['config']['commands']['start']);
- }
- return $this->parse('cd %path% && screen -dmS %prefix%%file% ./%file%');
- }
- public function start()
- {
- if ($this->isRunning()) {
- throw new \RuntimeException('Server is already running, can\'t start twice.');
- }
- $cmd = $this->getStartCommand();
- $this->app['system']->execute($cmd);
- $this->app['monolog']->addInfo('Server was started (' . $cmd . ')');
- }
- public function getStopCommand()
- {
- if (isset($this->app['config']['commands']) && isset($this->app['config']['commands']['stop'])) {
- return $this->parse($this->app['config']['commands']['stop']);
- }
- return $this->parse('screen -S %prefix%%file% -p 0 -X quit');
- }
- public function stop()
- {
- $cmd = $this->getStopCommand();
- $this->app['system']->execute($cmd);
- $this->app['monolog']->addInfo('Server was stopped (' . $cmd . ')');
- }
- public function restart()
- {
- if ($this->isRunning()) {
- $this->stop();
- sleep(1);
- }
- $this->start();
- $this->app['monolog']->addInfo('Server was restarted');
- }
- public function getIsRunningCommand()
- {
- if (isset($this->app['config']['commands']) && isset($this->app['config']['commands']['is_running'])) {
- return $this->parse($this->app['config']['commands']['is_running']);
- }
- return $this->parse('screen -ls | grep -c %prefix%%file%');
- }
- public function isRunning()
- {
- $cmd = $this->getIsRunningCommand();
- return (int) $this->app['system']->execute($cmd);
- }
- protected function parse($content)
- {
- return str_replace(array('%path%', '%file%', '%prefix%'),
- array(
- $this->app['config']['path'],
- $this->app['config']['file'],
- isset($this->app['config']['prefix']) ? $this->app['config']['prefix'] : ''
- ),
- $content);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement