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
|
|
|
use RuntimeException; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* PDO Resolver |
26
|
|
|
*/ |
27
|
|
|
class PdoResolver implements ResolverInterface |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* @var \PDO |
31
|
|
|
*/ |
32
|
|
|
protected $pdo; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var string |
36
|
|
|
*/ |
37
|
|
|
protected $sql; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Constructor. |
41
|
|
|
* |
42
|
|
|
* @param \PDO PDO Instance |
43
|
|
|
* @param string $sql SQL String |
44
|
|
|
*/ |
45
|
4 |
|
public function __construct(PDO $pdo, string $sql) |
46
|
|
|
{ |
47
|
4 |
|
$this->pdo = $pdo; |
48
|
4 |
|
$this->sql = $sql; |
49
|
4 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Builds the statement |
53
|
|
|
* |
54
|
|
|
* @return \PDOStatement |
55
|
|
|
*/ |
56
|
4 |
|
protected function buildStatement(): PDOStatement |
57
|
|
|
{ |
58
|
4 |
|
$statement = $this->pdo->prepare($this->sql); |
59
|
|
|
|
60
|
4 |
|
$error = $this->pdo->errorInfo(); |
61
|
4 |
|
if ($error[0] !== '00000') { |
62
|
|
|
throw new PDOException($error[2], (int)$error[0]); |
63
|
|
|
} |
64
|
|
|
|
65
|
4 |
|
if ($statement === false) { |
66
|
|
|
throw new RuntimeException(sprintf( |
67
|
|
|
'There was an error running your PDO resolver using this query: %s', |
68
|
|
|
$this->sql |
69
|
|
|
)); |
70
|
|
|
} |
71
|
|
|
|
72
|
4 |
|
return $statement; |
|
|
|
|
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* {@inheritDoc} |
77
|
|
|
*/ |
78
|
4 |
|
public function find(array $conditions): ?ArrayAccess |
79
|
|
|
{ |
80
|
4 |
|
foreach ($conditions as $key => $value) { |
81
|
4 |
|
unset($conditions[$key]); |
82
|
4 |
|
$conditions[':' . $key] = $value; |
83
|
|
|
} |
84
|
|
|
|
85
|
4 |
|
$statement = $this->buildStatement(); |
86
|
4 |
|
$statement->execute($conditions); |
87
|
4 |
|
$result = $statement->fetchAll(); |
88
|
|
|
|
89
|
4 |
|
if (empty($result)) { |
90
|
|
|
return null; |
91
|
|
|
} |
92
|
|
|
|
93
|
4 |
|
return new ArrayObject($result[0]); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|