1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Urls; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
use Thinktomorrow\Chief\Concerns\Morphable\Morphables; |
8
|
|
|
use Thinktomorrow\Chief\FlatReferences\FlatReferencePresenter; |
9
|
|
|
|
10
|
|
|
class UrlHelper |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Internal api for fetching all models that have an active url. |
14
|
|
|
* This will return a grouped values array ready for select fields |
15
|
|
|
* |
16
|
|
|
* @param bool $onlySingles |
17
|
|
|
* @param Model|null $ignoredModel |
18
|
|
|
* @return array |
19
|
|
|
*/ |
20
|
8 |
|
public static function allOnlineModels(bool $onlySingles = false, Model $ignoredModel = null): array |
21
|
|
|
{ |
22
|
|
|
$models = static::onlineModels($onlySingles, $ignoredModel); |
23
|
8 |
|
|
24
|
8 |
|
return FlatReferencePresenter::toGroupedSelectValues($models)->toArray(); |
25
|
8 |
|
} |
26
|
|
|
|
27
|
8 |
|
public static function allOnlineSingles() |
28
|
|
|
{ |
29
|
|
|
return static::allOnlineModels(true); |
30
|
|
|
} |
31
|
8 |
|
|
32
|
|
|
/** |
33
|
2 |
|
* Fetch all models that have an active url. Here we check on the ignored model |
34
|
2 |
|
* after retrieval from database so our memoized cache gets optimal usage. |
35
|
2 |
|
* |
36
|
2 |
|
* @param bool $onlySingles |
37
|
2 |
|
* @param Model|null $ignoredModel |
38
|
|
|
* @return Collection |
39
|
|
|
*/ |
40
|
|
|
private static function onlineModels(bool $onlySingles = false, Model $ignoredModel = null): Collection |
41
|
3 |
|
{ |
42
|
8 |
|
$models = chiefMemoize('all-online-models', function () use ($onlySingles) { |
43
|
|
|
$builder = UrlRecord::whereNull('redirect_id') |
44
|
|
|
->select('model_type', 'model_id') |
45
|
|
|
->groupBy('model_type', 'model_id'); |
46
|
3 |
|
|
47
|
|
|
if ($onlySingles) { |
48
|
|
|
$builder->where('model_type', 'singles'); |
49
|
3 |
|
} |
50
|
8 |
|
|
51
|
|
|
return $builder->get()->mapToGroups(function ($record) { |
52
|
8 |
|
return [$record->model_type => $record->model_id]; |
53
|
8 |
|
})->map(function ($record, $key) { |
54
|
|
|
return Morphables::instance($key)->find($record->toArray()); |
55
|
|
|
})->map->reject(function ($model) { |
56
|
|
|
return is_null($model) || !$model->isPublished(); // Invalid references to archived or removed models where url record still exists. |
57
|
|
|
})->flatten(); |
58
|
|
|
}, [$onlySingles]); |
59
|
|
|
|
60
|
|
|
if ($ignoredModel) { |
61
|
|
|
$models = $models->reject(function ($model) use ($ignoredModel) { |
62
|
|
|
return (get_class($model) === get_class($ignoredModel) && $model->id === $ignoredModel->id); |
63
|
|
|
}); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $models; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|