Passed
Push — master ( 4c08a2...19d2d9 )
by Damien
03:42
created

AuditReader::getConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
     * @param string $entity
221
     * @param string $id
222
     *
223
     * @throws AccessDeniedException
224
     * @throws InvalidArgumentException
225
     *
226
     * @return mixed[]
227
     */
228
    public function getAudit(string $entity, $id): array
229
    {
230
        $this->checkAuditable($entity);
231
        $this->checkRoles($entity, Security::VIEW_SCOPE);
232
233
        $connection = $this->entityManager->getConnection();
234
235
        /**
236
         * @var \Doctrine\DBAL\Query\QueryBuilder
237
         */
238
        $queryBuilder = $connection->createQueryBuilder();
239
        $queryBuilder
240
            ->select('*')
241
            ->from($this->getEntityAuditTableName($entity))
242
            ->where('id = :id')
243
            ->setParameter('id', $id)
244
        ;
245
246
        $this->filterByType($queryBuilder, $this->filters);
247
248
        /** @var Statement $statement */
249
        $statement = $queryBuilder->execute();
250
        $statement->setFetchMode(PDO::FETCH_CLASS, AuditEntry::class);
251
252
        return $statement->fetchAll();
253
    }
254
255
    /**
256
     * Returns the table name of $entity.
257
     *
258
     * @param string $entity
259
     *
260
     * @return string
261
     */
262
    public function getEntityTableName(string $entity): string
263
    {
264
        return $this->entityManager->getClassMetadata($entity)->getTableName();
265
    }
266
267
    /**
268
     * Returns the audit table name for $entity.
269
     *
270
     * @param string $entity
271
     *
272
     * @return string
273
     */
274
    public function getEntityAuditTableName(string $entity): string
275
    {
276
        $schema = '';
277
        if ($this->entityManager->getClassMetadata($entity)->getSchemaName()) {
278
            $schema = $this->entityManager->getClassMetadata($entity)->getSchemaName().'.';
279
        }
280
281
        return sprintf('%s%s%s%s', $schema, $this->configuration->getTablePrefix(), $this->getEntityTableName($entity), $this->configuration->getTableSuffix());
282
    }
283
284
    /**
285
     * @return EntityManagerInterface
286
     */
287
    public function getEntityManager(): EntityManagerInterface
288
    {
289
        return $this->entityManager;
290
    }
291
292
    private function filterByType(QueryBuilder $queryBuilder, array $filters): QueryBuilder
293
    {
294
        if (!empty($filters)) {
295
            $queryBuilder
296
                ->andWhere('type IN (:filters)')
297
                ->setParameter('filters', $filters, Connection::PARAM_STR_ARRAY)
298
            ;
299
        }
300
301
        return $queryBuilder;
302
    }
303
304
    private function filterByTransaction(QueryBuilder $queryBuilder, ?string $transactionHash): QueryBuilder
305
    {
306
        if (null !== $transactionHash) {
307
            $queryBuilder
308
                ->andWhere('transaction_hash = :transaction_hash')
309
                ->setParameter('transaction_hash', $transactionHash)
310
            ;
311
        }
312
313
        return $queryBuilder;
314
    }
315
316
    /**
317
     * @param QueryBuilder    $queryBuilder
318
     * @param null|int|string $id
319
     *
320
     * @return QueryBuilder
321
     */
322
    private function filterByObjectId(QueryBuilder $queryBuilder, $id): QueryBuilder
323
    {
324
        if (null !== $id) {
325
            $queryBuilder
326
                ->andWhere('object_id = :object_id')
327
                ->setParameter('object_id', $id)
328
            ;
329
        }
330
331
        return $queryBuilder;
332
    }
333
334
    /**
335
     * Returns an array of audited entries/operations.
336
     *
337
     * @param string          $entity
338
     * @param null|int|string $id
339
     * @param null|int        $page
340
     * @param null|int        $pageSize
341
     * @param null|string     $transactionHash
342
     * @param bool            $strict
343
     *
344
     * @throws AccessDeniedException
345
     * @throws InvalidArgumentException
346
     *
347
     * @return QueryBuilder
348
     */
