|
| 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 PDOCheck implements CheckInterface |
| 15 | +{ |
| 16 | + private $dsn; |
| 17 | + private $password; |
| 18 | + private $username; |
| 19 | + private $timeout; |
| 20 | + |
| 21 | + /** |
| 22 | + * @param string $dsn |
| 23 | + * @param string $username |
| 24 | + * @param string $password |
| 25 | + * @param int $timeout |
| 26 | + * |
| 27 | + * @return self |
| 28 | + */ |
| 29 | + public function __construct($dsn, $username, $password, $timeout = 1) |
| 30 | + { |
| 31 | + $this->dsn = $dsn; |
| 32 | + $this->username = $username; |
| 33 | + $this->password = $password; |
| 34 | + $this->timeout = $timeout; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @return Result\Failure|Result\Success |
| 39 | + */ |
| 40 | + public function check() |
| 41 | + { |
| 42 | + $msg = 'Could not talk to database server'; |
| 43 | + |
| 44 | + try { |
| 45 | + $pdo = new PDO($this->dsn, $this->username, $this->password); |
| 46 | + |
| 47 | + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); |
| 48 | + $pdo->setAttribute(PDO::ATTR_TIMEOUT, $this->timeout); |
| 49 | + |
| 50 | + $status = $pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS); |
| 51 | + if (null !== $status) { |
| 52 | + return new Result\Success('Connection to database server was successful.'); |
| 53 | + } |
| 54 | + } catch (\PDOException $e) { |
| 55 | + // skip to failure |
| 56 | + $msg .= ', e: ' . $e->getCode(); |
| 57 | + } |
| 58 | + |
| 59 | + return new Result\Failure($msg); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @return string |
| 64 | + */ |
| 65 | + public function getLabel() |
| 66 | + { |
| 67 | + return 'Check if the database server can be reached'; |
| 68 | + } |
| 69 | +} |
0 commit comments