Passed
Push — develop ( 2d3c3b...ea7628 )
by Nikolay
04:49
created

SystemMessages::echoWithSyslog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright © 2017-2024 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace MikoPBX\Core\System;
21
22
use MikoPBX\Common\Providers\LoggerProvider;
23
use Phalcon\Di;
24
25
/**
26
 * SystemMessages class
27
 *
28
 * @package MikoPBX\Core\System
29
 *
30
 */
31
class SystemMessages extends Di\Injectable
32
{
33
    public const RESULT_DONE = 'Done';
34
    public const RESULT_FAILED = 'Failed';
35
    public const RESULT_SKIPPED = 'Skipped';
36
37
    private static array $defaultTexts = [
38
        self::RESULT_DONE => " \033[32;1mDONE\033[0m \n", // Green for DONE
39
        self::RESULT_FAILED => " \033[31;1mFAIL\033[0m \n",  // Red for FAILED
40
        self::RESULT_SKIPPED => " \033[33;1mSKIP\033[0m \n", // Yellow for SKIPPED
41
    ];
42
43
    /**
44
     * Echoes a result message with progress dots.
45
     *
46
     * @param string $message The result message to echo.
47
     * @param string $result The result status (DONE by default).
48
     *
49
     * @return void
50
     */
51
    public static function teletypeEchoResult(string $message, string $result = self::RESULT_DONE): void
52
    {
53
        $len = max(0, 80 - strlen($message) - 9);
54
        $spaces = str_repeat('.', $len);
55
        $formattedResult = self::getFormattedResult($result);
56
        self::echoToTeletype($spaces.$formattedResult);
57
    }
58
59
    /**
60
     * Echoes a message and logs it to the ttyS0-ttyS5.
61
     *
62
     * @param string $message The message to echo in a serial console.
63
     *
64
     * @return void
65
     */
66
    public static function echoToTeletype(string $message): void
67
    {
68
        // Log to serial tty
69
        echo $message;
70
        for ($i = 0; $i <= 5; $i++) {
71
            $device = "/dev/ttyS$i";
72
            $busyboxPath = Util::which('busybox');
73
            // Get the result of the command execution
74
            $result = shell_exec("$busyboxPath setserial -g \"$device\" | $busyboxPath grep -v unknown 2> /dev/null");
75
            // If the result is not empty
76
            if (!empty($result)) {
77
                // Perform the same
78
                file_put_contents($device, $message, FILE_APPEND);
79
            }
80
        }
81
    }
82
83
    /**
84
     * Prepares formatted result string.
85
     *
86
     * @param string $result The result status.
87
     *
88
     * @return string Formatted result status.
89
     */
90
    private static function getFormattedResult(string $result = self::RESULT_DONE): string
91
    {
92
        if ($result === '1') {
93
            $result = self::RESULT_DONE;
94
        } elseif ($result === '0') {
95
            $result = self::RESULT_FAILED;
96
        }
97
        if (array_key_exists($result, self::$defaultTexts)) {
98
            $resultMessage = self::$defaultTexts[$result];
99
        } else {
100
            $resultMessage = "\033[90m$result\033[0m \n"; // Grey for unknown results
101
        }
102
        return $resultMessage;
103
    }
104
105
    /**
106
     * Echoes a result message with progress dots.
107
     *
108
     * @param string $message The result message to echo.
109
     * @param string $result The result status (DONE by default).
110
     *
111
     * @return void
112
     */
113
    public static function echoResult(string $message, string $result = self::RESULT_DONE): void
114
    {
115
        $cols = self::getCountCols();
116
        if (!is_numeric($cols)) {
117
            // Failed to retrieve the screen width.
118
            return;
119
        }
120
        $len = $cols - strlen($message) - 8;
121
        if ($len < 2) {
122
            // Incorrect screen width.
123
            return;
124
        }
125
126
        $spaces = str_repeat('.', $len);
127
        $formattedResult = self::getFormattedResult($result);
128
        echo "\r" . $message . $spaces. $formattedResult;
129
    }
130
131
    /**
132
     * Gets the count of columns in the terminal window.
133
     *
134
     * @return string The count of columns.
135
     */
136
    public static function getCountCols(): string
137
    {
138
        $len = 1 * trim(shell_exec('tput cols'));
139
140
        // If the count of columns is zero, set it to a default value of 80
141
        if ($len === 0) {
142
            $len = 80;
143
        } else {
144
            // Limit the count of columns to a maximum of 80
145
            $len = min($len, 80);
146
        }
147
        return $len;
148
    }
149
150
    /**
151
     * Echoes a message and logs it to the system log.
152
     *
153
     * @param string $message The message to echo and log.
154
     *
155
     * @return void
156
     */
157
    public static function echoWithSyslog(string $message): void
158
    {
159
        echo $message;
160
        // Log the message to the system log with LOG_INFO level
161
        self::sysLogMsg(static::class, $message, LOG_INFO);
162
    }
163
164
    /**
165
     * Adds messages to Syslog.
166
     *
167
     * @param string $ident The category, class, or method identification.
168
     * @param string $message The log message.
169
     * @param int $level The log level (default: LOG_WARNING).
170
     *
171
     * @return void
172
     */
173
    public static function sysLogMsg(string $ident, string $message, int $level = LOG_WARNING): void
174
    {
175
        /** @var \Phalcon\Logger $logger */
176
        $logger = Di::getDefault()->getShared(LoggerProvider::SERVICE_NAME);
177
        $logger->log($level, "{$message} on {$ident}");
178
    }
179
180
}