48 lines
1.8 KiB
PHP
48 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Catalog;
|
|
|
|
use Modules\Core\Catalog\Services\CollectionService;
|
|
|
|
/**
|
|
* Breadcrumb items for a collection and its ancestors, root first, in the
|
|
* shape <x-breadcrumb> takes. Home is added by the component itself.
|
|
*
|
|
* Interim: the indexed `ancestors` field gives the right ids and order, but
|
|
* its names are translated once at index time (CollectionIndexer uses
|
|
* translateAttribute('name') with no locale), so they'd show in the wrong
|
|
* language on the other locale. Each ancestor is re-read via getById() for a
|
|
* current-locale name instead. Trees are shallow, so it's one or two extra
|
|
* index lookups. Drop the re-read once core indexes ancestor names per locale.
|
|
*/
|
|
final class CollectionTrail
|
|
{
|
|
public function __construct(
|
|
private readonly CollectionService $collections,
|
|
) {}
|
|
|
|
/**
|
|
* @param array<string, mixed> $collection a localized CollectionService document
|
|
* @param bool $linkLast false when the collection itself is the current page
|
|
* @return array<int, array{label: string, href?: string}>
|
|
*/
|
|
public function for(array $collection, bool $linkLast = true): array
|
|
{
|
|
$ancestors = collect($collection['ancestors'] ?? [])
|
|
->map(fn (array $ancestor) => [
|
|
// Untranslated collections resolve to a null name, so keep the
|
|
// index-time name as a fallback.
|
|
'label' => $this->collections->getById((int) $ancestor['id'])['name'] ?? $ancestor['name'],
|
|
'href' => route('category.show', ['id' => $ancestor['id']]),
|
|
]);
|
|
|
|
$self = ['label' => $collection['name'] ?? ''];
|
|
|
|
if ($linkLast) {
|
|
$self['href'] = route('category.show', ['id' => $collection['id']]);
|
|
}
|
|
|
|
return [...$ancestors->values()->all(), $self];
|
|
}
|
|
}
|