Passed
Push — master ( a74354...254a60 )
by Andrea
18:29 queued 11s
created

FiApiController::generateEnumAndOptions()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 47
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 31
nc 6
nop 0
dl 0
loc 47
ccs 0
cts 31
cp 0
crap 42
rs 8.8017
c 0
b 0
f 0
1
<?php
2
3
namespace Cdf\BiCoreBundle\Controller;
4
5
use Cdf\BiCoreBundle\Service\Permessi\PermessiManager;
6
use function count;
7
use ReflectionClass;
8
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
9
use Twig\Environment;
10
use Symfony\Component\Inflector\Inflector;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Inflector\Inflector was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Cdf\BiCoreBundle\Utils\Api\ApiUtils;
12
use \Swagger\Insurance\Model\ModelsClaim;
0 ignored issues
show
Bug introduced by
The type Swagger\Insurance\Model\ModelsClaim was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Cdf\BiCoreBundle\Utils\String\StringUtils;
14
15
class FiApiController extends AbstractController
16
{
17
18
    use FiApiCoreControllerTrait;
19
    use FiApiCoreCrudControllerTrait;
0 ignored issues
show
Bug introduced by
The trait Cdf\BiCoreBundle\Control...CoreCrudControllerTrait requires the property $request which is not provided by Cdf\BiCoreBundle\Controller\FiApiController.
Loading history...
20
    use FiCoreTabellaControllerTrait;
21
22
    protected $bundle;
23
    protected $template;
24
    protected $controller;
25
    protected $permessi;
26
    //API rest attributes
27
    protected $project;
28
    protected $model;
29
    protected $collection;
30
    protected $modelClass;
31
    protected $formClass;
32
    protected $controllerItem;
33
    protected $apiController;
34
35
    protected $options;
36
    protected $enumOptions;
37
    protected $inflectorExceptions;
38
39
    public function __construct(PermessiManager $permessi, Environment $template)
40
    {
41
        $matches = [];
42
        $controllo = new ReflectionClass(get_class($this));
43
44
        preg_match('/(.*)\\\(.*)\\\Controller\\\(.*)Controller/', $controllo->name, $matches);
45
        if (0 == count($matches)) {
46
            preg_match('/(.*)(.*)\\\Controller\\\(.*)Controller/', $controllo->name, $matches);
47
        }
48
        $this->project = $this->getProject();
49
50
        $this->bundle = ($matches[count($matches) - 2] ? $matches[count($matches) - 2] : $matches[count($matches) - 3]);
51
        $this->controller = $matches[count($matches) - 1];
52
        $this->permessi = $permessi;
53
        $this->template = $template;
54
55
        $this->model = $this->controller; //they matches
56
        $this->collection = $this->pluralize($this->model);
57
        $this->modelClass = ApiUtils::getModelClass($this->project, $this->model);
58
        $this->formClass =  ApiUtils::getFormClass($this->model);
59
        $this->controllerItem = ApiUtils::getModelControllerClass($this->project, $this->model);
60
        $this->apiController = ApiUtils::getApiControllerClass($this->project, $this->collection);
61
        $this->options = array();
62
        $this->enumOptions = array();
63
        $this->inflectorExceptions = array();
64
        //it generates options one time for all
65
        $this->loadInflectorExceptions();
66
        $this->generateEnumAndOptions();
67
        //dump($this->options);
68
    }
69
70
    protected function loadInflectorExceptions()
71
    {
72
        $vars = getenv("INFLECTOR_EXCEPTIONS");
73
        if (isset($vars)) {
74
            $values = json_decode($vars, true);
75
            $this->inflectorExceptions = $values;
76
        }
77
    }
78
79
    /**
80
     * Copy this method into your controller in case of exceptions
81
     */
82
    protected function pluralizeForm($singleForm)
83
    {
84
        if (isset($this->inflectorExceptions[$singleForm])) {
85
            return $this->inflectorExceptions[$singleForm];
86
        }
87
        return Inflector::pluralize($singleForm);
88
    }
89
90
    /**
91
     * Pluralize a single form giving as response the correct plurale form matching with existent objects
92
     */
93
    protected function pluralize($singleForm)
94
    {
95
        $outcome = '';
96
        $results = $this->pluralizeForm($singleForm);
97
98
        if (is_array($results)) {
99
            foreach ($results as $result) {
100
                //get name of api controller
101
                $apiClassPath = ApiUtils::getApiControllerClass($this->project, $result);
102
                if (class_exists($apiClassPath)) {
103
                    $outcome = $result;
104
                    break;
105
                }
106
            }
107
        } else {
108
            $outcome = $results;
109
        }
110
        return $outcome;
111
    }
112
113
    /**
114
     * Generate option choices for edit form
115
     */
116
    protected function generateEnumAndOptions()
117
    {
118
        $itemController = new $this->controllerItem();
119
        $fieldMappings = $itemController::swaggerTypes();
120
121
        //dump($fieldMappings);
122
123
        foreach (array_keys($fieldMappings) as $fieldName) {
124
            //is it a foreign key field?
125
            if (\str_contains($fieldName, '_id')) {
126
                $tools = $this->getApiTools($fieldName, '_id');
127
                $apiController = $tools['controller'];
128
                $apiBook = $tools['book'];
129
130
                $method = $apiBook->getAllToString();
131
                $results = $apiController->$method();
132
133
                $arrayContainer = array();
134
                foreach ($results as $myItem) {
135
                    //transform this items for options
136
                    $element = array("id" => $myItem->getCode(), "descrizione" => $myItem->getText(), "valore" => $myItem->getText());
137
                    array_push($arrayContainer, $element);
138
                }
139
                $this->options[$tools['entity']] = $arrayContainer;
140
            } elseif (\str_contains($fieldName, '_enum')) {
141
                //dump("in fieldname ".$fieldName );
142
                $tools = $this->getApiTools($fieldName, '_enum');
143
                $apiController = $tools['controller'];
144
                $apiBook = $tools['book'];
145
146
                $getAllToStringMethod = $apiBook->getAllToString();
147
                $results = $apiController->$getAllToStringMethod();
148
149
                $decodeMap = array();
150
                $arrayContainer = array();
151
                foreach ($results as $result) {
152
                    $decodeMap[$result['code']] = $result['text'];
153
                    $element = array("id" => $result['code'], "descrizione" => $result['text'], "valore" => $result['text']);
154
                    array_push($arrayContainer, $element);
155
                }
156
                $this->options[$tools['entity']] = $arrayContainer;
157
        
158
                $arrayItem = array('nometabella' => $this->controller, 'nomecampo' => "$this->controller.$fieldName", 'etichetta' => "$fieldName",
159
                 'escluso' => false,
160
                'decodifiche' => $decodeMap);
161
162
                array_push($this->enumOptions, $arrayItem);
163
            }
164
        }
165
    }
166
167
    /**
168
     * It returns an array with 'controller' with the apiController
169
     * and 'book' the apiBook
170
     * and 'entity' the given fieldName less the suffix
171
     */
172
    protected function getApiTools($fieldName, $suffixString): array
173
    {
174
        $entityName = substr($fieldName, 0, strpos($fieldName, $suffixString));
175
176
        $parametri = array('str' => $entityName, 'primamaiuscola' => true);
177
        $outcome = StringUtils::toCamelCase($parametri);
178
        $outcome = $this->pluralize($outcome);
179
180
        $apiControllerClass = ApiUtils::getApiControllerClass($this->project, $outcome);
181
        $apiController = new $apiControllerClass();
182
183
        //$apiBook = new ApiUtils($entityName);
184
        $apiBook = new ApiUtils($outcome);
185
186
        $results = [
187
            'controller' => $apiController,
188
            'book' => $apiBook,
189
            'entity' => $entityName,
190
        ];
191
        return $results;
192
    }
193
194
    protected function getBundle()
195
    {
196
        return $this->bundle;
197
    }
198
199
    protected function getController()
200
    {
201
        return $this->controller;
202
    }
203
204
    protected function getPermessi()
205
    {
206
        return $this->permessi;
207
    }
208
209
    protected function getTemplate()
210
    {
211
        return $this->template;
212
    }
213
214
    public function getProject()
215
    {
216
        $annotations = array();
217
        $r = new ReflectionClass(get_class($this));
218
        $doc = $r->getDocComment();
219
        preg_match_all('#@var\(biproject="(.*?)"\)\n#s', $doc, $annotations);
220
        return $annotations[1][0];
221
    }
222
}
223