Completed
Pull Request — master (#254)
by Loïc
01:51
created

MakeGrid::askForNextField()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 8.5123
c 0
b 0
f 0
cc 6
nc 10
nop 2
1
<?php
2
3
/*
4
 * This file is part of monofony.
5
 *
6
 * (c) Mobizel
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace App\Maker;
15
16
use App\Maker\Helper\GridHelper;
17
use App\Maker\Helper\ResourceHelper;
18
use Symfony\Bundle\MakerBundle\ConsoleStyle;
19
use Symfony\Bundle\MakerBundle\DependencyBuilder;
20
use Symfony\Bundle\MakerBundle\Generator;
21
use Symfony\Bundle\MakerBundle\InputConfiguration;
22
use Symfony\Bundle\MakerBundle\Maker\AbstractMaker;
23
use Symfony\Component\Console\Command\Command;
24
use Symfony\Component\Console\Input\InputArgument;
25
use Symfony\Component\Console\Input\InputInterface;
26
use Symfony\Component\Console\Question\ChoiceQuestion;
27
use Symfony\Component\Filesystem\Filesystem;
28
use Symfony\Component\Yaml\Yaml;
29
use Webmozart\Assert\Assert;
30
31
final class MakeGrid extends AbstractMaker
32
{
33
    public static $defaultActionTypes = [
34
        'main' => [
35
            'create' => 'create',
36
        ],
37
        'item' => [
38
            'update' => 'update',
39
            'delete' => 'delete',
40
        ],
41
        'bulk' => [
42
            'delete' => 'delete',
43
        ],
44
    ];
45
46
    /** @var string */
47
    private $projectDir;
48
49
    /** @var ResourceHelper */
50
    private $resourceHelper;
51
52
    /** @var GridHelper */
53
    private $gridHelper;
54
55
    /** @var Filesystem */
56
    private $fileSystem;
57
58
    public function __construct(string $projectDir, ResourceHelper $resourceHelper, GridHelper $gridHelper)
59
    {
60
        $this->projectDir = $projectDir;
61
        $this->resourceHelper = $resourceHelper;
62
        $this->gridHelper = $gridHelper;
63
64
        $this->fileSystem = new Filesystem();
65
    }
66
67
    public static function getCommandName(): string
68
    {
69
        return 'make:sylius-grid';
70
    }
71
72
    public function configureCommand(Command $command, InputConfiguration $inputConfig)
73
    {
74
        $command
75
            ->setDescription('Creates a new grid')
76
            ->addArgument('section', InputArgument::REQUIRED, 'Section of the grid (backend or frontend)')
77
            ->addArgument('resource', InputArgument::REQUIRED, 'Resource alias of the grid')
78
        ;
79
80
        $inputConfig->setArgumentAsNonInteractive('resource');
81
        $inputConfig->setArgumentAsNonInteractive('section');
82
    }
83
84
    public function interact(InputInterface $input, ConsoleStyle $io, Command $command)
85
    {
86
        if (!$input->getArgument('section')) {
87
            $question = new ChoiceQuestion(
88
                'Please select a section for your grid',
89
                ['backend', 'frontend'],
90
                0
91
            );
92
93
            $section = $io->askQuestion($question);
94
95
            $input->setArgument('section', $section);
96
        }
97
98
        if (!$input->getArgument('resource')) {
99
            $question = new ChoiceQuestion(
100
                'Please select a resource for your grid',
101
                $this->resourceHelper->getResourcesAliases(),
102
                0
103
            );
104
105
            $resourceAlias = $io->askQuestion($question);
106
107
            $input->setArgument('resource', $resourceAlias);
108
        }
109
110
        if ($resourceAlias = $input->getArgument('resource')) {
111
            Assert::true($this->resourceHelper->isResourceAliasExist($resourceAlias), sprintf(
0 ignored issues
show
Bug introduced by
It seems like $resourceAlias defined by $input->getArgument('resource') on line 110 can also be of type array<integer,string>; however, App\Maker\Helper\Resourc...:isResourceAliasExist() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
112
                    'Resource with alias %s not found',
113
                    $resourceAlias
114
                )
115
            );
116
        }
117
    }
118
119
    public function configureDependencies(DependencyBuilder $dependencies)
120
    {
121
    }
122
123
    public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator)
124
    {
125
        $resourceAlias = $input->getArgument('resource');
126
127
        $fields = [];
128
        $isFirstField = true;
129
        while (true) {
130
            $newField = $this->askForNextField($io, $isFirstField);
131
            $isFirstField = false;
132
133
            if (null === $newField) {
134
                break;
135
            }
136
137
            $fields = array_merge($fields, $newField);
138
        }
139
140
        $actions = [
141
            'main' => [],
142
            'item' => [],
143
            'bulk' => [],
144
        ];
145
146
        foreach ($actions as $section => $data) {
147
            $hasSectionAction = $io->confirm(sprintf('Do you have %s actions?', $section), true);
148
149
            if ($hasSectionAction) {
150
                $newActions = $this->askForNextAction($io, $section);
151
                $actions[$section] = array_merge($actions[$section], $newActions);
152
            } else {
153
                unset($actions[$section]);
154
            }
155
        }
156
157
        $this->generateGridConfigFile($input, $io, $generator, $fields, $actions);
158
    }
