User::addUser()   B
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.8571
c 0
b 0
f 0
ccs 0
cts 13
cp 0
cc 3
eloc 14
nc 3
nop 1
crap 12
1
<?php
2
3
/*
4
 * This file is part of the PhpBotFramework.
5
 *
6
 * PhpBotFramework is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, version 3.
9
 *
10
 * PhpBotFramework is distributed in the hope that it will be useful, but
11
 * WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace PhpBotFramework\Database;
20
21
use PhpBotFramework\Exceptions\BotException;
22
23
/**
24
 * \addtogroup Modules
25
 * \brief Build your own bot using modules.
26
 * \details PhpBotFramework\Bot contains all modules and features of this framework but you're probabily not using all of them.
27
 * If you prefer keeping your bot lightweight you can extends PhpFrameworkBot\Core\BaseBot and use modules to add features.
28
 * The BaseBot class includes command handler (command types have to be included manually), api methods and file uploading.
29
 * @{
30
 */
31
32
/** \class User
33
 */
34
trait User
35
{
36
    /** @} */
37
38
    abstract protected function sanitizeUserTable();
39
40
    /** @internal
41
      * \brief PDO connection to the database. */
42
    public $pdo;
43
44
    /**
45
     * \addtogroup Database
46
     * @{
47
     */
48
49
    /**
50
     * \addtogroup Users-handle Users handling
51
     * \brief Handle bot users on the database.
52
     * @{
53
     */
54
55
    /** \brief Table contaning bot users data in the SQL database. */
56
    public $user_table = 'User';
57
58
    /** \brief Name of the column that represents the user id in the sql database */
59
    public $id_column = 'chat_id';
60
61
    /**
62
     * \brief Add a user to the database.
63
     * \details Add a user to the database in Bot::$user_table table and Bot::$id_column column using Bot::$pdo connection.
64
     * @param string|int $chat_id chat ID of the user to add.
65
     * @return bool True on success.
66
     */
67
    public function addUser($chat_id) : bool
68
    {
69
        if (!isset($this->pdo)) {
70
            throw new BotException("Database connection not set");
71
        }
72
73
        $this->sanitizeUserTable();
74
75
        // Create insertion query and initialize variable
76
        $query = "INSERT INTO $this->user_table ($this->id_column) VALUES (:chat_id)";
77
78
        $sth = $this->pdo->prepare($query);
79
        $sth->bindParam(':chat_id', $chat_id);
80
81
        try {
82
            $sth->execute();
83
            $success = true;
84
        } catch (\PDOException $e) {
85
            echo $e->getMessage();
86
87
            $success = false;
88
        }
89
90
        return $success;
91
    }
92
93
    /**
94
     * \brief Send a message to every user available on the database.
95
     * \details Send a message to all subscribed users, change Bot::$user_table and Bot::$id_column to match your database structure.
96
     * This method requires Bot::$pdo connection set.
97
     * All parameters are the same as CoreBot::sendMessage.
98
     * Because a limitation of Telegram Bot API the bot will have a delay after 20 messages sent in different chats.
99
     * @return int How many messages were sent.
100
     * @see CoreBot::sendMessage
101
     */
102
    public function broadcastMessage(
103
        string $text,
104
        string $reply_markup = null,
105
        string $parse_mode = 'HTML',
106
        bool $disable_web_preview = true,
107
        bool $disable_notification = false
108
    ) : int {
109
        if (!isset($this->pdo)) {
110
            throw new BotException("Database connection not set");
111
        }
112
113
        $this->sanitizeUserTable();
114
115
        $sth = $this->pdo->prepare("SELECT $this->id_column FROM $this->user_table");
116
117
        try {
118
            $sth->execute();
119
        } catch (\PDOException $e) {
120
            echo $e->getMessage();
121
        }
122
123
        // Iterate over all the row got
124
        while ($user = $sth->fetch()) {
125
            $user_data = $this->getChat($user[$this->id_column]);
0 ignored issues
show
Bug introduced by
It seems like getChat() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
126
127
            if ($user_data !== false) {
128
                // Change the chat_id for the next API method
129
                $this->bot->setChatID($user[$this->id_column]);
0 ignored issues
show
Bug introduced by
The property bot does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
130
                $this->bot->sendMessage($text, $reply_markup, null, $parse_mode, $disable_web_preview, $disable_notification);
131
            }
132
        }
133
134
        return $sth->rowCount();
135
    }
136
137
    /** @} */
138
139
    /** @} */
140
}
141