CreateItemsCommand::execute()   C
last analyzed

Complexity

Conditions 9
Paths 11

Size

Total Lines 79
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 79
rs 5.6693
c 0
b 0
f 0
cc 9
eloc 51
nc 11
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Rottenwood\KingdomBundle\Command\Console;
4
5
use Rottenwood\KingdomBundle\Entity\Infrastructure\Item;
6
use Rottenwood\KingdomBundle\Entity\InventoryItem;
7
use Rottenwood\KingdomBundle\Entity\Items\ResourceWood;
8
use Rottenwood\KingdomBundle\Entity\RoomResource;
9
use Rottenwood\KingdomBundle\Entity\RoomTypes\Forest;
10
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Symfony\Component\Finder\Finder;
14
use Symfony\Component\Finder\SplFileInfo;
15
use Symfony\Component\Yaml\Parser;
16
17
/** {@inheritDoc} */
18
class CreateItemsCommand extends ContainerAwareCommand
19
{
20
21
    const RESOURCE_QUANTITY = 10;
22
23
    /** {@inheritDoc} */
24
    protected function configure()
25
    {
26
        $this->setName('kingdom:create:items')->setDescription('Создание тестовых предметов');
27
    }
28
29
    /** {@inheritDoc} */
30
    protected function execute(InputInterface $input, OutputInterface $output)
31
    {
32
        $container = $this->getContainer();
33
34
        $itemRepository = $container->get('kingdom.item_repository');
35
        $humanRepository = $container->get('kingdom.human_repository');
36
        $em = $itemRepository->getEntityManager();
37
38
        $items = $itemRepository->findAllItems();
39
        $users = $humanRepository->findAllHumans();
40
        $rooms = $container->get('kingdom.room_repository')->findAllRooms();
41
42
        if (count($items)) {
43
            $output->writeln(
44
                sprintf('Уже создано %d предметов. Удалите их командой kingdom:purge:items', count($items))
45
            );
46
        } else {
47
            $output->writeln('Загрузка данных о предметах ... ');
48
            $allNewItemsData = $this->parseItemsFromYaml();
49
50
            foreach ($allNewItemsData as $newItemType => $newItemsData) {
51
                $newItemType = mb_convert_case($newItemType, MB_CASE_TITLE);
52
                $itemClass = 'Rottenwood\\KingdomBundle\\Entity\\Items\\' . $newItemType;
53
54
                foreach ($newItemsData as $newItemId => $newItemData) {
55
                    /** @var Item $newItem */
56
                    $newItem = new $itemClass(
57
                        $newItemId,
58
                        $newItemData['name'][0],
59
                        $newItemData['name'][1],
60
                        $newItemData['name'][2],
61
                        $newItemData['name'][3],
62
                        $newItemData['name'][4],
63
                        $newItemData['name'][5],
64
                        $newItemData['desc'],
65
                        $newItemData['pic'],
66
                        is_array($newItemData['slots']) ? $newItemData['slots'] : [$newItemData['slots']]
67
                    );
68
69
                    $em->persist($newItem);
70
71
                    $output->writeln(sprintf('Создан предмет %s!', $newItem->getName()));
72
73
                    foreach ($users as $user) {
74
                        $inventoryItem = new InventoryItem($user, $newItem);
75
                        $em->persist($inventoryItem);
76
77
                        $output->writeln(
78
                            sprintf('Предмет "%s" передан персонажу %s.', $newItem->getName(), $user->getName())
79
                        );
80
                    }
81
82
                    if ($newItem instanceof ResourceWood) {
83
                        foreach ($rooms as $room) {
84
                            if ($room->getType() instanceof Forest) {
85
                                $roomResource = new RoomResource($room, $newItem, self::RESOURCE_QUANTITY);
86
                                $em->persist($roomResource);
87
88
                                $output->writeln(
89
                                    sprintf(
90
                                        'Ресурс "%s" добавлен в комнату %s[%d/%d] в количестве %d единиц.',
91
                                        $newItem->getName(),
92
                                        $room->getName(),
93
                                        $room->getX(),
94
                                        $room->getY(),
95
                                        $roomResource->getQuantity()
96
                                    )
97
                                );
98
                            }
99
                        }
100
                    }
101
                }
102
            }
103
104
            $em->flush();
105
106
            $output->writeln('Создано новых предметов: ' . count($itemRepository->findAll()));
107
        }
108
    }
109
110
    /**
111
     * Парсинг yaml-файлов с данными об игровых предметах
112
     * @return array
113
     */
114
    private function parseItemsFromYaml(): array
115
    {
116
        $yamlParser = new Parser();
117
        $fileFinder = new Finder();
118
119
        /** @var SplFileInfo[] $yamlFiles */
120
        $yamlFiles = $fileFinder->files()->in(__DIR__ . '/../../Resources/items')->name('*.yml');
121
122
        $yamlData = [];
123
        foreach ($yamlFiles as $yamlFile) {
124
            $yamlData = array_merge($yamlParser->parse(file_get_contents($yamlFile->getPathname())), $yamlData);
125
        }
126
127
        return $yamlData;
128
    }
129
}
130