Passed
Push — master ( 1ce9aa...29cd64 )
by Shahrad
02:01
created

CrashPad::setAdminChatId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace TelegramBot;
5
6
/**
7
 * CrashPad class
8
 *
9
 * @link    https://github.com/telegram-bot-php/core
10
 * @author  Shahrad Elahi (https://github.com/shahradelahi)
11
 * @license https://github.com/telegram-bot-php/core/blob/master/LICENSE (MIT License)
12
 */
13
class CrashPad
14
{
15
16
    /**
17
     * Report the error to the developers from the Telegram Bot API.
18
     *
19
     * @param int $chat_id The chat id of the group to send the message to.
20
     * @param \Exception $exception The exception to report.
21
     * @param string|null $update (Optional) The update that caused the exception.
22
     * @retrun bool
23
     */
24
    public static function report(int $chat_id, \Exception $exception, string|null $update = null): bool
25
    {
26
        if ($chat_id === -1) {
27
            throw new \RuntimeException(sprintf(
28
                'The given `chat_id` is not valid. given: %s',
29
                $chat_id
30
            ));
31
        }
32
33
        TelegramLog::error(($message = sprintf(
34
            "%s(%d): %s\n%s",
35
            $exception->getFile(),
36
            $exception->getLine(),
37
            $exception->getMessage(),
38
            $exception->getTraceAsString()
39
        )));
40
41
        echo '<b>TelegramError:</b> ' . $message;
42
43
        $text = Request::sendMessage([
44
            'chat_id' => $chat_id,
45
            'text' => $message,
46
        ]);
47
48
        if ($update !== null) {
49
            $document = Request::sendDocument([
50
                'chat_id' => $chat_id,
51
                'document' => self::createCrashFile(
52
                    $message . "\n\n" . $update
53
                ),
54
            ]);
55
            return $text->isOk() && $document->isOk();
56
        }
57
58
        return $text->isOk();
59
    }
60
61
    /**
62
     * Create a log file for the error.
63
     *
64
     * @param string $content The content of the log file.
65
     * @retrun string The path of the log file.
66
     */
67
    private static function createCrashFile(string $content): string
68
    {
69
        $base_path = $_SERVER['DOCUMENT_ROOT'] . '.telegram-bot/';
70
        if (!file_exists($base_path)) {
71
            mkdir($base_path, 0777, true);
72
        }
73
74
        file_put_contents(($file = $base_path . uniqid('error_') . '.log'), $content);
75
        return $file;
76
    }
77
78
    /**
79
     * Clear crash files.
80
     *
81
     * @return void
82
     */
83
    public static function clearCrashFiles(): void
84
    {
85
        $files = glob(getcwd() . '.telegram-bot/*.log');
86
        foreach ($files as $file) {
87
            unlink($file);
88
        }
89
    }
90
91
    /**
92
     * Debug mode. Catch the crash reports.
93
     *
94
     * @param int $admin_id (optional) The admin chat id.
95
     * @return void
96
     */
97
    public static function setDebugMode(int $admin_id = -1): void
98
    {
99
        error_reporting(E_ALL);
100
        ini_set('display_errors', '1');
101
102
        defined('DEBUG_MODE') or define('DEBUG_MODE', true);
103
        if ($admin_id !== -1) {
104
            Telegram::setAdminChatId($admin_id);
105
        }
106
107
        set_exception_handler(function ($exception) {
108
            if (!defined('DEBUG_MODE') && !DEBUG_MODE) {
109
                throw $exception;
110
            } else {
111
                if (Telegram::getAdminChatId() !== -1) {
112
                    $input = getenv('TG_CURRENT_UPDATE') ?? Telegram::getInput();
113
                    $update = Telegram::processUpdate($input, Telegram::getApiToken());
0 ignored issues
show
Bug introduced by
It seems like $input can also be of type null; however, parameter $input of TelegramBot\Telegram::processUpdate() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

113
                    $update = Telegram::processUpdate(/** @scrutinizer ignore-type */ $input, Telegram::getApiToken());
Loading history...
Bug introduced by
It seems like TelegramBot\Telegram::getApiToken() can also be of type false; however, parameter $apiKey of TelegramBot\Telegram::processUpdate() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

113
                    $update = Telegram::processUpdate($input, /** @scrutinizer ignore-type */ Telegram::getApiToken());
Loading history...
114
                    CrashPad::report(Telegram::getAdminChatId(), $exception, json_encode($update));
115
                }
116
            }
117
        });
118
    }
119
120
}