|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace JustBetter\Detour\Actions; |
| 4 | + |
| 5 | +use JustBetter\Detour\Contracts\CreatesDetoursFromEntry; |
| 6 | +use JustBetter\Detour\Contracts\DeletesDetour; |
| 7 | +use JustBetter\Detour\Contracts\FindsDetour; |
| 8 | +use JustBetter\Detour\Contracts\GetsOldEntryUri; |
| 9 | +use JustBetter\Detour\Contracts\StoresDetour; |
| 10 | +use JustBetter\Detour\Data\Form; |
| 11 | +use JustBetter\Detour\Enums\Type; |
| 12 | +use JustBetter\Detour\Utils\EntryHelper; |
| 13 | +use Statamic\Entries\Entry; |
| 14 | +use Statamic\Facades\Entry as EntryFacade; |
| 15 | + |
| 16 | +class CreateDetoursFromEntry implements CreatesDetoursFromEntry |
| 17 | +{ |
| 18 | + public function __construct( |
| 19 | + protected FindsDetour $findContract, |
| 20 | + protected StoresDetour $storeContract, |
| 21 | + protected DeletesDetour $deleteContract, |
| 22 | + protected GetsOldEntryUri $getOldEntryUriContract, |
| 23 | + ) {} |
| 24 | + |
| 25 | + public function create(Entry $entry): void |
| 26 | + { |
| 27 | + if (! config()->boolean('justbetter.statamic-detour.auto_create')) { |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + $parentEntryId = $entry->id(); |
| 32 | + $parentOldSlug = $entry->getOriginal('slug'); |
| 33 | + $parentNewSlug = $entry->slug(); |
| 34 | + |
| 35 | + foreach (EntryHelper::entryAndDescendantIds($entry) as $entryId) { |
| 36 | + /** @var Entry $target */ |
| 37 | + $target = $entryId === $parentEntryId |
| 38 | + ? $entry |
| 39 | + : EntryFacade::find($entryId); |
| 40 | + |
| 41 | + if ($entryId === $parentEntryId) { |
| 42 | + $this->createDetour($target); |
| 43 | + |
| 44 | + continue; |
| 45 | + } |
| 46 | + |
| 47 | + $this->createDetour($target, $parentOldSlug, $parentNewSlug); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + protected function createDetour(Entry $entry, ?string $parentOldSlug = null, ?string $parentNewSlug = null): void |
| 52 | + { |
| 53 | + if (! $entry->uri()) { |
| 54 | + return; |
| 55 | + } |
| 56 | + if ($parentOldSlug && $parentNewSlug) { |
| 57 | + $oldUri = $this->getOldEntryUriContract->get($entry, $parentOldSlug, $parentNewSlug); |
| 58 | + } else { |
| 59 | + $oldUri = $this->getOldEntryUriContract->get($entry); |
| 60 | + } |
| 61 | + |
| 62 | + if (! $oldUri || $entry->uri() === $oldUri) { |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + if ($conflictingDetour = $this->findContract->firstWhere('from', $entry->uri())) { |
| 67 | + $this->deleteContract->delete($conflictingDetour->id); |
| 68 | + } |
| 69 | + |
| 70 | + $data = Form::make([ |
| 71 | + 'from' => $oldUri, |
| 72 | + 'to' => $entry->uri(), |
| 73 | + 'code' => '301', |
| 74 | + 'type' => Type::Path->value, |
| 75 | + ]); |
| 76 | + |
| 77 | + $this->storeContract->store($data); |
| 78 | + } |
| 79 | + |
| 80 | + public static function bind(): void |
| 81 | + { |
| 82 | + app()->singleton(CreatesDetoursFromEntry::class, static::class); |
| 83 | + } |
| 84 | +} |
0 commit comments