|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Betta\ModifyClasses\Concerns; |
| 4 | + |
| 5 | +trait CanRemove |
| 6 | +{ |
| 7 | + protected ?string $removeable = null; |
| 8 | + protected ?string $removeableType = null; |
| 9 | + |
| 10 | + public function removeMany(array $injectables): static |
| 11 | + { |
| 12 | + foreach ($injectables as $injectable) { |
| 13 | + $this->remove($injectable); |
| 14 | + } |
| 15 | + return $this; |
| 16 | + } |
| 17 | + |
| 18 | + public function remove(string $removeable): static |
| 19 | + { |
| 20 | + $this->removeable = $removeable; |
| 21 | + $this->removeableType(); |
| 22 | + $this->handleRemoveable(); |
| 23 | + $this->reset(); |
| 24 | + |
| 25 | + return $this; |
| 26 | + } |
| 27 | + |
| 28 | + protected function getRemoveable(): ?string |
| 29 | + { |
| 30 | + return $this->removeable; |
| 31 | + } |
| 32 | + |
| 33 | + protected function getRemoveableName(): string |
| 34 | + { |
| 35 | + return class_basename($this->getRemoveable()); |
| 36 | + } |
| 37 | + |
| 38 | + protected function removeInterface(): void |
| 39 | + { |
| 40 | + if (! $this->hasInterface()) { |
| 41 | + return; |
| 42 | + } |
| 43 | + $this->injectDescriptor(); |
| 44 | + $this->removeImport($this->getRemoveable()); |
| 45 | + } |
| 46 | + |
| 47 | + protected function hasInterface(): bool |
| 48 | + { |
| 49 | + return $this->getImplements()->filter(fn ($interface) => $interface === $this->getRemoveable())->isNotEmpty(); |
| 50 | + } |
| 51 | + |
| 52 | + protected function removeTrait(): void |
| 53 | + { |
| 54 | + $this->removeImport($this->getRemoveable()); |
| 55 | + $this->removeUse(); |
| 56 | + } |
| 57 | + |
| 58 | + protected function removeUse(): void |
| 59 | + { |
| 60 | + collect([ |
| 61 | + "use {$this->getRemoveable()};", |
| 62 | + "use {$this->getRemoveableName()};", |
| 63 | + ])->each(fn ($line) => $this->buffer = $this->buffer->remove($line)); |
| 64 | + } |
| 65 | + |
| 66 | + protected function handleRemoveable(): void |
| 67 | + { |
| 68 | + match ($this->getRemoveableType()) { |
| 69 | + 'interface' => $this->removeInterface(), |
| 70 | + 'trait' => $this->removeTrait(), |
| 71 | + }; |
| 72 | + } |
| 73 | + |
| 74 | + public function getRemoveableType(): ?string |
| 75 | + { |
| 76 | + return $this->removeableType; |
| 77 | + } |
| 78 | + |
| 79 | + protected function removeableType(): void |
| 80 | + { |
| 81 | + $this->removeableType = $this->getType($this->removeable); |
| 82 | + } |
| 83 | +} |
0 commit comments