Completed
Push — master ( 08d7ff...cbdf77 )
by Midori
01:25
created

AbstractRepository::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace midorikocak\nanodb;
6
7
use Exception;
8
use midorikocak\querymaker\QueryInterface;
9
use ReflectionException;
10
11
use function array_filter;
12
use function array_key_exists;
13
use function array_map;
14
use function is_array;
15
16
abstract class AbstractRepository implements RepositoryInterface
17
{
18
    protected Database $db;
19
    protected string $tableName = '';
20
    protected string $className = '';
21
22
    public function __construct(Database $db)
23
    {
24
        $this->db = $db;
25
        $this->className = __NAMESPACE__ . '\\' . $this->className;
26
    }
27
28
    /**
29
     * @throws ReflectionException
30
     */
31
    public function read(string $id): Item
32
    {
33
        if ($id) {
34
            $this->db->select($this->tableName)->where('id', $id)->execute();
35
        } else {
36
            $this->db->select($this->tableName)->execute();
37
        }
38
        return $this->className::fromArray($this->db->fetch());
39
    }
40
41
    /**
42
     * @return Item[]
43
     */
44
    public function readAll(?QueryInterface $query = null): array
45
    {
46
        if ($query !== null) {
47
            $db = $this->db->query($query);
48
        } else {
49
            $db = $this->db->select($this->tableName);
50
        }
51
52
        $db->execute();
53
        $items = $db->fetchAll();
54
        return array_map(function ($item) {
55
            $article = $this->className::fromArray($item);
56
            if (array_key_exists('id', $item)) {
57
                $article->setId($item['id']);
58
            }
59
            if (array_key_exists('user_id', $item)) {
60
                $article->setUserId($item['user_id']);
61
            }
62
63
            return $article;
64
        }, $items);
65
    }
66
67
    /**
68
     * @param Item $item
69
     * @throws ReflectionException
70
     */
71
    public function save($item): Item
72
    {
73
        if ($item->getId() !== null) {
74
            $data = $item->toArray();
75
76
            $id = $data['id'];
77
78
            unset($data['id']);
79
80
            $this->db->update($this->tableName, $data)->where('id', $id)->execute();
81
82
            return $this->read($id);
83
        }
84
85
        $itemData = array_filter($item->toArray(), fn($item) => !is_array($item));
86
87
        if ($this->db->insert($this->tableName, $itemData)->execute() === false) {
88
            throw new Exception('Not Found.');
89
        }
90
91
        $lastInsertId = $this->db->lastInsertId();
92
        $updatedItem = $this->db->select($this->tableName)->where('id', $lastInsertId)->fetch();
93
94
        $item = $this->className::fromArray($updatedItem);
95
        $item->setFromArray($updatedItem);
96
        return $item;
97
    }
98
99
    public function remove($item): int
100
    {
101
        $id = $item->getId();
102
        if ($id !== null) {
103
            $this->db->delete($this->tableName)->where('id', $id)->execute();
104
            return $this->db->rowCount();
105
        }
106
        return 0;
107
    }
108
}
109