Passed
Branch master (989b89)
by Wanderson
01:21
created

Connection::getPDO()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Win\Database;
4
5
use PDO;
6
use PDOException;
7
use Win\DesignPattern\SingletonTrait;
8
use Win\Mvc\Application;
9
10
/**
11
 * Conexão com banco de dados
12
 *
13
 */
14
abstract class Connection {
15
16
	use SingletonTrait;
17
18
	/** @var PDO */
19
	protected $pdo;
20
21
	/** @var PDOException|null */
22
	protected $pdoException;
23
24
	/**
25
	 * Cria e retorna conexão PDO
26
	 * @param string[] $dbConfig
27
	 * @throws PDOException
28
	 * @return PDO
29
	 */
30
	abstract protected function createPdo(&$dbConfig);
31
32
	/** @return PDO */
33
	final public function getPDO() {
34
		return $this->pdo;
35
	}
36
37
	/**
38
	 * Cria uma conexão com um banco de dados
39
	 * @param string[] $dbConfig
40
	 */
41
	public function connect($dbConfig) {
42
		try {
43
			$this->pdo = $this->createPdo($dbConfig);
44
			$this->pdo->exec("set names utf8");
45
			$this->pdoException = null;
46
		} catch (PDOException $ex) {
47
			$this->pdoException = $ex;
48
		}
49
	}
50
51
	/**
52
	 * Retorna TRUE caso a conexão tenha sido bem sucedida
53
	 * @return boolean
54
	 */
55
	public function isValid() {
56
		return (is_null($this->pdoException) && $this->pdo instanceof \PDO);
57
	}
58
59
	/**
60
	 * Redireciona para 503 caso a conexão tenha falhado
61
	 */
62
	public function validate() {
63
		if (!is_null($this->pdoException)) {
64
			Application::app()->errorPage(503, $this->pdoException->getMessage());
65
		}
66
	}
67
68
}
69