Passed
Push — master ( a3a165...30c474 )
by Philippe
38:54 queued 32:37
created

MemoizedUrlRecord::clearCachedRecords()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Thinktomorrow\Chief\Urls;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
class MemoizedUrlRecord extends UrlRecord
8
{
9 56
    public static $cachedRecords;
10
11
    public static function clearCachedRecords()
12 56
    {
13 56
        static::$cachedRecords = null;
14
    }
15
16 75
    /**
17
     * Here we cache all the url records and determine the proper url record
18
     * via the collection methods. This is a lot faster on large data sets.
19 75
     *
20 75
     * @param Model $model
21
     * @param string|null $locale
22
     * @return UrlRecord
23
     * @throws UrlRecordNotFound
24
     */
25
    public static function findByModel(Model $model, string $locale = null): UrlRecord
26
    {
27
        if (!static::$cachedRecords) {
28
            static::$cachedRecords = parent::all();
29
        }
30
31
        $record = static::$cachedRecords
32
            ->where('model_type', $model->getMorphClass())
33
            ->where('model_id', $model->id)
34
            ->where('locale', $locale)
35
            ->sortBy('redirect_id')
36
            ->first();
37
38
        if (!$record) {
39
            throw new UrlRecordNotFound('No url record found for model ['.$model->getMorphClass().'@'.$model->id.'] for locale ['.$locale.'].');
40
        }
41
42
        return $record;
43
    }
44
45
    public static function getByModel(Model $model)
46
    {
47
        return chiefMemoize('url-records-get-by-model', function ($model) {
48
            return parent::getByModel($model);
49
        }, [$model]);
50
    }
51
}
52