1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace LibraryCatalog\Infrastructure\Persistence; |
6
|
|
|
|
7
|
|
|
use LibraryCatalog\Entity\Author; |
8
|
|
|
use LibraryCatalog\Service\Repository\AuthorRepositoryInterface; |
9
|
|
|
use LibraryCatalog\Service\Repository\Exception; |
10
|
|
|
use LibraryCatalog\Service\Repository\PdoTrait; |
11
|
|
|
use LibraryCatalog\Transformer\Serializer; |
12
|
|
|
|
13
|
|
|
class AuthorRepositoryPdo implements AuthorRepositoryInterface |
14
|
|
|
{ |
15
|
|
|
use PdoTrait; |
16
|
|
|
|
17
|
|
|
protected const TABLE_NAME = 'authors'; |
18
|
|
|
|
19
|
|
|
/** @var Serializer */ |
20
|
|
|
protected Serializer $serializer; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* AuthorRepositoryPdo constructor. |
24
|
|
|
* @param Serializer $serializer |
25
|
|
|
* @param string $host |
26
|
|
|
* @param string $user |
27
|
|
|
* @param string $password |
28
|
|
|
* @param string $dbname |
29
|
|
|
*/ |
30
|
1 |
|
public function __construct(Serializer $serializer, string $host, string $user, string $password, string $dbname) |
31
|
|
|
{ |
32
|
1 |
|
$this->prepareConnection($host, $user, $password, $dbname); |
33
|
1 |
|
$this->serializer = $serializer; |
34
|
1 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param mixed $id |
38
|
|
|
* @param bool $withBooks |
39
|
|
|
* @return Author|null |
40
|
|
|
* @throws Exception |
41
|
|
|
* @throws Serializer\HydrateException |
42
|
|
|
*/ |
43
|
5 |
|
public function load($id, bool $withBooks = false): ?Author |
44
|
|
|
{ |
45
|
5 |
|
if ($id == '') { |
46
|
|
|
return null; |
47
|
|
|
} |
48
|
|
|
|
49
|
5 |
|
$data = $this->fetchOne(static::TABLE_NAME, $id); |
50
|
5 |
|
return $data ? $this->serializer->hydrate($data, Author::class) : null; |
|
|
|
|
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param string $name |
55
|
|
|
* @param string $birthdate |
56
|
|
|
* @return Author|null |
57
|
|
|
* @throws Exception |
58
|
|
|
* @throws Serializer\HydrateException |
59
|
|
|
*/ |
60
|
1 |
|
public function loadByNameBirthdate(string $name, string $birthdate): ?Author |
61
|
|
|
{ |
62
|
1 |
|
$data = $this->fetchList(static::TABLE_NAME, 'name = ? and birthdate = ?', [$name, $birthdate], 1); |
63
|
1 |
|
return count($data) >= 1 ? $this->serializer->hydrate($data[0], Author::class) : null; |
|
|
|
|
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param Author $author |
68
|
|
|
* @return void |
69
|
|
|
* @throws Exception |
70
|
|
|
*/ |
71
|
4 |
|
public function save(Author $author): void |
72
|
|
|
{ |
73
|
4 |
|
$author->id = $this->insert(static::TABLE_NAME, $this->serializer->extractFields($author)); |
74
|
4 |
|
} |
75
|
|
|
} |
76
|
|
|
|