Passed
Push — ft/fields-refactor ( 34e13a...220f3b )
by Ben
81:47
created

UrlHelper::allOnlineModels()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 23
ccs 10
cts 10
cp 1
rs 9.8666
c 1
b 0
f 0
cc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Thinktomorrow\Chief\Urls;
4
5
use Thinktomorrow\Chief\Concerns\Morphable\Morphables;
6
use Thinktomorrow\Chief\FlatReferences\FlatReferencePresenter;
7
8
class UrlHelper
9
{
10
    /**
11
     * Internal api for fetching all models that have an active url
12
     *
13
     * @param bool $onlySingles
14
     * @return array
15
     */
16 6
    public static function allOnlineModels(bool $onlySingles = false): array
17
    {
18
        return chiefMemoize('all-online-models', function () use($onlySingles) {
19
20 6
            $builder = UrlRecord::whereNull('redirect_id')->select('model_type', 'model_id')->groupBy('model_type', 'model_id');
21
22 6
            if($onlySingles) {
23 5
                $builder->where('model_type', 'singles');
24
            }
25
26
            $liveUrlRecords = $builder->get()->mapToGroups(function($record) {
27 1
                return [$record->model_type => $record->model_id];
28 6
            });
29
30
            // Get model for each of these records...
31
            $models = $liveUrlRecords->map(function($record, $key){
32 1
                return Morphables::instance($key)->find($record->toArray());
33
            })->each->reject(function ($model) {
34
                // Invalid references to archived or removed models where url record still exists.
35 1
                return is_null($model);
36 6
            })->flatten();
37
38 6
            return FlatReferencePresenter::toGroupedSelectValues($models)->toArray();
39 6
        });
40
    }
41
42 5
    public static function allOnlineSingles()
43
    {
44 5
        return static::allOnlineModels(true);
45
    }
46
}