Completed
Push — dependabot/npm_and_yarn/tippy.... ( 40037f...deaa3c )
by
unknown
400:02 queued 379:38
created

UrlHelper::allOnlineModels()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 12
c 2
b 1
f 0
dl 0
loc 22
ccs 10
cts 10
cp 1
rs 9.8666
cc 3
nc 1
nop 1
crap 3
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 8
    public static function allOnlineModels(bool $onlySingles = false): array
17
    {
18
        return chiefMemoize('all-online-models', function () use ($onlySingles) {
19 8
            $builder = UrlRecord::whereNull('redirect_id')->select('model_type', 'model_id')->groupBy('model_type', 'model_id');
20
21 8
            if ($onlySingles) {
22 6
                $builder->where('model_type', 'singles');
23
            }
24
25
            $liveUrlRecords = $builder->get()->mapToGroups(function ($record) {
26 1
                return [$record->model_type => $record->model_id];
27 8
            });
28
29
            // Get model for each of these records...
30
            $models = $liveUrlRecords->map(function ($record, $key) {
31 1
                return Morphables::instance($key)->find($record->toArray());
32
            })->map->reject(function ($model) {
33
                // Invalid references to archived or removed models where url record still exists.
34 1
                return is_null($model) || !$model->isPublished();
35 8
            })->flatten();
36
37 8
            return FlatReferencePresenter::toGroupedSelectValues($models)->toArray();
38 8
        });
39
    }
40
41 6
    public static function allOnlineSingles()
42
    {
43 6
        return static::allOnlineModels(true);
44
    }
45
}
46