create([ 'name' => $name, ]); } /** * @param list $items */ public function publish(Bundle $bundle, array $items): BundleVersion { if ($items === []) { throw new DomainRuleException('Ein Paket braucht mindestens einen Bestandteil.'); } $this->assertItems($items); $this->collectArticleIds($bundle->id, $items); return DB::transaction(function () use ($bundle, $items): BundleVersion { $version = $bundle->versions()->create([ 'number' => ((int) $bundle->versions()->max('number')) + 1, 'status' => BundleStatus::Entwurf, ]); foreach (array_values($items) as $index => $item) { $version->items()->create([ 'position' => $index + 1, 'license_article_id' => $item instanceof LicenseArticle ? $item->id : null, 'nested_bundle_id' => $item instanceof Bundle ? $item->id : null, ]); } $version->status = BundleStatus::Veroeffentlicht; $version->save(); return $version->load('items'); }); } /** * @return list */ public function articleIds(BundleVersion $version): array { return $this->collectArticleIds($version->bundle_id, $this->targetsOf($version)); } /** * @param list $items */ private function assertItems(array $items): void { foreach ($items as $item) { if (! $item instanceof LicenseArticle && ! $item instanceof Bundle) { throw new DomainRuleException('Ein Paket enthält nur Lizenzartikel oder andere Pakete.'); } } } /** * @param list $items * @param list $stack * @return list */ private function collectArticleIds(int $bundleId, array $items, array $stack = []): array { if (in_array($bundleId, $stack, true)) { throw new DomainRuleException('Pakete dürfen keinen Zyklus bilden.'); } $stack[] = $bundleId; $articleIds = []; foreach ($items as $item) { if ($item instanceof LicenseArticle) { $articleIds[$item->id] = $item->id; continue; } $published = $this->publishedVersion($item); if ($published === null) { throw new DomainRuleException('Ein eingebettetes Paket braucht eine veröffentlichte Fassung.'); } foreach ($this->collectArticleIds($item->id, $this->targetsOf($published), $stack) as $articleId) { $articleIds[$articleId] = $articleId; } } return array_values($articleIds); } private function publishedVersion(Bundle $bundle): ?BundleVersion { return $bundle->versions() ->where('status', BundleStatus::Veroeffentlicht) ->orderByDesc('number') ->first(); } /** * @return list */ private function targetsOf(BundleVersion $version): array { $targets = []; foreach ($version->items()->orderBy('position')->get() as $item) { $target = $item->article ?? $item->nestedBundle; if ($target === null) { throw new DomainRuleException('Ein Paketbestandteil braucht genau ein Ziel.'); } $targets[] = $target; } return $targets; } }