FiApiController::getCollectionName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Cdf\BiCoreBundle\Controller;
4
5
use Cdf\BiCoreBundle\Service\Permessi\PermessiManager;
6
7
use function count;
8
9
use ReflectionClass;
10
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
11
use Twig\Environment;
12
use Doctrine\ORM\EntityManagerInterface;
13
use Symfony\Component\String\Inflector\EnglishInflector;
14
use Cdf\BiCoreBundle\Utils\Api\ApiUtils;
15
use Cdf\BiCoreBundle\Utils\String\StringUtils;
16
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
17
18
19
use Cdf\BiCoreBundle\Service\Api\ApiManager;
20
use Cdf\BiCoreBundle\Service\Api\Oauth2TokenService;
21
22
/**
23
 * @SuppressWarnings(PHPMD.TooManyFields)
24
 * @codeCoverageIgnore
25
 */
26
class FiApiController extends AbstractController
27
{
28
    use FiApiCoreControllerTrait;
29
    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...
30
    use FiCoreTabellaControllerTrait;
31
32
    protected string $bundle;
33
    protected Environment $template;
34
    protected string $controller;
35
    protected PermessiManager $permessi;
36
    //API rest attributes
37
    protected string $project;
38
    protected string $model;
39
    protected string $collection;
40
    protected string $modelClass;
41
    protected string $formClass;
42
    protected string $controllerItem;
43
    protected string $apiController;
44
    /** @var array<mixed> */
45
    protected array $options;
46
    /** @var array<mixed> */
47
    protected array $enumOptions;
48
    /** @var array<mixed> */
49
    protected array $inflectorExceptions;
50
    protected ParameterBagInterface $params;
51
    protected EntityManagerInterface $em;
52
    protected ApiManager $apiManager;
53
    protected string $apiProjectCollection;
54
55
56
57
    public function __construct(PermessiManager $permessi, Environment $template, ParameterBagInterface $params, EntityManagerInterface $em)
58
    {
59
        $matches = [];
60
        $controllo = new ReflectionClass(get_class($this));
61
62
        preg_match('/(.*)\\\(.*)\\\Controller\\\(.*)Controller/', $controllo->name, $matches);
63
        if (0 == count($matches)) {
64
            preg_match('/(.*)(.*)\\\Controller\\\(.*)Controller/', $controllo->name, $matches);
65
        }
66
        $this->project = $this->getProject();
67
        $this->params = $params;
68
69
        $this->bundle = ($matches[count($matches) - 2] ? $matches[count($matches) - 2] : $matches[count($matches) - 3]);
70
        $this->controller = $matches[count($matches) - 1];
71
        $this->permessi = $permessi;
72
        $this->template = $template;
73
        $this->em = $em;
74
75
        $this->model = $this->controller; //they matches
76
        $this->collection = $this->pluralize($this->model);
77
        $apiUtil = new ApiUtils();
78
        $this->modelClass = $apiUtil->getModelClass($this->project, $this->model);
79
        $this->formClass = $apiUtil->getFormClass($this->model);
80
        $this->controllerItem = $apiUtil->getModelControllerClass($this->project, $this->model);
81
        $this->apiController = $apiUtil->getApiControllerClass($this->project, $this->collection);
82
        $this->options = array();
83
        $this->enumOptions = array();
84
        $this->inflectorExceptions = array();
85
86
        //*** instantiate ApiManager ***
87
        $this->apiManager = new ApiManager(
88
            $this->params->get("bi_core.oauth2_enabled"),
89
            new Oauth2TokenService(
90
                $this->params->get("bi_core.oauth2_endpoint"),
91
                $this->params->get("bi_core.oauth2_clientkey")
92
            )
93
        );
94
95
        $this->apiManager->setProjectName($this->project);
96
        $this->apiProjectCollection = strtolower($this->collection);
97
98
        $projectRoot = $apiUtil->getProjectRoot($this->project);
99
100
        $projectConfiguration = $projectRoot."Configuration";
101
        $projectHeaderSelector = $projectRoot."HeaderSelector";
102
103
        $config = $projectConfiguration::getDefaultConfiguration();
104
        $headerSelector = new $projectHeaderSelector($config);
105
106
        $this->apiManager->setApiClientConfigs($headerSelector, $config);
107
108
        $this->apiManager->setApiController($this->apiProjectCollection);
109
110
        //it generates options one time for all
111
        $this->loadInflectorExceptions();
112
        $this->generateEnumAndOptions();
113
    }
114
115
    protected function loadInflectorExceptions() : void
116
    {
117
        $vars = $this->params->get("bi_core.api_inflector_exceptions");
118
        if (($vars)) {
119
            $values = json_decode($vars, true);
120
            $this->inflectorExceptions = $values;
121
        }
122
    }
123
124
    protected function getCollectionName() : string
125
    {
126
        return $this->apiProjectCollection;
127
    }
128
129
    /**
130
     * Copy this method into your controller in case of exceptions
131
     *
132
     * @param string $singleForm
133
     * @return array<mixed>|string
134
     */
135
    protected function pluralizeForm(string $singleForm)
136
    {
137
        if (isset($this->inflectorExceptions[$singleForm])) {
138
            return $this->inflectorExceptions[$singleForm];
139
        }
140
        $inflector = new EnglishInflector();
141
        return $inflector->pluralize($singleForm);
142
    }
143
144
    /**
145
     * Pluralize a single form giving as response the correct plurale form matching with existent objects
146
     */
147
    protected function pluralize(string $singleForm) : string
148
    {
149
        $outcome = '';
150
        $results = $this->pluralizeForm($singleForm);
151
152
        if (is_array($results)) {
153
            $apiUtil = new ApiUtils();
154
            foreach ($results as $result) {
155
                //get name of api controller
156
                $apiClassPath = $apiUtil->getApiControllerClass($this->project, $result);
157
                if (class_exists($apiClassPath)) {
158
                    $outcome = $result;
159
                    break;
160
                }
161
            }
162
        } else {
163
            $outcome = $results;
164
        }
165
        return $outcome;
166
    }
167
168
    /**
169
     * Generate option choices for edit form
170
     */
171
    protected function generateEnumAndOptions() : void
172
    {
173
        $itemController = new $this->controllerItem();
174
        $fieldMappings = $itemController::swaggerTypes();
175
176
        //dump($fieldMappings);
177
178
        foreach (array_keys($fieldMappings) as $fieldName) {
179
            //is it a foreign key field?
180
            if (\str_contains($fieldName, '_id')) {
181
                $tools = $this->getApiTools($fieldName, '_id');
182
                $apiBook = $tools['book'];
183
                $apiProjectCollection = $apiBook->getApiCollection();
184
                $this->apiManager->setApiController($apiProjectCollection);
185
                $results = $this->apiManager->getAllToString($apiProjectCollection, null, null, null, "");
186
187
                $arrayContainer = array();
188
                foreach ($results as $myItem) {
189
                    //transform this items for options
190
                    $element = array("id" => $myItem->getCode(), "descrizione" => $myItem->getText(), "valore" => $myItem->getText());
191
                    array_push($arrayContainer, $element);
192
                }
193
                $this->options[$tools['entity']] = $arrayContainer;
194
            } elseif (\str_contains($fieldName, '_enum')) {
195
                //dump("in fieldname ".$fieldName );
196
                $tools = $this->getApiTools($fieldName, '_enum');
197
                $apiBook = $tools['book'];
198
                $apiProjectCollection = $apiBook->getApiCollection();
199
                $this->apiManager->setApiController($apiProjectCollection);
200
                $results = $this->apiManager->getAllToString($apiProjectCollection, null, null, null, "");
201
202
                $decodeMap = array();
203
                $arrayContainer = array();
204
                foreach ($results as $result) {
205
                    $decodeMap[$result['code']] = $result['text'];
206
                    $element = array("id" => $result['code'], "descrizione" => $result['text'], "valore" => $result['text']);
207
                    array_push($arrayContainer, $element);
208
                }
209
                $this->options[$tools['entity']] = $arrayContainer;
210
211
                $arrayItem = array('nometabella' => $this->controller, 'nomecampo' => "$this->controller.$fieldName", 'etichetta' => "$fieldName",
212
                    'escluso' => false,
213
                    'decodifiche' => $decodeMap);
214
215
                array_push($this->enumOptions, $arrayItem);
216
            }
217
        }
218
    }
219
220
    /**
221
     * It checks if there are some enum collections having a match with defined column fields
222
     * and append attribute "decofiche" to them.
223
     * THIS HAVE TO BE INVOKED BY SPECIFIC ENTITY CONTROLLER.
224
     */
225
    /**
226
     * It returns an array with 'controller' with the apiController
227
     * and 'book' the apiBook
228
     * and 'entity' the given fieldName less the suffix
229
230
     * @param array<mixed> $modellocolonne
231
     */
232
    protected function mergeColumnsAndEnumOptions(array &$modellocolonne) : void
233
    {
234
        foreach ($this->enumOptions as $enumOption) {
235
            if (isset($modellocolonne[$enumOption['nomecampo']])) {
236
                $modellocolonne[$enumOption['nomecampo']]['decodifiche'] = $enumOption['decodifiche'];
237
            }
238
        }
239
    }
240
241
    /**
242
     * It returns an array with 'controller' with the apiController
243
     * and 'book' the apiBook
244
     * and 'entity' the given fieldName less the suffix
245
246
     * @param string $fieldName
247
     * @param string $suffixString
248
     * @return array<mixed>
249
     */
250
    protected function getApiTools($fieldName, $suffixString): array
251
    {
252
        $entityName = substr($fieldName, 0, strpos($fieldName, $suffixString));
253
254
        $parametri = array('str' => $entityName, 'primamaiuscola' => true);
255
        $outcome = StringUtils::toCamelCase($parametri);
256
        $outcome = $this->pluralize($outcome);
257
258
        $apiUtil = new ApiUtils();
259
        $apiControllerClass = $apiUtil->getApiControllerClass($this->project, $outcome);
260
        $apiController = new $apiControllerClass();
261
262
        //$apiBook = new ApiUtils($entityName);
263
        $apiBook = new ApiUtils($outcome);
264
265
        $results = [
266
            'controller' => $apiController,
267
            'book' => $apiBook,
268
            'entity' => $entityName,
269
        ];
270
        return $results;
271
    }
272
273
    protected function getBundle() : string
274
    {
275
        return $this->bundle;
276
    }
277
278
    protected function getController() : string
279
    {
280
        return $this->controller;
281
    }
282
283
    protected function getPermessi() : PermessiManager
284
    {
285
        return $this->permessi;
286
    }
287
288
    protected function getTemplate() : Environment
289
    {
290
        return $this->template;
291
    }
292
293
    public function getProject() : string
294
    {
295
        $annotations = array();
296
        $r = new ReflectionClass(get_class($this));
297
        $doc = $r->getDocComment();
298
        preg_match_all('#@var\(biproject="(.*?)"\)[\r\n]+#s', $doc, $annotations);
299
        return $annotations[1][0];
300
    }
301
}
302