159
160
    private function askForNextField(ConsoleStyle $io, bool $isFirstField)
161
    {
162
        $io->writeln('');
163
164
        if ($isFirstField) {
165
            $questionText = 'New field name (press <return> to stop adding fields)';
166
        } else {
167
            $questionText = 'Add another field? Enter the field name (or press <return> to stop adding fields)';
168
        }
169
170
        $fieldName = $io->ask($questionText, null, function ($name) {
171
            // allow it to be empty
172
            if (!$name) {
173
                return $name;
174
            }
175
176
            return $name;
177
        });
178
179
        if (!$fieldName) {
180
            return null;
181
        }
182
183
        $fieldType = $io->choice('Enter the field type', $this->gridHelper->getFilterIds(), 'string');
184
        $fieldLabel = $io->ask('Enter the field label', '~');
185
        $isSortable = $io->confirm('Is the field sortable?', true);
186
187
        if ($isSortable) {
188
            $fieldSortable = $io->ask('Enter the sortable path', '~');
189
        }
190
191
        $fieldData = [
192
            'type' => $fieldType,
193
            'label' => $fieldLabel,
194
        ];
195
196
        if ($isSortable) {
197
            $fieldData['sortable'] = $fieldSortable;
198
        }
199
200
        return [
201
            $fieldName => [
202
                'type' => $fieldType,
203
                'label' => $fieldLabel,
204
                'sortable' => $fieldSortable ?? null,
205
            ],
206
        ];
207
    }
208
209
    private function askForNextAction(ConsoleStyle $io, string $section)
210
    {
211
        $io->writeln('');
212
213
        $actionTypes = static::$defaultActionTypes[$section];
214
215
        if (count($actionTypes) > 1) {
216
            $choiceQuestion = new ChoiceQuestion(
217
                'Enter the action types (coma-separated)',
218
                static::$defaultActionTypes[$section],
219
                implode(', ', static::$defaultActionTypes[$section])
220
            );
221
            $choiceQuestion->setMultiselect(true);
222
            $actionTypes = $io->askQuestion($choiceQuestion);
223
        }
224
225
        $data = [];
226
        foreach ($actionTypes as $type) {
227
            $data[$type] = [
228
                'type' => $type,
229
            ];
230
        }
231
232
        return $data;
233
    }
234
235
    private function generateGridConfigFile(
236
        InputInterface $input,
237
        ConsoleStyle $io,
0 ignored issues
show
Unused Code introduced by
The parameter $io is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
238
        Generator $generator,
0 ignored issues
show
Unused Code introduced by
The parameter $generator is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
239
        array $fields,
240
        array $actions
241
    ): void {
242
        $section = $input->getArgument('section');
243
        $resourceAlias = $input->getArgument('resource');
244
        [$appName, $resourceName] = $this->resourceHelper->splitResourceAlias($resourceAlias);
0 ignored issues
show
Bug introduced by
It seems like $resourceAlias defined by $input->getArgument('resource') on line 243 can also be of type array<integer,string> or null; however, App\Maker\Helper\Resourc...r::splitResourceAlias() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
245
        $gridId = sprintf('%s_%s_%s', $appName, $section, $resourceName);
246
247
        $gridConfigDir = $this->getGridConfigDir($resourceAlias, $section);
0 ignored issues
show
Bug introduced by
It seems like $resourceAlias defined by $input->getArgument('resource') on line 243 can also be of type array<integer,string> or null; however, App\Maker\MakeGrid::getGridConfigDir() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $section defined by $input->getArgument('section') on line 242 can also be of type array<integer,string> or null; however, App\Maker\MakeGrid::getGridConfigDir() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
248
        $modelClass = $this->resourceHelper->getResourceModelFromAlias($resourceAlias);
0 ignored issues
show
Bug introduced by
It seems like $resourceAlias defined by $input->getArgument('resource') on line 243 can also be of type array<integer,string> or null; however, App\Maker\Helper\Resourc...esourceModelFromAlias() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
249
250
        $gridData = [
251
            'driver' => [
252
                'name' => 'doctrine/orm',
253
                'options' => [
254
                    'class' => '"%'.$modelClass.'%"',
255
                ],
256
            ],
257
        ];
258
259
        if (count($fields) > 0) {
260
            $gridData['fields'] = $fields;
261
        }
262
263
        if (count($actions) > 0) {
264
            $gridData['actions'] = $actions;
265
        }
266
267
        $data = [
268
            'sylius_grids' => [
269
                'grids' => [
270
                    $gridId => $gridData,
271
                ],
272
            ],
273
        ];
274
275
        $yaml = Yaml::dump($data, 10);
276
277
        $this->fileSystem->dumpFile($gridConfigDir, $yaml);
278
    }
279
280
    private function getGridConfigDir(string $resourceAlias, string $section)
281
    {
282
        $resource = $this->resourceHelper->getResourceNameFromAlias($resourceAlias);
283
        $filename = $resource.'.yaml';
284
285
        return sprintf('%s/%s/%s', $this->projectDir.'/config/packages/grids', $section, $filename);
286
    }
287
}
288