Completed
Pull Request — master (#22)
by Sergey
13:18
created

CacheDecorator::find()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
cc 6
eloc 15
nc 8
nop 3
1
<?php
2
3
namespace Isswp101\Persimmon\Cache;
4
5
use Isswp101\Persimmon\Contracts\Storable;
6
use Isswp101\Persimmon\Repository\IRepository;
7
8
class CacheDecorator
9
{
10
    private $repository;
11
    private $cacheRepository;
12
    private static $allColumnsHashes = []; // Static is not a good idea
13
14
    public function __construct(IRepository $repository, IRepository $cacheRepository)
15
    {
16
        $this->repository = $repository;
17
        $this->cacheRepository = $cacheRepository;
18
    }
19
20
    private function getHash(string $id, string $class): string
21
    {
22
        return $class . '@' . $id;
23
    }
24
25
    public function find(string $id, string $class, array $columns = []): ?Storable
26
    {
27
        $hash = $this->getHash($id, $class);
28
        $model = $this->cacheRepository->find($id, $class, $columns);
29
        if ($model) {
30
            if ($columns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $columns of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
31
                if (!array_diff($columns, array_keys($model->toArray()))) {
32
                    return $model;
33
                }
34
            } else {
35
                if (CacheDecorator::$allColumnsHashes[$hash] ?? false) {
36
                    return $model;
37
                }
38
            }
39
        }
40
        $model = $this->repository->find($id, $class, $columns);
41
        $this->cacheRepository->update($model);
42
        if (!$columns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $columns of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
43
            CacheDecorator::$allColumnsHashes[$hash] = true;
44
        }
45
        return $model;
46
    }
47
}