|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Realms\RolePlaying; |
| 6 | + |
| 7 | +use App\Realms\RolePlaying\Inventory\Item; |
| 8 | +use App\Realms\RolePlaying\Inventory\ItemType; |
| 9 | +use App\Realms\RolePlaying\Inventory\Problems\CannotWearMultipleArmors; |
| 10 | +use App\Realms\RolePlaying\Inventory\Problems\CannotWearTooManyRings; |
| 11 | +use App\Realms\RolePlaying\Inventory\Problems\NoDualWielding; |
| 12 | +use App\Realms\RolePlaying\Inventory\Problems\WeaponNotEquipped; |
| 13 | +use loophp\collection\Collection; |
| 14 | + |
| 15 | +final class WarriorBuilder |
| 16 | +{ |
| 17 | + private string $name = "player"; |
| 18 | + private int $hitPoints = 100; |
| 19 | + private array $items = []; |
| 20 | + |
| 21 | + public static function start(): self |
| 22 | + { |
| 23 | + return new self(); |
| 24 | + } |
| 25 | + |
| 26 | + public function withHitPoints(int $hitPoints): self |
| 27 | + { |
| 28 | + $this->hitPoints = $hitPoints; |
| 29 | + return $this; |
| 30 | + } |
| 31 | + |
| 32 | + public function withName(string $name): self |
| 33 | + { |
| 34 | + $this->name = $name; |
| 35 | + return $this; |
| 36 | + } |
| 37 | + |
| 38 | + public function withItems(Item ...$items): self |
| 39 | + { |
| 40 | + $this->items = array_merge($this->items, $items); |
| 41 | + return $this; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @throws WeaponNotEquipped |
| 46 | + * @throws NoDualWielding |
| 47 | + * @throws CannotWearMultipleArmors |
| 48 | + * @throws CannotWearTooManyRings |
| 49 | + */ |
| 50 | + public function build(): Character |
| 51 | + { |
| 52 | + $items = Collection::fromIterable($this->items); |
| 53 | + |
| 54 | + $countByType = static fn (ItemType $type) => $items |
| 55 | + ->filter(static fn (Item $item) => $item->type->is($type)) |
| 56 | + ->count(); |
| 57 | + |
| 58 | + WeaponNotEquipped::whenNoWeapon($countByType(ItemType::Weapon)); |
| 59 | + NoDualWielding::whenMoreThanOneWeapon($countByType(ItemType::Weapon)); |
| 60 | + CannotWearMultipleArmors::whenMoreThanOneArmor($countByType(ItemType::Armor)); |
| 61 | + CannotWearTooManyRings::whenMoreThanTwoRings($countByType(ItemType::Ring)); |
| 62 | + |
| 63 | + return Character::of($this->name, $this->hitPoints, ...$this->items); |
| 64 | + } |
| 65 | +} |
0 commit comments