Passed
Push — master ( f85738...3d85c1 )
by Peter
04:52
created

TokenSqlDataMapper::addUserGroups()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 18
rs 9.9
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Admin\Orm\DataMappers;
6
7
use AbterPhp\Admin\Domain\Entities\Token as Entity;
8
use DateTimeImmutable;
9
use Opulence\Orm\DataMappers\SqlDataMapper;
10
use Opulence\QueryBuilders\MySql\QueryBuilder;
11
use Opulence\QueryBuilders\MySql\SelectQuery;
12
13
class TokenSqlDataMapper extends SqlDataMapper implements ITokenDataMapper
14
{
15
    /**
16
     * @param Entity $entity
17
     */
18
    public function add($entity)
19
    {
20
        if (!($entity instanceof Entity)) {
0 ignored issues
show
introduced by
$entity is always a sub-type of AbterPhp\Admin\Domain\Entities\Token.
Loading history...
21
            throw new \InvalidArgumentException(__CLASS__ . ':' . __FUNCTION__ . ' expects a Token entity.');
22
        }
23
24
        $query = (new QueryBuilder())
25
            ->insert(
26
                'tokens',
27
                [
28
                    'id'            => [$entity->getId(), \PDO::PARAM_STR],
29
                    'api_client_id' => [$entity->getApiClientId(), \PDO::PARAM_STR],
30
                    'expires_at'    => [$entity->getExpiresAt(), \PDO::PARAM_STR],
31
                ]
32
            );
33
34
        $statement = $this->writeConnection->prepare($query->getSql());
35
        $statement->bindValues($query->getParameters());
36
        $statement->execute();
37
    }
38
39
    /**
40
     * @param Entity $entity
41
     */
42
    public function delete($entity)
43
    {
44
        if (!($entity instanceof Entity)) {
0 ignored issues
show
introduced by
$entity is always a sub-type of AbterPhp\Admin\Domain\Entities\Token.
Loading history...
45
            throw new \InvalidArgumentException(__CLASS__ . ':' . __FUNCTION__ . ' expects a Token entity.');
46
        }
47
48
        $query = (new QueryBuilder())
49
            ->update(
50
                'tokens',
51
                'tokens',
52
                [
53
                    'deleted' => [1, \PDO::PARAM_INT],
54
                ]
55
            )
56
            ->where('id = ?')
57
            ->addUnnamedPlaceholderValue($entity->getId(), \PDO::PARAM_STR);
58
59
        $statement = $this->writeConnection->prepare($query->getSql());
60
        $statement->bindValues($query->getParameters());
61
        $statement->execute();
62
    }
63
64
    /**
65
     * @return Entity[]
66
     */
67
    public function getAll(): array
68
    {
69
        $query = $this->getBaseQuery();
70
71
        $sql = $query->getSql();
72
73
        return $this->read($sql, [], self::VALUE_TYPE_ARRAY);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->read($sql,...self::VALUE_TYPE_ARRAY) could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
74
    }
75
76
    /**
77
     * @param int|string $id
78
     *
79
     * @return Entity|null
80
     */
81
    public function getById($id): ?Entity
82
    {
83
        $query = $this->getBaseQuery()->andWhere('tokens.id = :user_id');
84
85
        $sql    = $query->getSql();
86
        $params = ['user_id' => [$id, \PDO::PARAM_STR]];
87
88
        return $this->read($sql, $params, self::VALUE_TYPE_ENTITY, true);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->read($sql,...ALUE_TYPE_ENTITY, true) could return the type array which is incompatible with the type-hinted return AbterPhp\Admin\Domain\Entities\Token|null. Consider adding an additional type-check to rule them out.
Loading history...
89
    }
90
91
    /**
92
     * @param string $clientId
93
     *
94
     * @return Entity|null
95
     */
96
    public function getByClientId(string $clientId): ?Entity
97
    {
98
        $query = $this->getBaseQuery()->andWhere('tokens.api_client_id = :api_client_id');
99
100
        $sql    = $query->getSql();
101
        $params = ['api_client_id' => [$clientId, \PDO::PARAM_STR]];
102
103
        return $this->read($sql, $params, self::VALUE_TYPE_ENTITY, true);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->read($sql,...ALUE_TYPE_ENTITY, true) could return the type array which is incompatible with the type-hinted return AbterPhp\Admin\Domain\Entities\Token|null. Consider adding an additional type-check to rule them out.
Loading history...
104
    }
105
106
    /**
107
     * @param Entity $entity
108
     */
109
    public function update($entity)
110
    {
111
        if (!($entity instanceof Entity)) {
0 ignored issues
show
introduced by
$entity is always a sub-type of AbterPhp\Admin\Domain\Entities\Token.
Loading history...
112
            throw new \InvalidArgumentException(__CLASS__ . ':' . __FUNCTION__ . ' expects a Token entity.');
113
        }
114
115
        $query = (new QueryBuilder())
116
            ->update(
117
                'tokens',
118
                'tokens',
119
                [
120
                    'id'            => [$entity->getId(), \PDO::PARAM_STR],
121
                    'api_client_id' => [$entity->getApiClientId(), \PDO::PARAM_STR],
122
                    'expires_at'    => [$entity->getExpiresAt(), \PDO::PARAM_STR],
123
                ]
124
            )
125
            ->where('id = ?')
126
            ->addUnnamedPlaceholderValue($entity->getId(), \PDO::PARAM_STR);
127
128
        $statement = $this->writeConnection->prepare($query->getSql());
129
        $statement->bindValues($query->getParameters());
130
        $statement->execute();
131
    }
132
133
    /**
134
     * @param array $data
135
     *
136
     * @return Entity
137
     */
138
    protected function loadEntity(array $data): Entity
139
    {
140
        if (empty($data['id'])) {
141
            throw new \RuntimeException();
142
        }
143
144
        $expiresAt = new DateTimeImmutable($data['expires_at']);
145
        $revokedAt = null;
146
        if ($revokedAt) {
0 ignored issues
show
introduced by
$revokedAt is of type null, thus it always evaluated to false.
Loading history...
147
            $revokedAt = new DateTimeImmutable($data['revoked_at']);
148
        }
149
150
        return new Entity(
151
            $data['id'],
152
            $data['api_client_id'],
153
            $expiresAt,
154
            $revokedAt
155
        );
156
    }
157
158
    /**
159
     * @return SelectQuery
160
     */
161
    private function getBaseQuery(): SelectQuery
162
    {
163
        /** @var SelectQuery $query */
164
        $query = (new QueryBuilder())
165
            ->select(
166
                'tokens.id',
167
                'tokens.api_client_id',
168
                'tokens.expires_at',
169
                'tokens.revoked_at'
170
            )
171
            ->from('tokens')
172
            ->where('tokens.deleted = 0');
173
174
        return $query;
175
    }
176
}
177