Passed
Push — master ( 827113...b9e4dc )
by Florian
06:14
created

PdoResolver::find()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 16
ccs 9
cts 10
cp 0.9
rs 9.9666
cc 3
nc 4
nop 1
crap 3.009
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Copyright (c) Phauthentic (https://github.com/Phauthentic)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Phauthentic (https://github.com/Phauthentic)
11
 * @link          https://github.com/Phauthentic
12
 * @license       https://opensource.org/licenses/mit-license.php MIT License
13
 */
14
namespace Phauthentic\Authentication\Identifier\Resolver;
15
16
use ArrayAccess;
17
use ArrayObject;
18
use PDO;
19
use PDOException;
20
use PDOStatement;
21
use Phauthentic\Authentication\Identifier\Resolver\ResolverInterface;
22
23
/**
24
 * PDO Resolver
25
 */
26
class PdoResolver implements ResolverInterface
27
{
28
	/**
29
	 * @var \PDO
30
	 */
31
	protected $pdo;
32
33
	/**
34
	 * @var string
35
	 */
36
	protected $sql;
37
38
	/**
39
	 * Constructor.
40
	 *
41
	 * @param \PDO PDO Instance
42
	 * @param string $sql SQL String
43
	 */
44 3
	public function __construct(PDO $pdo, string $sql)
45
	{
46 3
		$this->pdo = $pdo;
47 3
		$this->sql = $sql;
48 3
	}
49
50
	/**
51
	 * Builds the statement
52
	 *
53
	 * @return \PDOStatement
54
	 */
55 3
	protected function buildStatement(): PDOStatement
56
	{
57 3
		$statement = $this->pdo->prepare($this->sql);
58
59 3
		$error = $this->pdo->errorInfo();
60 3
		if ($error[0] !== '00000') {
61
			throw new PDOException($error[2], (int)$error[0]);
62
		}
63
64 3
		return $statement;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $statement could return the type boolean which is incompatible with the type-hinted return PDOStatement. Consider adding an additional type-check to rule them out.
Loading history...
65
	}
66
67
	/**
68
	 * {@inheritDoc}
69
	 */
70 3
	public function find(array $conditions): ?ArrayAccess
71
	{
72 3
		foreach ($conditions as $key => $value) {
73 3
			unset($conditions[$key]);
74 3
			$conditions[':' . $key] = $value;
75
		}
76
77 3
		$statement = $this->buildStatement();
78 3
		$statement->execute($conditions);
79 3
		$result = $statement->fetchAll();
80
81 3
		if (empty($result)) {
82
			return null;
83
		}
84
85 3
		return new ArrayObject($result[0]);
86
	}
87
}
88