Skip to content
This repository was archived by the owner on Jan 31, 2020. It is now read-only.

Commit b45d0fb

Browse files
committed
Enhancement: a check for MySQL connections
Related: easybib/issues#4396
1 parent 83ea42d commit b45d0fb

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?php
2+
/**
3+
* @license http://framework.zend.com/license/new-bsd New BSD License
4+
*/
5+
6+
namespace ZendDiagnostics\Check;
7+
8+
use PDO;
9+
use ZendDiagnostics\Result;
10+
11+
/**
12+
* Ensures a connection to the MySQL server/database is possible.
13+
*/
14+
class MySQLCheck implements CheckInterface
15+
{
16+
private $dbname;
17+
private $host;
18+
private $passwd;
19+
private $port;
20+
private $username;
21+
22+
/**
23+
* @param string $host
24+
* @param string $username
25+
* @param string $passwd
26+
* @param string $dbname
27+
* @param int $port
28+
*
29+
* @return self
30+
*/
31+
public function __construct($host, $username, $passwd, $dbname, $port = 3306)
32+
{
33+
$this->host = $host;
34+
$this->username = $username;
35+
$this->passwd = $passwd;
36+
$this->dbname = $dbname;
37+
$this->port = $port;
38+
}
39+
40+
/**
41+
* @return Result\Failure|Result\Success
42+
*/
43+
public function check()
44+
{
45+
$dsn = sprintf(
46+
'mysql:host=%s;dbname=%s;charset=utf8;port=%d',
47+
$this->host,
48+
$this->dbname,
49+
$this->port
50+
);
51+
52+
$msg = 'Could not talk to mysql';
53+
54+
try {
55+
$pdo = new PDO(
56+
$dsn,
57+
$this->username,
58+
$this->passwd
59+
);
60+
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
61+
$pdo->setAttribute(PDO::ATTR_TIMEOUT, 1); // 1 second timeout
62+
$status = $pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS);
63+
if (null !== $status) {
64+
return new Result\Success('Can haz MySQL');
65+
}
66+
} catch (\PDOException $e) {
67+
// skip to failure
68+
$msg .= ', e: ' . $e->getCode();
69+
}
70+
71+
return new Result\Failure($msg);
72+
}
73+
74+
/**
75+
* @return string
76+
*/
77+
public function getLabel()
78+
{
79+
return 'Check if MySQL can be reached';
80+
}
81+
}

0 commit comments

Comments
 (0)