GenCrudGenerator   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 255
Duplicated Lines 14.51 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 8
Bugs 3 Features 5
Metric Value
wmc 21
c 8
b 3
f 5
lcom 1
cbo 7
dl 37
loc 255
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
B generate() 0 36 5
B generateControllerClass() 0 32 3
B generateHandlers() 0 29 3
A generateHandlerException() 0 6 1
A generateTestClass() 18 18 1
A processRenderFile() 0 21 1
B addToServices() 0 32 2
A genParamsData() 18 18 3
A generateConfiguration() 0 21 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Kpicaza\GenBundle\Generator;
4
5
use Doctrine\Common\Inflector\Inflector;
6
use Doctrine\ORM\Mapping\ClassMetadataInfo;
7
use Sensio\Bundle\GeneratorBundle\Generator\DoctrineCrudGenerator;
8
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
9
use Symfony\Component\Yaml\Dumper;
10
use Symfony\Component\Yaml\Parser;
11
12
class GenCrudGenerator extends DoctrineCrudGenerator
13
{
14
    protected $services;
15
16
    protected $data;
17
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, $format, $routePrefix, $needWriteActions, $forceOverwrite)
22
    {
23
        $this->routePrefix = $routePrefix;
24
        $this->routeNamePrefix = self::getRouteNamePrefix($routePrefix);
25
        $this->actions = $needWriteActions ? array('index', 'show', 'new', 'edit', 'delete', 'options') : array('index', 'show', 'options');
26
27
        if (count($metadata->identifier) != 1) {
28
            throw new \RuntimeException('The REST generator does not support entity classes with multiple or no primary keys.');
29
        }
30
31
        $this->entity = $entity;
32
        $this->entitySingularized = lcfirst(Inflector::singularize($entity));
33
        $this->entityPluralized = lcfirst(Inflector::pluralize($entity));
34
        $this->bundle = $bundle;
35
        $this->metadata = $metadata;
36
        $this->setFormat($format);
37
38
        $this->data = $this->genParamsData();
39
40
        foreach ($this->data[0]['Handlers'] as $service => $arguments) {
41
            $this->generateHandlers($arguments, $forceOverwrite);
42
        }
43
44
        $this->generateHandlerException();
45
46
        $this->generateControllerClass($forceOverwrite);
47
48
        $dir = sprintf('%s/Resources/views/%s', $this->rootDir, str_replace('\\', '/', strtolower($this->entity)));
49
50
        if (!file_exists($dir)) {
51
            $this->filesystem->mkdir($dir, 0777);
52
        }
53
54
        $this->generateTestClass();
55
        $this->generateConfiguration();
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    protected function generateControllerClass($forceOverwrite)
62
    {
63
        $dir = $this->bundle->getPath();
64
65
        $parts = explode('\\', $this->entity);
66
        $entityClass = array_pop($parts);
67
        $entityNamespace = implode('\\', $parts);
68
        $options = $this->data[0]['Controller'];
69
70
        $target = sprintf(
71
            '%s/Controller/%s/%sController.php',
72
            $dir,
73
            str_replace('\\', '/', $entityNamespace),
74
            $entityClass
75
        );
76
77
        if (!$forceOverwrite && file_exists($target)) {
78
            throw new \RuntimeException('Unable to generate the controller as it already exists.');
79
        }
80
81
        $handler = $this->data[0]['Handlers'];
82
83
        $this->processRenderFile(
84
            'crud/controller.php.twig',
85
            $target,
86
            null,
87
            $entityClass,
88
            $entityNamespace,
89
            key($handler),
90
            $options
91
        );
92
    }
93
94
    /**
95
     * @param $arguments
96
     * @param $forceOverwrite
97
     */
98
    protected function generateHandlers($arguments, $forceOverwrite)
99
    {
100
        $dir = $this->bundle->getPath().'/'.$arguments['dir'];
101
102
        $parts = explode('\\', $this->entity);
103
        $entityClass = array_pop($parts);
104
        $serviceNamespace = $arguments['dir'];
105
106
        $target = sprintf(
107
            '%s/%s.php',
108
            $dir,
109
            $arguments['classname']
110
        );
111
112
        if (!$forceOverwrite && file_exists($target)) {
113
            throw new \RuntimeException('Unable to generate the handler as it already exists.');
114
        }
115
116
        $this->processRenderFile(
117
            'crud/handler.php.twig',
118
            $target,
119
            $arguments['classname'],
120
            $entityClass,
121
            $serviceNamespace,
122
            null
123
        );
124
125
        $this->addToServices($this->data[0]['Handlers']);
126
    }
127
128
    protected function generateHandlerException()
129
    {
130
        return $this->renderFile('crud/formException.php.twig', sprintf('%s/Exception/InvalidFormException.php', $this->bundle->getPath()), array(
131
            'namespace' => $this->bundle->getNamespace(),
132
        ));
133
    }
134
135 View Code Duplication
    protected function generateTestClass()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
136
    {
137
        $parts = explode('\\', $this->entity);
138
        $entityClass = array_pop($parts);
139
140
        $dir = sprintf('%s/../tests/%s/Controller/', $this->rootDir, $this->bundle->getName());
141
142
        $target = $dir.$entityClass.'ControllerTest.php';
143
144
        $this->processRenderFile(
145
            'crud/tests/controllerTest.php.twig',
146
            $target,
147
            sprintf('%sControllerTest', $entityClass),
148
            $entityClass,
149
            'Controller',
150
            null
151
        );
152
    }
153
154
    /**
155
     * @param $file
156
     * @param $target
157
     * @param $classname
158
     * @param $entityClass
159
     * @param $serviceNamespace
160
     * @param null $service
161
     */
162
    protected function processRenderFile($file, $target, $classname, $entityClass, $serviceNamespace, $service = null, $options = null)
163
    {
164
        $this->renderFile($file, $target, array(
165
            'actions' => $this->actions,
166
            'route_prefix' => $this->routePrefix,
167
            'route_name_prefix' => $this->routeNamePrefix,
168
            'bundle' => $this->bundle->getName(),
169
            'entity' => $this->entity,
170
            'entity_singularized' => $this->entitySingularized,
171
            'entity_pluralized' => $this->entityPluralized,
172
            'entity_class' => $entityClass,
173
            'namespace' => $this->bundle->getNamespace(),
174
            'service_namespace' => $serviceNamespace,
175
            'entity_namespace' => $serviceNamespace,
176
            'format' => $this->format,
177
            'class_name' => $classname,
178
            'service' => $service,
179
            'fields' => $this->metadata->fieldMappings,
180
            'options' => $options,
181
        ));
182
    }
183
184
    /**
185
     * @param $definition
186
     */
187
    protected function addToServices($definition)
188
    {
189
        $file = sprintf('%s/config/%s', $this->rootDir, 'services.yml');
190
191
        $yaml = new Parser();
192
        $services = $yaml->parse(file_get_contents($file));
193
194
        if (empty($services['services'][sprintf('app.%s_repository', strtolower($this->entity))])) {
195
            $file = sprintf('%s/config/%s', $this->rootDir, 'gen/services.yml');
196
            $services = array_merge($services, $yaml->parse(file_get_contents($file)));
197
        }
198
199
        $array = array(
200
            key($definition) => array(
201
                'class' => $definition[key($definition)]['class'],
202
                'arguments' => array(
203
                    $definition[key($definition)]['arguments'][0][0],
204
                    $definition[key($definition)]['arguments'][1][0],
205
                ),
206
            ),
207
        );
208
209
        $services['services'][key($array)] = $array[key($array)];
210
211
        $dumper = new Dumper();
212
213
        $yaml = $dumper->dump($services, 4);
214
215
        $file = sprintf('%s/config/%s', $this->rootDir, 'gen/services.yml');
216
217
        file_put_contents($file, $yaml);
218
    }
219
220
    /**
221
     * @return array
222
     */
223 View Code Duplication
    protected function genParamsData()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
224
    {
225
        $data = array();
226
        $dir = sprintf('%s/config/gen/%s', $this->rootDir, $this->entity);
227
        $yaml = new Parser();
228
229
        $files = scandir(str_replace('\\', '/', $dir));
230
231
        foreach ($files as $file) {
232
            if (0 == strpos($file, '.')) {
233
                continue;
234
            }
235
236
            $data[] = $yaml->parse(file_get_contents($dir.'/'.$file));
237
        }
238
239
        return $data;
240
    }
241
242
    /**
243
     * {@inheritdoc}
244
     */
245
    protected function generateConfiguration()
246
    {
247
        if (!in_array($this->format, array('yml', 'xml', 'php'))) {
248
            return;
249
        }
250
251
        $target = sprintf(
252
            '%s/Resources/config/routing/%s.%s',
253
            $this->bundle->getPath(),
254
            strtolower(str_replace('\\', '_', $this->entity)),
255
            $this->format
256
        );
257
258
        $this->renderFile('crud/config/routing.'.$this->format.'.twig', $target, array(
259
            'actions' => $this->actions,
260
            'route_prefix' => $this->routePrefix,
261
            'route_name_prefix' => $this->routeNamePrefix,
262
            'bundle' => $this->bundle->getName(),
263
            'entity' => $this->entity,
264
        ));
265
    }
266
}
267