Completed
Push — development ( 9736ae...1c21f9 )
by Mirco
24s queued 10s
created

SecurityRolesRepository::fetchUserRoles()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
1
<?php
2
3
namespace Oc\Repository;
4
5
use Doctrine\DBAL\Connection;
6
use Oc\Entity\SecurityRolesEntity;
7
use Oc\Entity\UserEntity;
8
use Oc\Repository\Exception\RecordAlreadyExistsException;
9
use Oc\Repository\Exception\RecordNotFoundException;
10
use Oc\Repository\Exception\RecordNotPersistedException;
11
use Oc\Repository\Exception\RecordsNotFoundException;
12
13
class SecurityRolesRepository
14
{
15
    const TABLE = 'security_roles';
16
17
    /** @var Connection */
18
    private $connection;
19
20
21
    public function __construct(Connection $connection)
22
    {
23
        $this->connection = $connection;
24
    }
25
26
27
    /**
28
     * @return SecurityRolesEntity[]
29
     */
30
    public function fetchAll()
31
    {
32
        $statement = $this->connection->createQueryBuilder()
33
            ->select('*')
34
            ->from(self::TABLE)
35
            ->execute();
36
37
        $result = $statement->fetchAll();
38
39
        if ($statement->rowCount() === 0) {
40
            throw new RecordsNotFoundException('No records found');
41
        }
42
43
        $records = [];
44
45
        foreach ($result as $item) {
46
            $records[] = $this->getEntityFromDatabaseArray($item);
47
        }
48
49
        return $records;
50
    }
51
52
    /**
53
     * @return SecurityRolesEntity
54
     */
55
    public function fetchOneBy(array $where = [])
56
    {
57
        $queryBuilder = $this->connection->createQueryBuilder()
58
            ->select('*')
59
            ->from(self::TABLE)
60
            ->setMaxResults(1);
61
62
        if (count($where) > 0) {
63
            foreach ($where as $column => $value) {
64
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
65
            }
66
        }
67
68
        $statement = $queryBuilder->execute();
69
70
        $result = $statement->fetch();
71
72
        if ($statement->rowCount() === 0) {
73
            throw new RecordNotFoundException('Record with given where clause not found');
74
        }
75
76
        return $this->getEntityFromDatabaseArray($result);
77
    }
78
79
80
    /**
81
     * @return SecurityRolesEntity[]
82
     */
83
    public function fetchBy(array $where = [])
84
    {
85
        $queryBuilder = $this->connection->createQueryBuilder()
86
            ->select('*')
87
            ->from(self::TABLE);
88
89
        if (count($where) > 0) {
90
            foreach ($where as $column => $value) {
91
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
92
            }
93
        }
94
95
        $statement = $queryBuilder->execute();
96
97
        $result = $statement->fetchAll();
98
99
        if ($statement->rowCount() === 0) {
100
            throw new RecordsNotFoundException('No records with given where clause found');
101
        }
102
103
        $entities = [];
104
105
        foreach ($result as $item) {
106
            $entities[] = $this->getEntityFromDatabaseArray($item);
107
        }
108
109
        return $entities;
110
    }
111
112
113
    public function fetchUserRoles(UserEntity $user)
114
    {
115
        $statement = $this->connection->createQueryBuilder()
116
            ->select('*')
117
            ->from(self::TABLE, 'sr')
118
            ->join('sr', 'user_roles', 'ur', 'sr.id = ur.role_id')
119
            ->where('ur.user_id = :userId')
120
            ->setParameter(':userId', $user->id)
121
            ->execute();
122
123
        $result = $statement->fetchAll();
124
125
        if ($statement->rowCount() === 0) {
126
            throw new RecordsNotFoundException('No records found');
127
        }
128
129
        $records = [];
130
131
        foreach ($result as $item) {
132
            $records[] = $this->getEntityFromDatabaseArray($item);
133
        }
134
135
        return array_map(static function ($role) {return $role->role;}, $records);
136
    }
137
138
139
    /**
140
     * @return SecurityRolesEntity
141
     */
142
    public function create(SecurityRolesEntity $entity)
143
    {
144
        if (!$entity->isNew()) {
145
            throw new RecordAlreadyExistsException('The entity does already exist.');
146
        }
147
148
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
149
150
        $this->connection->insert(
151
            self::TABLE,
152
            $databaseArray
153
        );
154
155
        $entity->id = (int)$this->connection->lastInsertId();
156
157
        return $entity;
158
    }
159
160
161
    /**
162
     * @return SecurityRolesEntity
163
     */
164
    public function update(SecurityRolesEntity $entity)
165
    {
166
        if ($entity->isNew()) {
167
            throw new RecordNotPersistedException('The entity does not exist.');
168
        }
169
170
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
171
172
        $this->connection->update(
173
            self::TABLE,
174
            $databaseArray,
175
            ['id' => $entity->id]
176
        );
177
178
        return $entity;
179
    }
180
181
182
    /**
183
     * @return SecurityRolesEntity
184
     */
185
    public function remove(SecurityRolesEntity $entity)
186
    {
187
        if ($entity->isNew()) {
188
            throw new RecordNotPersistedException('The entity does not exist.');
189
        }
190
191
        $this->connection->delete(
192
            self::TABLE,
193
            ['id' => $entity->id]
194
        );
195
196
        $entity->cacheId = null;
0 ignored issues
show
Bug introduced by
The property cacheId does not seem to exist in Oc\Entity\SecurityRolesEntity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
197
198
        return $entity;
199
    }
200
201
202
    /**
203
     * @return []
0 ignored issues
show
Documentation introduced by
The doc-type [] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
204
     */
205
    public function getDatabaseArrayFromEntity(SecurityRolesEntity $entity)
206
    {
207
        return [
208
            'id' => $entity->id,
209
            'role' => $entity->role,
210
        ];
211
    }
212
213
    /**
214
     * @return SecurityRolesEntity
215
     */
216
    public function getEntityFromDatabaseArray(array $data)
217
    {
218
        $entity = new SecurityRolesEntity();
219
        $entity->id = (int)$data['id'];
220
        $entity->role = (string)$data['role'];
221
        return $entity;
222
    }
223
}
224