|
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
|
8 |
|
$models = static::onlineModels($onlySingles, $ignoredModel); |
|
23
|
|
|
|
|
24
|
8 |
|
return FlatReferencePresenter::toGroupedSelectValues($models)->toArray(); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public static function allOnlineSingles() |
|
28
|
|
|
{ |
|
29
|
|
|
return static::allOnlineModels(true); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Fetch all models that have an active url. Here we check on the ignored model |
|
34
|
|
|
* after retrieval from database so our memoized cache gets optimal usage. |
|
35
|
|
|
* |
|
36
|
|
|
* @param bool $onlySingles |
|
37
|
|
|
* @param Model|null $ignoredModel |
|
38
|
|
|
* @return Collection |
|
39
|
|
|
*/ |
|
40
|
8 |
|
private static function onlineModels(bool $onlySingles = false, Model $ignoredModel = null): Collection |
|
41
|
|
|
{ |
|
42
|
|
|
$models = chiefMemoize('all-online-models', function () use ($onlySingles) { |
|
43
|
8 |
|
$builder = UrlRecord::whereNull('redirect_id') |
|
44
|
8 |
|
->select('model_type', 'model_id') |
|
45
|
8 |
|
->groupBy('model_type', 'model_id'); |
|
46
|
|
|
|
|
47
|
8 |
|
if ($onlySingles) { |
|
48
|
|
|
$builder->where('model_type', 'singles'); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
return $builder->get()->mapToGroups(function ($record) { |
|
52
|
4 |
|
return [$record->model_type => $record->model_id]; |
|
53
|
|
|
})->map(function ($record, $key) { |
|
54
|
4 |
|
return Morphables::instance($key)->find($record->toArray()); |
|
55
|
|
|
})->map->reject(function ($model) { |
|
56
|
4 |
|
return is_null($model) || !$model->isPublished(); // Invalid references to archived or removed models where url record still exists. |
|
57
|
8 |
|
})->flatten(); |
|
58
|
8 |
|
}, [$onlySingles]); |
|
59
|
|
|
|
|
60
|
8 |
|
if ($ignoredModel) { |
|
61
|
|
|
$models = $models->reject(function ($model) use ($ignoredModel) { |
|
62
|
|
|
return (get_class($model) === get_class($ignoredModel) && $model->id === $ignoredModel->id); |
|
63
|
2 |
|
}); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
8 |
|
return $models; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|