RestGenerator::generateRest()   F
last analyzed

Complexity

Conditions 10
Paths 321

Size

Total Lines 135
Code Lines 77

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 135
rs 3.1304
c 0
b 0
f 0
cc 10
eloc 77
nc 321
nop 2

How to fix   Long Method    Complexity   

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 Yoghi\Bundle\MaddaBundle\Generator;
4
5
/*
6
* This file is part of the MADDA project.
7
*
8
* (c) Stefano Tamagnini <>
9
*
10
* This source file is subject to the GPLv3 license that is bundled
11
* with this source code in the file LICENSE.
12
*/
13
14
use League\Flysystem\Adapter\Local;
15
use Nette\PhpGenerator\Method;
16
use Raml\Exception\InvalidJsonException;
17
use Raml\Exception\RamlParserException;
18
use Raml\Parser;
19
use Symfony\Component\Yaml\Dumper;
20
21
/**
22
 * @author Stefano Tamagnini <>
23
 */
24
class RestGenerator extends AbstractFileGenerator
25
{
26
    /**
27
     * Modello virtuale delle API.
28
     *
29
     * @var \Raml\ApiDefinition
30
     */
31
    private $apiDef;
32
33
    /**
34
     * Informazioni esterne usate per generare i web service.
35
     *
36
     * @var array
37
     */
38
    private $mapExternalInfo;
39
40
    /**
41
     * Name bundle.
42
     *
43
     * @var string
44
     */
45
    private $bundleName;
46
47
    public function __construct($bundleName = 'AppBundle', $mapExternalInfo = [])
48
    {
49
        $this->errors = [];
50
        $this->bundleName = $bundleName;
51
        $this->mapExternalInfo = $mapExternalInfo;
52
    }
53
54
    /**
55
     * Rimuove le parentesi graffe e capitalizza le parole della stringa passata in ingresso.
56
     *
57
     * @param [type] $str [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
58
     *
59
     * @return [type] [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
60
     */
61
    private function removeGraph(&$str)
62
    {
63
        $str = str_replace('{', '', $str);
64
        $str = str_replace('}', '', $str);
65
        $str = ucfirst($str);
66
    }
67
68
    /**
69
     * @param string $ramlFile
70
     */
71
    public function generateRest($ramlFile, Local $directoryOutput)
72
    {
73
        $parser = new Parser();
74
        try {
75
76
            /*
77
             * file di routing symfony
78
             * @var array
79
             */
80
            $routing = [];
81
82
            /*
83
             * Mappa delle proprieta dei controller da generare
84
             * @var array
85
             */
86
            $mappaClassDef = [];
87
88
            $this->apiDef = $parser->parse($ramlFile);
89
            $this->logger->info('Title: '.$this->apiDef->getTitle());
90
91
            $baseUrl = $this->apiDef->getBaseUrl();
92
93
            $parametriBaseUrl = $this->apiDef->getBaseUriParameters();
94
            /** @var \Raml\BaseUriParameter $definition */
95
            foreach ($parametriBaseUrl as $varName => $definition) {
96
                if (!array_key_exists($varName, $this->mapExternalInfo)) {
97
                    $this->error('Missing: '.$varName.' -> '.$definition->getDescription());
98
                    $this->mapExternalInfo[$varName] = 'undefined';
99
                }
100
                $baseUrl = str_replace($varName, $this->mapExternalInfo[$varName], $baseUrl);
101
            }
102
103
            $this->info('BaseUrl '.$baseUrl); //corrisponde a host: "{subdomain}.example.com" dentro routing.yml
104
105
            $enabledProtocols = $this->apiDef->getProtocols(); //serve per fare controlli su http/https -> schemes:  [https] dentro routing.yml
106
107
            $infoSecuritySchema = $this->apiDef->getSecuredBy(); // descrive i vari security schema usati nelle varie risorse
0 ignored issues
show
Unused Code introduced by
$infoSecuritySchema is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
108
109
            /* @var: \Raml\Resource[] */
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
110
            $resources = $this->apiDef->getResources();
111
112
            $namespace = $this->bundleName.'\Controller';
113
114
            /** @var: \Raml\Resource $resource */
115
            foreach ($resources as $resource) {
116
                $displayName = $resource->getDisplayName();
0 ignored issues
show
Bug introduced by
The method getDisplayName cannot be called on $resource (of type resource).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
117
                $this->info('Controller per path: '.$displayName);
118
119
                $names = explode('/', $displayName);
120
                preg_match_all("/(\/{[a-zA-Z]+}(\/)?)+/i", $displayName, $methodParam);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal /(\/{[a-zA-Z]+}(\/)?)+/i does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
121
                array_walk($names, [$this, 'removeGraph']);
122
                $className = implode('', $names);
123
124
                $methods = $resource->getMethods();
0 ignored issues
show
Bug introduced by
The method getMethods cannot be called on $resource (of type resource).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
125
126
                if (count($methods) > 0) {
127
                    /** @var \Raml\Method $method */
128
                    foreach ($methods as $method) {
129
                        $controllerName = ucfirst($className);
130
131
                        // Creo $appBundle / $workspace Controller . php
132
                        $this->info('Genera: '.$namespace.$controllerName.'Controller');
133
                        $controllerProperties = [];
134
                        $controllerProperties['name'] = $controllerName.'Controller';
135
                        $controllerProperties['namespace'] = $namespace;
136
                        $controllerProperties['extend'] = 'Symfony\Bundle\FrameworkBundle\Controller\Controller';
137
138
                        $methodListParams = implode(',', $methodParam[0]);
139
140
                        $type = strtolower($method->getType());
141
                        $methodCallName = $type.$controllerName;
142
                        $actionName = $methodCallName.'Action';
143
                        $this->info('Call Method: '.$actionName.'('.$methodListParams.')');
144
145
                        $controllerProperties['methods'] = [];
146
                        $controllerProperties['methods'][$actionName] = [];
147
                        $controllerProperties['methods'][$actionName]['params'] = [
148
149
                        ];
150
151
                        $description = $method->getDescription();
152
                        $this->info('Description: '.$description);
153
154
                        $entryName = strtolower($className).'_'.$type;
155
                        $routing[$entryName]['path'] = $displayName;
156
                        $routing[$entryName]['defaults']['_controller'] = $this->bundleName.':'.$controllerName.':'.$methodCallName;
157
                        $routing[$entryName]['host'] = $baseUrl;
158
                        $routing[$entryName]['methods'] = [];
159
                        $routing[$entryName]['methods'][] = strtoupper($type);
160
                        $routing[$entryName]['schemas'] = $enabledProtocols;
161
                        $routing[$entryName]['requirements'] = [];
162
                        $routing[$entryName]['requirements'][] = 'FIXME';
163
164
                        $mappaClassDef[$controllerName.'Controller'] = $controllerProperties;
165
                    } //fine methods
166
                }
167
168
                /* @var \Raml\Resource $subResources */
169
                $subResources = $resource->getResources();
0 ignored issues
show
Bug introduced by
The method getResources cannot be called on $resource (of type resource).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
170
171
                foreach ($subResources as $subResource) {
0 ignored issues
show
Bug introduced by
The expression $subResources of type object<Raml\Resource> is not traversable.
Loading history...
Unused Code introduced by
This foreach statement is empty and can be removed.

This check looks for foreach loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Consider removing the loop.

Loading history...
172
                    //$this->analyzeResource($subResource, $directoryOutput);
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
173
                    //// SAMPLE:
174
                    // /Workspace GET => Workspace/GetWorkspace.php
175
                    // /Workspace POST => Workspace/POSTWorkspace.php
176
                    // /Workspace/{id} GET => Workspace/GetWorkspaceById.php
177
                }
178
            } //fine reousrces
179
180
            $indent = 4;
181
            $inline = 2;
182
            $yaml = new Dumper($indent);
183
            $this->currentFile = $yaml->dump($routing, $inline, 0, 0);
184
185
            $this->_createFileOnDir($directoryOutput, $this->bundleName.'/Resources/config/routing.yml');
186
187
            foreach ($mappaClassDef as $className => $controllerProp) {
188
                $this->info('Devo creare '.$className);
189
                $gClassgen = new ClassGenerator($namespace, $className);
190
                $gClassgen->setLogger($this->logger);
191
                $config = new ClassConfig();
192
                $typesReferenceArray = [];
193
                $typesDescArray = [];
194
                $gClassgen->generateClassType($controllerProp, $typesReferenceArray, $typesDescArray, $config);
195
                $gClassgen->createFileOnDir($directoryOutput);
196
            }
197
198
            $this->info('Scrittura su '.$directoryOutput);
199
        } catch (InvalidJsonException $e) {
200
            $this->error('['.$e->getErrorCode().'] '.$e->getMessage());
201
            $this->error($e->getTraceAsString());
202
        } catch (RamlParserException $e) {
203
            $this->error('['.$e->getErrorCode().'] '.$e->getMessage());
0 ignored issues
show
Bug introduced by
The method getErrorCode() does not seem to exist on object<Raml\Exception\RamlParserException>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
204
        }
205
    }
206
}
207