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