Completed
Pull Request — master (#22)
by
unknown
02:03
created

DatabaseHandler   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 163
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 0
dl 0
loc 163
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A connect() 0 14 2
A mergeWithDefaults() 0 4 1
A stringify() 0 20 3
B addUser() 0 38 3
B broadcastMessage() 0 45 5
1
<?php
2
3
namespace PhpBotFramework\Utilities;
4
5
trait DatabaseHandler {
6
    /**
7
     * \brief Open a database connection using PDO.
8
     * \details Provides a simpler way to initialize a database connection
9
     * and create a PDO instance.
10
     * @param $params Parameters for initialize connection.
11
     * @return True on success.
12
     */
13
    public function connect($params) {
14
        try {
15
            $config = $this->stringify($this->mergeWithDefaults($params));
16
17
            $this->pdo = new \PDO($config, $params['username'], $params['password']);
0 ignored issues
show
Bug introduced by
The property pdo 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...
18
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
19
20
            return true;
21
        } catch (PDOException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Utilities\PDOException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
22
            echo 'Unable to connect to database, an error occured:' . $e->getMessage();
23
        }
24
25
        return false;
26
    }
27
28
    protected function mergeWithDefaults($params) {
29
        $DEFAULTS = [ 'adapter' => 'mysql', 'host' => 'localhost' ];
30
        return array_merge($DEFAULTS, $params);
31
    }
32
33
    /** \brief Returns a string that can passed to PDO in order to open connection. */
34
    protected function stringify($params) : string {
35
        $response = $params['adapter'] . ':';
36
        $fields = [];
37
38
        foreach ($params as $field => $value) {
39
            /**
40
             *Check if the current field matches one of the fields
41
             * that are passed to PDO in another way and so don't need
42
             * to be included in the string.
43
             */
44
            if (in_array($field, ['adapter', 'username', 'password'])) {
45
                unset($params[$field]);
46
                continue;
47
            }
48
49
            array_push($fields, $field . '=' . $value);
50
        }
51
52
        return $response . join(';', $fields);
53
    }
54
55
    /**
56
     * \addtogroup Users-handle Users handling
57
     * \brief Handle bot users on the database.
58
     * @{
59
     */
60
61
    /** \brief Table contaning bot users data in the sql database. */
62
    public $user_table = '"User"';
63
64
    /** \brief Name of the column that represents the user id in the sql database */
65
    public $id_column = 'chat_id';
66
67
    /** \brief Add a user to the database.
68
     * \details Add a user to the database in Bot::$user_table table and Bot::$id_column column using Bot::$pdo connection.
69
     * @param $chat_id chat_id of the user to add.
70
     * @return True on success.
71
     */
72
    public function addUser($chat_id) : bool {
73
74
        // Is there database connection?
75
        if (!isset($this->pdo)) {
76
77
            throw new BotException("Database connection not set");
78
79
        }
80
81
        // Create insertion query and initialize variable
82
        $query = "INSERT INTO $this->user_table ($this->id_column) VALUES (:chat_id)";
83
84
        // Prepare the query
85
        $sth = $this->pdo->prepare($query);
86
87
        // Add the chat_id to the query
88
        $sth->bindParam(':chat_id', $chat_id);
89
90
        try {
91
92
            $sth->execute();
93
            $success = true;
94
95
        } catch (PDOException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Utilities\PDOException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
96
97
            echo $e->getMessage();
98
99
            $success = false;
100
101
        }
102
103
        // Close statement
104
        $sth = null;
0 ignored issues
show
Unused Code introduced by
$sth is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
105
106
        // Return result
107
        return $success;
108
109
    }
110
111
    /**
112
     * \brief Broadcast a message to all user registred on the database.
113
     * \details Send a message to all users subscribed, change Bot::$user_table and Bot::$id_column to match your database structure is.
114
     * This method requires Bot::$pdo connection set.
115
     * All parameters are the same as CoreBot::sendMessage.
116
     * Because a limitation of Telegram Bot API the bot will have a delay after 20 messages sent in different chats.
117
     * @see CoreBot::sendMessage
118
     */
119
    public function broadcastMessage($text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = true, bool $disable_notification = false) {
120
121
        // Is there database connection?
122
        if (!isset($this->pdo)) {
123
124
            throw new BotException("Database connection not set");
125
126
        }
127
128
        // Prepare the query to get all chat_id from the database
129
        $sth = $this->pdo->prepare("SELECT $this->id_column FROM $this->user_table");
130
131
        try {
132
133
            $sth->execute();
134
135
        } catch (PDOException $e) {
0 ignored issues
show
Bug introduced by
The class PhpBotFramework\Utilities\PDOException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
136
137
            echo $e->getMessage();
138
139
        }
140
141
        // Iterate over all the row got
142
        while ($user = $sth->fetch()) {
143
144
            // Call getChat to know that this users haven't blocked the bot
145
            $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...
146
147
            // Did they block it?
148
            if ($user_data !== false) {
149
150
                // Change the chat_id for the next API method
151
                $this->setChatID($user[$this->id_column]);
0 ignored issues
show
Bug introduced by
It seems like setChatID() 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...
152
153
                // Send the message
154
                $this->sendMessage($text, $reply_markup, null, $parse_mode, $disable_web_preview, $disable_notification);
0 ignored issues
show
Bug introduced by
It seems like sendMessage() 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...
155
156
            }
157
158
        }
159
160
        // Close statement
161
        $sth = null;
0 ignored issues
show
Unused Code introduced by
$sth is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
162
163
    }
164
165
    /** @} */
166
167
}
168