$geography InvestmentRelations::dossier() result * @param list $linked opportunity ids already linked to the record * @return array{provinces: list, sector: string, items: list>} */ public function for(InvestmentDossier $record, array $geography, array $linked): array { $provinces = []; foreach ($geography['locations'] ?? [] as $location) { foreach ($location['path'] ?? [] as $node) { $node = (array) $node; if (($node['location_type'] ?? null) === 'province') { $provinces[$node['id']] = $node['name']; } } } $content = $record->content; $sector = trim(implode(' · ', array_filter([$content['sector'] ?? null, $content['clusters'] ?? null]))); $empty = ['provinces' => array_values($provinces), 'sector' => $sector, 'items' => []]; if ($provinces === [] || $sector === '') { return $empty; } $stems = $this->stems($sector.' '.$record->title); $items = []; foreach ($provinces as $id => $name) { $found = app(InvestmentCatalogue::class)->query(['province_id' => $id, 'territory_basis' => 'direct']) ->whereNotIn('opportunities.id', $linked)->limit(200)->get(['opportunities.id', 'title', 'slug', 'summary', 'sector_id']); foreach ($found as $opportunity) { $sectorName = (string) $opportunity->sector?->name; if ($sectorName !== '' && array_intersect($this->stems($sectorName), $stems) !== []) { $items[$opportunity->id] = ['id' => $opportunity->id, 'title' => $opportunity->title, 'slug' => $opportunity->slug, 'summary' => $opportunity->summary, 'sector' => $sectorName, 'province' => $name]; } } } $items = array_values($items); usort($items, fn ($a, $b) => strcmp($a['title'], $b['title'])); return [...$empty, 'items' => array_slice($items, 0, 12)]; } /** Stems too general to say two sectors are the same («Zona Económica Especial» is not «Economia Azul»). */ private const GENERIC = ['economi', 'especia', 'desenvo', 'integra', 'servico', 'naciona', 'regiona', 'program', 'project', 'cadeia', 'valor']; /** @return list seven-letter stems, so «Infraestruturas» meets «Infra-Estrutura». */ private function stems(string $text): array { $normal = preg_replace('/[^a-z ]+/', ' ', str_replace('-', '', strtolower(Str::ascii($text)))); $words = array_filter(explode(' ', (string) $normal), fn ($w) => strlen($w) >= 5); return array_values(array_diff(array_unique(array_map(fn ($w) => substr($w, 0, 7), $words)), self::GENERIC)); } }