Implement CommandFactory

This commit is contained in:
Kacper Majczak 2022-09-12 14:32:37 +02:00
parent 448e7f04a6
commit d18f1c7e6f

View File

@ -6,44 +6,65 @@ namespace GildedRose;
final class GildedRose final class GildedRose
{ {
private const SULFURAS_HAND_OF_RAGNAROS = 'Sulfuras, Hand of Ragnaros';
private const BACKSTAGE_PASSES_TO_A_TAFKAL_80_ETC_CONCERT = 'Backstage passes to a TAFKAL80ETC concert';
private const AGED_BRIE = 'Aged Brie';
/** /**
* @var Item[] * @var Item[]
*/ */
private $items; private $items;
private CommandFactory $commandFactory;
public function __construct(array $items) public function __construct(array $items)
{ {
$this->items = $items; $this->items = $items;
$this->commandFactory = new CommandFactory();
} }
public function updateQuality(): void public function updateQuality(): void
{ {
foreach ($this->items as $item) { foreach ($this->items as $item) {
if ($item->name === self::AGED_BRIE) { $command = $this->commandFactory->createFor($item->name);
(new AgedBrieCommand())->execute($item);
$command->execute($item);
}
}
} }
if ($item->name === self::BACKSTAGE_PASSES_TO_A_TAFKAL_80_ETC_CONCERT) {
(new BackstageCommand())->execute($item); interface Command
{
public function execute(Item $item): void;
} }
if (in_array($item->name, final class CommandFactory
{
private const SULFURAS_HAND_OF_RAGNAROS = 'Sulfuras, Hand of Ragnaros';
private const BACKSTAGE_PASSES_TO_A_TAFKAL_80_ETC_CONCERT = 'Backstage passes to a TAFKAL80ETC concert';
private const AGED_BRIE = 'Aged Brie';
public function createFor(string $itemName): Command
{
if ($itemName === self::AGED_BRIE) {
return new AgedBrieCommand();
}
if ($itemName === self::BACKSTAGE_PASSES_TO_A_TAFKAL_80_ETC_CONCERT) {
return new BackstageCommand();
}
if (in_array($itemName,
[ [
self::AGED_BRIE, self::AGED_BRIE,
self::BACKSTAGE_PASSES_TO_A_TAFKAL_80_ETC_CONCERT, self::BACKSTAGE_PASSES_TO_A_TAFKAL_80_ETC_CONCERT,
self::SULFURAS_HAND_OF_RAGNAROS self::SULFURAS_HAND_OF_RAGNAROS
] ]
) === false) { ) === false) {
(new NormalCommand())->execute($item); return new NormalCommand();
}
} }
return new NoopCommand();
} }
} }
final class AgedBrieCommand final class AgedBrieCommand implements Command
{ {
public function execute(Item $item): void public function execute(Item $item): void
{ {
@ -56,7 +77,7 @@ final class AgedBrieCommand
} }
} }
final class BackstageCommand final class BackstageCommand implements Command
{ {
public function execute(Item $item): void public function execute(Item $item): void
{ {
@ -78,7 +99,7 @@ final class BackstageCommand
} }
} }
final class NormalCommand final class NormalCommand implements Command
{ {
public function execute(Item $item): void public function execute(Item $item): void
{ {
@ -89,3 +110,11 @@ final class NormalCommand
} }
} }
} }
final class NoopCommand implements Command
{
public function execute(Item $item): void
{
// noop
}
}