349
    private function getAuditsQueryBuilder(string $entity, $id = null, ?int $page = null, ?int $pageSize = null, ?string $transactionHash = null, bool $strict = true): QueryBuilder
350
    {
351
        $this->checkAuditable($entity);
352
        $this->checkRoles($entity, Security::VIEW_SCOPE);
353
354
        if (null !== $page && $page < 1) {
355
            throw new \InvalidArgumentException('$page must be greater or equal than 1.');
356
        }
357
358
        if (null !== $pageSize && $pageSize < 1) {
359
            throw new \InvalidArgumentException('$pageSize must be greater or equal than 1.');
360
        }
361
362
        $storage = $this->configuration->getEntityManager() ?? $this->entityManager;
363
        $connection = $storage->getConnection();
364
365
        $queryBuilder = $connection->createQueryBuilder();
366
        $queryBuilder
367
            ->select('*')
368
            ->from($this->getEntityAuditTableName($entity), 'at')
369
            ->orderBy('created_at', 'DESC')
370
            ->addOrderBy('id', 'DESC')
371
        ;
372
373
        $metadata = $this->entityManager->getClassMetadata($entity);
374
        if ($strict && $metadata instanceof ORMMetadata && ORMMetadata::INHERITANCE_TYPE_SINGLE_TABLE === $metadata->inheritanceType) {
375
            $queryBuilder
376
                ->andWhere('discriminator = :discriminator')
377
                ->setParameter('discriminator', $entity)
378
            ;
379
        }
380
381
        $this->filterByObjectId($queryBuilder, $id);
382
        $this->filterByType($queryBuilder, $this->filters);
383
        $this->filterByTransaction($queryBuilder, $transactionHash);
384
385
        if (null !== $pageSize) {
386
            $queryBuilder
387
                ->setFirstResult(($page - 1) * $pageSize)
388
                ->setMaxResults($pageSize)
389
            ;
390
        }
391
392
        return $queryBuilder;
393
    }
394
395
    /**
396
     * Throws an InvalidArgumentException if given entity is not auditable.
397
     *
398
     * @param string $entity
399
     *
400
     * @throws InvalidArgumentException
401
     */
402
    private function checkAuditable(string $entity): void
403
    {
404
        if (!$this->configuration->isAuditable($entity)) {
405
            throw new InvalidArgumentException('Entity '.$entity.' is not auditable.');
406
        }
407
    }
408
409
    /**
410
     * Throws an AccessDeniedException if user not is granted to access audits for the given entity.
411
     *
412
     * @param string $entity
413
     * @param string $scope
414
     *
415
     * @throws AccessDeniedException
416
     */
417
    private function checkRoles(string $entity, string $scope): void
418
    {
419
        $userProvider = $this->configuration->getUserProvider();
420
        $user = null === $userProvider ? null : $userProvider->getUser();
421
        $security = null === $userProvider ? null : $userProvider->getSecurity();
422
423
        if (!($user instanceof UserInterface) || !($security instanceof CoreSecurity)) {
424
            // If no security defined or no user identified, consider access granted
425
            return;
426
        }
427
428
        $entities = $this->configuration->getEntities();
429
430
        if (!isset($entities[$entity]['roles']) || null === $entities[$entity]['roles']) {
431
            // If no roles are configured, consider access granted
432
            return;
433
        }
434
435
        if (!isset($entities[$entity]['roles'][$scope]) || null === $entities[$entity]['roles'][$scope]) {
436
            // If no roles for the given scope are configured, consider access granted
437
            return;
438
        }
439
440
        // roles are defined for the give scope
441
        foreach ($entities[$entity]['roles'][$scope] as $role) {
442
            if ($security->isGranted($role)) {
443
                // role granted => access granted
444
                return;
445
            }
446
        }
447
448
        // access denied
449
        throw new AccessDeniedException('You are not allowed to access audits of '.$entity.' entity.');
450
    }
451
}
452