]> git.mxchange.org Git - friendica.git/blob - tests/Util/Database/StaticDatabase.php
Rework Module\ToggleMobile to check for local links
[friendica.git] / tests / Util / Database / StaticDatabase.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Test\Util\Database;
23
24 use Friendica\Database\Database;
25 use Friendica\Database\DatabaseException;
26 use PDO;
27 use PDOException;
28
29 /**
30  * Overrides the Friendica database class for re-using the connection
31  * for different tests
32  *
33  * Overrides functionality to enforce one transaction per call (for nested transactions)
34  */
35 class StaticDatabase extends Database
36 {
37         /**
38          * @var ExtendedPDO
39          */
40         private static $staticConnection;
41
42         /** @var bool  */
43         private $_locked = false;
44
45         /**
46          * Override the behaviour of connect, due there is just one, static connection at all
47          *
48          * @return bool Success
49          */
50         public function connect(): bool
51         {
52                 if (!is_null($this->connection) && $this->connected()) {
53                         return true;
54                 }
55
56                 if (!isset(self::$staticConnection)) {
57                         self::statConnect($_SERVER);
58                 }
59
60                 $this->driver = 'pdo';
61                 $this->connection = self::$staticConnection;
62                 $this->connected = true;
63
64                 return $this->connected;
65         }
66
67         /**
68          * Override the transaction since there are now hierarchical transactions possible
69          *
70          * @return bool
71          */
72         public function transaction(): bool
73         {
74                 if (!$this->in_transaction && !$this->connection->beginTransaction()) {
75                         return false;
76                 }
77
78                 $this->in_transaction = true;
79                 return true;
80         }
81
82         /** Mock for locking tables */
83         public function lock($table): bool
84         {
85                 if ($this->_locked) {
86                         return false;
87                 }
88
89                 $this->in_transaction = true;
90                 $this->_locked = true;
91
92                 return true;
93         }
94
95         /** Mock for unlocking tables */
96         public function unlock(): bool
97         {
98                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
99                 $this->performCommit();
100
101                 $this->in_transaction = false;
102                 $this->_locked = false;
103
104                 return true;
105         }
106
107         /**
108          * Does a commit
109          *
110          * @return bool Was the command executed successfully?
111          */
112         public function commit(): bool
113         {
114                 if (!$this->performCommit()) {
115                         return false;
116                 }
117                 $this->in_transaction = false;
118                 return true;
119         }
120
121         /**
122          * Setup of the global, static connection
123          * Either through explicit calling or through implicit using the Database
124          *
125          * @param array $server $_SERVER variables
126          *
127          * @throws \Exception
128          */
129         public static function statConnect(array $server)
130         {
131                 // Init variables
132                 $db_host = $db_user = $db_data = $db_pw = '';
133
134                 // Use environment variables for mysql if they are set beforehand
135                 if (!empty($server['MYSQL_HOST'])
136                     && (!empty($server['MYSQL_USERNAME']) || !empty($server['MYSQL_USER']))
137                     && $server['MYSQL_PASSWORD'] !== false
138                     && !empty($server['MYSQL_DATABASE']))
139                 {
140                         $db_host = $server['MYSQL_HOST'];
141                         if (!empty($server['MYSQL_PORT'])) {
142                                 $db_host .= ':' . $server['MYSQL_PORT'];
143                         }
144
145                         if (!empty($server['MYSQL_USERNAME'])) {
146                                 $db_user = $server['MYSQL_USERNAME'];
147                         } else {
148                                 $db_user = $server['MYSQL_USER'];
149                         }
150                         $db_pw = (string) $server['MYSQL_PASSWORD'];
151                         $db_data = $server['MYSQL_DATABASE'];
152                 }
153
154                 if (empty($db_host) || empty($db_user) || empty($db_data)) {
155                         throw new DatabaseException('Either one of the following settings are missing: Host, User or Database', 999, 'CONNECT');
156                 }
157
158                 $port       = 0;
159                 $serveraddr = trim($db_host);
160                 $serverdata = explode(':', $serveraddr);
161                 $server     = $serverdata[0];
162                 if (count($serverdata) > 1) {
163                         $port = (int) trim($serverdata[1]);
164                 }
165                 $server  = trim($server);
166                 $user    = trim($db_user);
167                 $pass    = trim($db_pw);
168                 $db      = trim($db_data);
169
170                 if (!(strlen($server) && strlen($user) && strlen($db))) {
171                         return;
172                 }
173
174                 $connect = "mysql:host=" . $server . ";dbname=" . $db;
175
176                 if ($port > 0) {
177                         $connect .= ";port=" . $port;
178                 }
179
180                 try {
181                         self::$staticConnection = @new ExtendedPDO($connect, $user, $pass);
182                         self::$staticConnection->setAttribute(PDO::ATTR_AUTOCOMMIT,0);
183                 } catch (PDOException $e) {
184                         /*
185                          * @TODO Try to find a way to log this exception as it contains valuable information
186                          * @nupplaphil@github.com comment:
187                          *
188                          * There is no easy possibility to add a logger here, that's why
189                          * there isn't any yet and instead a placeholder.. This execution
190                          * point is a critical state during a testrun, and tbh I'd like to
191                          * leave here no further logic (yet) because I spent hours debugging
192                          * cases, where transactions weren't fully closed and
193                          * strange/unpredictable errors occur (sometimes -mainly during
194                          * debugging other errors :) ...)
195                          */
196                 }
197         }
198
199         /**
200          * @return ExtendedPDO The global, static connection
201          */
202         public static function getGlobConnection()
203         {
204                 return self::$staticConnection;
205         }
206
207         /**
208          * Perform a global rollback for every nested transaction of the static connection
209          */
210         public static function statRollback()
211         {
212                 if (isset(self::$staticConnection)) {
213                         while (self::$staticConnection->getTransactionDepth() > 0) {
214                                 self::$staticConnection->rollBack();
215                         }
216                 }
217         }
218 }