§ Для кода
Стартовый код для полезных функции.
1function config($name, $default = null) { return app::config($name, $default); }
2
3class app {
4
5 static $log_prefix;
6 static $need_stop = 0;
7 static $config = [];
8 static $argv = [];
9
10 static function init($argv) {
11
12 self::$argv = $argv;
13 self::reconfig();
14
15
16 spl_autoload_register([self::class, "lazy"]);
17 }
18
19 static function lazy($class)
20 {
21 $name = basename(str_replace('\\', '/', $class));
22 $dirs = [
23
24 ];
25
26 foreach ($dirs as $fn) {
27 if (file_exists($fn)) {
28 include $fn;
29 return;
30 }
31 }
32 }
33
34
35 static function reconfig() {
36
37 clearstatcache(true);
38
39 $files = [
40 __DIR__ . '/config.ini',
41 __DIR__ . '/config.dev.ini',
42 ];
43
44
45 foreach ($files as $file)
46 if (file_exists($file))
47 foreach (parse_ini_file($file, true) as $n => $u)
48 foreach ($u as $a => $b)
49 self::$config[$n][$a] = $b;
50
51 self::$config['database'] = ['connections' => self::$config['database'] ?? []];
52 }
53
54
55 static function config($cname, $default = null) {
56
57 $config = self::$config;
58 foreach (explode('.', $cname) as $item) {
59 if (isset($config[$item])) $config = $config[$item];
60 else return $default;
61 }
62 return $config;
63 }
64
65 static function log($msg) { echo self::$log_prefix . '['.date('Y-m-d H:i:s')."] $msg\n"; }
66 static function success($msg) { self::log("\e[1;32m$msg\e[0m"); }
67 static function error($msg) { self::log("\e[1;31m$msg\e[0m"); }
68 static function warn($msg) { self::log("\e[33m$msg\e[0m"); }
69 static function info($msg) { self::log("\e[36m$msg\e[0m"); }
70
71
72 static function argv($name, $def = null) {
73
74 if (is_integer($name)) {
75 return self::$argv[$name + 2] ?? $def;
76 } else if (strlen($name) == 1) {
77 return getopt($name);
78 } else {
79 foreach (self::$argv as $v)
80 if (preg_match("~^--$name=(.+)$~", $v, $c))
81 return $c[1];
82
83 return $def;
84 }
85 }
86
87
88 static function ps($filter = '') {
89
90 $r = [];
91 $ps = array_map(function ($e) { return preg_split('~\s+~', $e, 11); }, explode("\n", trim(`ps aux`)));
92 $ps = array_filter($ps, function($e) { return !preg_match('~^(\[|/bin/sh|COMMAND|/sbin/|/lib/|php-fpm)~', $e[10]); });
93 foreach ($ps as $x) if ($filter === '' || preg_match('~'.$filter.'~', $x[10] ?? "")) $r[$x[1]] = $x[10];
94 return $r;
95 }
96
97
98 static function registerSIG() {
99
100 pcntl_signal(SIGTERM, [app::class, "stopAll"]);
101 pcntl_signal(SIGINT, [app::class, "stopAll"]);
102 }
103
104
105 static function stopAll(int $signal) {
106 self::$need_stop = 1;
107 }
108
109
110 static function stop($stopfile = false) {
111
112 if (file_exists($stopfile)) {
113 return 1;
114 } else {
115 pcntl_signal_dispatch();
116 return self::$need_stop;
117 }
118 }
119}
120
121app::init($argv);