Issues (36)

utils/importFromLog.php (2 issues)

Labels
Severity
1
<?php
2
3
/**
4
 * Import all updates from a raw updates log file into the database.
5
 * Works for both webhook and getUpdates.
6
 *
7
 * Modify $updates_log_file_path and $mysql_credentials below!
8
 *
9
 * Requires PHP7+
10
 *
11
 * @todo Move to dedicated CLI tool.
12
 */
13
14
use Longman\TelegramBot\DB;
15
use Longman\TelegramBot\Entities\Update;
16
use Longman\TelegramBot\Telegram;
17
18
require __DIR__ . '/../vendor/autoload.php';
19
20
// This is the file that contains the raw updates.
21
$updates_log_file_path = __DIR__ . '/updates.log';
22
23
// Credentials of the database to import updates to.
24
$mysql_credentials = [
25
    'host'     => 'localhost',
26
    'port'     => 3306, // optional
27
    'user'     => 'dbuser',
28
    'password' => 'dbpass',
29
    'database' => 'dbname',
30
];
31
32
try {
33
    // Create dummy Telegram API object and connect to MySQL database.
34
    (new Telegram('1:A'))->enableMySql($mysql_credentials);
35
36
    // Load the updates log file to iterate over.
37
    $updates_log_file = new SplFileObject($updates_log_file_path);
38
    $updates_log_file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
39
40
    foreach ($updates_log_file as $update_json) {
41
        if ($update_arr = json_decode($update_json, true)) {
0 ignored issues
show
It seems like $update_json can also be of type array; however, parameter $json of json_decode() 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

41
        if ($update_arr = json_decode(/** @scrutinizer ignore-type */ $update_json, true)) {
Loading history...
42
            echo $update_json . PHP_EOL;
0 ignored issues
show
Are you sure $update_json of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

42
            echo /** @scrutinizer ignore-type */ $update_json . PHP_EOL;
Loading history...
43
44
            // Get all updates on this line.
45
            $updates_data = array_filter($update_arr['result'] ?? [$update_arr]);
46
            foreach ($updates_data as $update_data) {
47
                $update = new Update($update_data);
48
                printf(
49
                    'Update ID %d %s' . PHP_EOL,
50
                    $update->getUpdateId(),
51
                    DB::insertRequest($update) ? '(success)' : '(failed) ' . implode(' ', DB::getPdo()->errorInfo())
52
                );
53
            }
54
        }
55
    }
56
} catch (Throwable $e) {
57
    // Output any errors.
58
    echo $e;
59
}
60