Passed
Push — master ( e3309c...6bfc11 )
by Damien
02:17
created

AuditReader   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 458
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 53
eloc 147
c 5
b 0
f 0
dl 0
loc 458
rs 6.96

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getConfiguration() 0 3 1
A getAuditsByTransactionHash() 0 17 4
A getEntities() 0 16 4
A getAudits() 0 12 1
A getEntityManager() 0 3 1
A getAuditsPager() 0 26 4
A getAudit() 0 25 1
A getAuditsCount() 0 13 2
A filterBy() 0 9 2
A getFilters() 0 3 1
B checkRoles() 0 33 11
A checkAuditable() 0 4 2
A filterByType() 0 10 2
A getEntityTableName() 0 3 1
A filterByObjectId() 0 10 2
A getEntityAuditTableName() 0 8 2
B getAuditsQueryBuilder() 0 44 9
A filterByTransaction() 0 10 2

How to fix   Complexity   

Complex Class

Complex classes like AuditReader often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AuditReader, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace DH\DoctrineAuditBundle\Reader;
4
5
use DH\DoctrineAuditBundle\Annotation\Security;
6
use DH\DoctrineAuditBundle\AuditConfiguration;
7
use DH\DoctrineAuditBundle\Exception\AccessDeniedException;
8
use DH\DoctrineAuditBundle\Exception\InvalidArgumentException;
9
use DH\DoctrineAuditBundle\User\UserInterface;
10
use Doctrine\DBAL\Connection;
11
use Doctrine\DBAL\Query\QueryBuilder;
12
use Doctrine\DBAL\Statement;
13
use Doctrine\ORM\EntityManagerInterface;
14
use Doctrine\ORM\Mapping\ClassMetadata as ORMMetadata;
15
use PDO;
16
use Symfony\Component\Security\Core\Security as CoreSecurity;
17
18
class AuditReader
19
{
20
    public const UPDATE = 'update';
21
    public const ASSOCIATE = 'associate';
22
    public const DISSOCIATE = 'dissociate';
23
    public const INSERT = 'insert';
24
    public const REMOVE = 'remove';
25
26
    public const PAGE_SIZE = 50;
27
28
    /**
29
     * @var AuditConfiguration
30
     */
31
    private $configuration;
32
33
    /**
34
     * @var EntityManagerInterface
35
     */
36
    private $entityManager;
37
38
    /**
39
     * @var array
40
     */
41
    private $filters = [];
42
43
    /**
44
     * AuditReader constructor.
45
     *
46
     * @param AuditConfiguration     $configuration
47
     * @param EntityManagerInterface $entityManager
48
     */
49
    public function __construct(
50
        AuditConfiguration $configuration,
51
        EntityManagerInterface $entityManager
52
    ) {
53
        $this->configuration = $configuration;
54
        $this->entityManager = $entityManager;
55
    }
56
57
    /**
58
     * @return AuditConfiguration
59
     */
60
    public function getConfiguration(): AuditConfiguration
61
    {
62
        return $this->configuration;
63
    }
64
65
    /**
66
     * Set the filter(s) for AuditEntry retrieving.
67
     *
68
     * @param array|string $filter
69
     *
70
     * @return AuditReader
71
     */
72
    public function filterBy($filter): self
73
    {
74
        $filters = \is_array($filter) ? $filter : [$filter];
75
76
        $this->filters = array_filter($filters, static function ($f) {
77
            return \in_array($f, [self::UPDATE, self::ASSOCIATE, self::DISSOCIATE, self::INSERT, self::REMOVE], true);
78
        });
79
80
        return $this;
81
    }
82
83
    /**
84
     * Returns current filter.
85
     *
86
     * @return array
87
     */
88
    public function getFilters(): array
89
    {
90
        return $this->filters;
91
    }
92
93
    /**
94
     * Returns an array of audit table names indexed by entity FQN.
95
     *
96
     * @throws \Doctrine\ORM\ORMException
97
     *
98
     * @return array
99
     */
100
    public function getEntities(): array
101
    {
102
        $metadataDriver = $this->entityManager->getConfiguration()->getMetadataDriverImpl();
103
        $entities = [];
104
        if (null !== $metadataDriver) {
105
            $entities = $metadataDriver->getAllClassNames();
106
        }
107
        $audited = [];
108
        foreach ($entities as $entity) {
109
            if ($this->configuration->isAuditable($entity)) {
110
                $audited[$entity] = $this->getEntityTableName($entity);
111
            }
112
        }
113
        ksort($audited);
114
115
        return $audited;
116
    }
117
118
    /**
119
     * Returns an array of audited entries/operations.
120
     *
121
     * @param string          $entity
122
     * @param null|int|string $id
123
     * @param null|int        $page
124
     * @param null|int        $pageSize
125
     * @param null|string     $transactionHash
126
     * @param bool            $strict
127
     *
128
     * @throws AccessDeniedException
129
     * @throws InvalidArgumentException
130
     *
131
     * @return array
132
     */
133
    public function getAudits(string $entity, $id = null, ?int $page = null, ?int $pageSize = null, ?string $transactionHash = null, bool $strict = true): array
134
    {
135
        $this->checkAuditable($entity);
136
        $this->checkRoles($entity, Security::VIEW_SCOPE);
137
138
        $queryBuilder = $this->getAuditsQueryBuilder($entity, $id, $page, $pageSize, $transactionHash, $strict);
139
140
        /** @var Statement $statement */
141
        $statement = $queryBuilder->execute();
142
        $statement->setFetchMode(PDO::FETCH_CLASS, AuditEntry::class);
143
144
        return $statement->fetchAll();
145
    }
146
147
    /**
148
     * Returns an array of all audited entries/operations for a given transaction hash
149
     * indexed by entity FQCN.
150
     *
151
     * @param string $transactionHash
152
     *
153
     * @throws InvalidArgumentException
154
     * @throws \Doctrine\ORM\ORMException
155
     *
156
     * @return array
157
     */
158
    public function getAuditsByTransactionHash(string $transactionHash): array
159
    {
160
        $results = [];
161
162
        $entities = $this->getEntities();
163
        foreach ($entities as $entity => $tablename) {
164
            try {
165
                $audits = $this->getAudits($entity, null, null, null, $transactionHash);
166
                if (\count($audits) > 0) {
167
                    $results[$entity] = $audits;
168
                }
169
            } catch (AccessDeniedException $e) {
170
                // acces denied
171
            }
172
        }
173
174
        return $results;
175
    }
176
177
    /**
178
     * Returns an array of audited entries/operations.
179
     *
180
     * @param string          $entity
181
     * @param null|int|string $id
182
     * @param int             $page
183
     * @param int             $pageSize
184
     *
185
     * @throws AccessDeniedException
186
     * @throws InvalidArgumentException
187
     *
188
     * @return array
189
     */
190
    public function getAuditsPager(string $entity, $id = null, int $page = 1, int $pageSize = self::PAGE_SIZE): array
191
    {
192
        $queryBuilder = $this->getAuditsQueryBuilder($entity, $id);
193
194
        $currentPage = $page < 1 ? 1 : $page;
195
        $firstResult = ($currentPage - 1) * $pageSize;
196
197
        $queryBuilder
198
            ->setFirstResult($firstResult)
199
            ->setMaxResults($pageSize)
200
        ;
201
202
        $paginator = new Paginator($queryBuilder);
203
        $numResults = $paginator->count();
204
        $hasPreviousPage = $currentPage > 1;
205
        $hasNextPage = ($currentPage * $pageSize) < $numResults;
206
207
        return [
208
            'results' => $paginator->getIterator(),
209
            'currentPage' => $currentPage,
210
            'hasPreviousPage' => $hasPreviousPage,
211
            'hasNextPage' => $hasNextPage,
212
            'previousPage' => $hasPreviousPage ? $currentPage - 1 : null,
213
            'nextPage' => $hasNextPage ? $currentPage + 1 : null,
214
            'numPages' => (int) ceil($numResults / $pageSize),
215
            'haveToPaginate' => $numResults > $pageSize,
216
        ];
217
    }
218
219
    /**
220
     * Returns the amount of audited entries/operations.
221
     *
222
     * @param string          $entity
223
     * @param null|int|string $id
224
     *
225
     * @throws AccessDeniedException
226
     * @throws InvalidArgumentException
227
     *
228
     * @return int
229
     */
230
    public function getAuditsCount(string $entity, $id = null): int
231
    {
232
        $queryBuilder = $this->getAuditsQueryBuilder($entity, $id);
233
234
        $result = $queryBuilder
235
            ->resetQueryPart('select')
236
            ->resetQueryPart('orderBy')
237
            ->select('COUNT(id)')
238
            ->execute()
239
            ->fetchColumn(0)
240
        ;
241
242
        return false === $result ? 0 : $result;
243
    }
244
245
    /**
246
     * @param string $entity
247
     * @param string $id
248
     *
249
     * @throws AccessDeniedException
250
     * @throws InvalidArgumentException
251
     *
252
     * @return mixed[]
253
     */
254
    public function getAudit(string $entity, $id): array
255
    {
256
        $this->checkAuditable($entity);
257
        $this->checkRoles($entity, Security::VIEW_SCOPE);
258
259
        $connection = $this->entityManager->getConnection();
260
261
        /**
262
         * @var \Doctrine\DBAL\Query\QueryBuilder
263
         */
264
        $queryBuilder = $connection->createQueryBuilder();
265
        $queryBuilder
266
            ->select('*')
267
            ->from($this->getEntityAuditTableName($entity))
268
            ->where('id = :id')
269
            ->setParameter('id', $id)
270
        ;
271
272
        $this->filterByType($queryBuilder, $this->filters);
273
274
        /** @var Statement $statement */
275
        $statement = $queryBuilder->execute();
276
        $statement->setFetchMode(PDO::FETCH_CLASS, AuditEntry::class);
277
278
        return $statement->fetchAll();
279
    }
280
281
    /**
282
     * Returns the table name of $entity.
283
     *
284
     * @param string $entity
285
     *
286
     * @return string
287
     */
288
    public function getEntityTableName(string $entity): string
289
    {
290
        return $this->entityManager->getClassMetadata($entity)->getTableName();
291
    }
292
293
    /**
294
     * Returns the audit table name for $entity.
295
     *
296
     * @param string $entity
297
     *
298
     * @return string
299
     */
300
    public function getEntityAuditTableName(string $entity): string
301
    {
302
        $schema = '';
303
        if ($this->entityManager->getClassMetadata($entity)->getSchemaName()) {
304
            $schema = $this->entityManager->getClassMetadata($entity)->getSchemaName().'.';
305
        }
306
307
        return sprintf('%s%s%s%s', $schema, $this->configuration->getTablePrefix(), $this->getEntityTableName($entity), $this->configuration->getTableSuffix());
308
    }
309
310
    /**
311
     * @return EntityManagerInterface
312
     */
313
    public function getEntityManager(): EntityManagerInterface
314
    {
315
        return $this->entityManager;
316
    }
317
318
    private function filterByType(QueryBuilder $queryBuilder, array $filters): QueryBuilder
319
    {
320
        if (!empty($filters)) {
321
            $queryBuilder
322
                ->andWhere('type IN (:filters)')
323
                ->setParameter('filters', $filters, Connection::PARAM_STR_ARRAY)
324
            ;
325
        }
326
327
        return $queryBuilder;
328
    }
329
330
    private function filterByTransaction(QueryBuilder $queryBuilder, ?string $transactionHash): QueryBuilder
331
    {
332
        if (null !== $transactionHash) {
333
            $queryBuilder
334
                ->andWhere('transaction_hash = :transaction_hash')
335
                ->setParameter('transaction_hash', $transactionHash)
336
            ;
337
        }
338
339
        return $queryBuilder;
340
    }
341
342
    /**
343
     * @param QueryBuilder    $queryBuilder
344
     * @param null|int|string $id
345
     *
346
     * @return QueryBuilder
347
     */
348
    private function filterByObjectId(QueryBuilder $queryBuilder, $id): QueryBuilder
349
    {
350
        if (null !== $id) {
351
            $queryBuilder
352
                ->andWhere('object_id = :object_id')
353
                ->setParameter('object_id', $id)
354
            ;
355
        }
356
357
        return $queryBuilder;
358
    }
359
360
    /**
361
     * Returns an array of audited entries/operations.
362
     *
363
     * @param string          $entity
364
     * @param null|int|string $id
365
     * @param null|int        $page
366
     * @param null|int        $pageSize
367
     * @param null|string     $transactionHash
368
     * @param bool            $strict
369
     *
370
     * @throws AccessDeniedException
371
     * @throws InvalidArgumentException
372
     *
373
     * @return QueryBuilder
374
     */
375
    private function getAuditsQueryBuilder(string $entity, $id = null, ?int $page = null, ?int $pageSize = null, ?string $transactionHash = null, bool $strict = true): QueryBuilder
376
    {
377
        $this->checkAuditable($entity);
378
        $this->checkRoles($entity, Security::VIEW_SCOPE);
379
380
        if (null !== $page && $page < 1) {
381
            throw new \InvalidArgumentException('$page must be greater or equal than 1.');
382
        }
383
384
        if (null !== $pageSize && $pageSize < 1) {
385
            throw new \InvalidArgumentException('$pageSize must be greater or equal than 1.');
386
        }
387
388
        $storage = $this->configuration->getEntityManager() ?? $this->entityManager;
389
        $connection = $storage->getConnection();
390
391
        $queryBuilder = $connection->createQueryBuilder();
392
        $queryBuilder
393
            ->select('*')
394
            ->from($this->getEntityAuditTableName($entity), 'at')
395
            ->orderBy('created_at', 'DESC')
396
            ->addOrderBy('id', 'DESC')
397
        ;
398
399
        $metadata = $this->entityManager->getClassMetadata($entity);
400
        if ($strict && $metadata instanceof ORMMetadata && ORMMetadata::INHERITANCE_TYPE_SINGLE_TABLE === $metadata->inheritanceType) {
401
            $queryBuilder
402
                ->andWhere('discriminator = :discriminator')
403
                ->setParameter('discriminator', $entity)
404
            ;
405
        }
406
407
        $this->filterByObjectId($queryBuilder, $id);
408
        $this->filterByType($queryBuilder, $this->filters);
409
        $this->filterByTransaction($queryBuilder, $transactionHash);
410
411
        if (null !== $pageSize) {
412
            $queryBuilder
413
                ->setFirstResult(($page - 1) * $pageSize)
414
                ->setMaxResults($pageSize)
415
            ;
416
        }
417
418
        return $queryBuilder;
419
    }
420
421
    /**
422
     * Throws an InvalidArgumentException if given entity is not auditable.
423
     *
424
     * @param string $entity
425
     *
426
     * @throws InvalidArgumentException
427
     */
428
    private function checkAuditable(string $entity): void
429
    {
430
        if (!$this->configuration->isAuditable($entity)) {
431
            throw new InvalidArgumentException('Entity '.$entity.' is not auditable.');
432
        }
433
    }
434
435
    /**
436
     * Throws an AccessDeniedException if user not is granted to access audits for the given entity.
437
     *
438
     * @param string $entity
439
     * @param string $scope
440
     *
441
     * @throws AccessDeniedException
442
     */
443
    private function checkRoles(string $entity, string $scope): void
444
    {
445
        $userProvider = $this->configuration->getUserProvider();
446
        $user = null === $userProvider ? null : $userProvider->getUser();
447
        $security = null === $userProvider ? null : $userProvider->getSecurity();
448
449
        if (!($user instanceof UserInterface) || !($security instanceof CoreSecurity)) {
450
            // If no security defined or no user identified, consider access granted
451
            return;
452
        }
453
454
        $entities = $this->configuration->getEntities();
455
456
        if (!isset($entities[$entity]['roles']) || null === $entities[$entity]['roles']) {
457
            // If no roles are configured, consider access granted
458
            return;
459
        }
460
461
        if (!isset($entities[$entity]['roles'][$scope]) || null === $entities[$entity]['roles'][$scope]) {
462
            // If no roles for the given scope are configured, consider access granted
463
            return;
464
        }
465
466
        // roles are defined for the give scope
467
        foreach ($entities[$entity]['roles'][$scope] as $role) {
468
            if ($security->isGranted($role)) {
469
                // role granted => access granted
470
                return;
471
            }
472
        }
473
474
        // access denied
475
        throw new AccessDeniedException('You are not allowed to access audits of '.$entity.' entity.');
476
    }
477
}
478