Test Failed
Push — master ( 1b7368...050678 )
by Fran
25:16 queued 22:49
created

GeneratorService::generateApiFiles()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 16
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 13
c 1
b 0
f 0
nc 6
nop 6
dl 0
loc 16
ccs 14
cts 14
cp 1
crap 8
rs 8.4444
1
<?php
2
namespace PSFS\services;
3
4
use PSFS\base\Logger;
5
use PSFS\base\types\helpers\GeneratorHelper;
6
use PSFS\base\types\SimpleService;
7
use PSFS\base\types\traits\Generator\PropelHelperTrait;
8
use PSFS\base\types\traits\Generator\StructureTrait;
9
10
/**
11
 * Class GeneratorService
12
 * @package PSFS\services
13
 */
14
class GeneratorService extends SimpleService
15
{
16
    use PropelHelperTrait;
17
    use StructureTrait;
18
    /**
19
     * @Injectable
20
     * @var \PSFS\base\config\Config Servicio de configuración
21
     */
22
    protected $config;
23
    /**
24
     * @Injectable
25
     * @var \PSFS\base\Security Servicio de autenticación
26
     */
27
    protected $security;
28
29
    /**
30
     * Servicio que genera la estructura de un módulo o lo actualiza en caso de ser necesario
31
     * @param string $module
32
     * @param boolean $force
33
     * @param string $type
34
     * @param string $apiClass
35
     * @return mixed
36
     * @throws \PSFS\base\exception\GeneratorException
37
     * @throws \ReflectionException
38
     */
39 1
    public function createStructureModule($module, $force = false, $type = "", $apiClass = "")
40
    {
41 1
        $modPath = CORE_DIR . DIRECTORY_SEPARATOR;
42 1
        $module = ucfirst($module);
43 1
        $this->createModulePath($module, $modPath);
44 1
        $this->createModulePathTree($module, $modPath);
0 ignored issues
show
Bug introduced by
$modPath of type string is incompatible with the type boolean expected by parameter $modPath of PSFS\services\GeneratorS...:createModulePathTree(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

44
        $this->createModulePathTree($module, /** @scrutinizer ignore-type */ $modPath);
Loading history...
45 1
        $this->createModuleBaseFiles($module, $modPath, $force, $type);
46 1
        $this->createModuleModels($module, $modPath);
47 1
        $this->generateBaseApiTemplate($module, $modPath, $force, $apiClass);
48
        //Redireccionamos al home definido
49 1
        Logger::log("Módulo generado correctamente");
50
    }
51
52
    /**
53
     * Servicio que genera las plantillas básicas de ficheros del módulo
54
     * @param string $module
55
     * @param string $modPath
56
     * @param boolean $force
57
     * @param string $controllerType
58
     */
59 1
    private function createModuleBaseFiles($module, $modPath, $force = false, $controllerType = '')
60
    {
61 1
        $modulePath = $modPath . $module;
62 1
        $this->generateControllerTemplate($module, $modulePath, $force, $controllerType);
63 1
        $this->generateServiceTemplate($module, $modulePath, $force);
64 1
        $this->genereateAutoloaderTemplate($module, $modulePath, $force);
65 1
        $this->generateSchemaTemplate($module, $modulePath, $force);
66 1
        $this->generateConfigurationTemplates($module, $modulePath, $force);
67 1
        $this->generateIndexTemplate($module, $modulePath, $force);
68 1
        $this->generatePublicTemplates($modulePath, $force);
69
    }
70
71
    /**
72
     * @param string $module
73
     * @param string $modulePath
74
     * @param bool $force
75
     * @return void
76
     */
77 1
    public function generateConfigurationTemplates(string $module, string $modulePath, bool $force = false): void {
78 1
        $this->generatePropertiesTemplate($module, $modulePath, $force);
79 1
        $this->generateConfigTemplate($modulePath, $force);
80
    }
81
82
    /**
83
     * @param string $module
84
     * @param string $modPath
85
     * @param boolean $force
86
     * @param string $controllerType
87
     * @return boolean
88
     */
89 1
    private function generateControllerTemplate($module, $modPath, $force = false, $controllerType = "")
90
    {
91
        //Generamos el controlador base
92 1
        Logger::log("Generamos el controlador BASE");
93 1
        $class = preg_replace('/(\\\|\/)/', '', $module);
94 1
        $controllerBody = $this->tpl->dump("generator/controller.template.twig", array(
95 1
            "module" => $module,
96 1
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
97 1
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
98 1
            "class" => $class,
99 1
            "controllerType" => $class . "Base",
100 1
            "is_base" => false
101 1
        ));
102 1
        $controller = $this->writeTemplateToFile($controllerBody, $modPath . DIRECTORY_SEPARATOR . "Controller" .
103 1
            DIRECTORY_SEPARATOR . "{$class}Controller.php", $force);
104
105 1
        $controllerBody = $this->tpl->dump("generator/controller.template.twig", array(
106 1
            "module" => $module,
107 1
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
108 1
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
109 1
            "class" => $class . "Base",
110 1
            "service" => $class,
111 1
            "controllerType" => $controllerType,
112 1
            "is_base" => true,
113 1
            "domain" => $class,
114 1
        ));
115 1
        $controllerBase = $this->writeTemplateToFile($controllerBody, $modPath . DIRECTORY_SEPARATOR . "Controller" .
116 1
            DIRECTORY_SEPARATOR . "base" . DIRECTORY_SEPARATOR . "{$class}BaseController.php", true);
117
118 1
        $filename = $modPath . DIRECTORY_SEPARATOR . "Test" . DIRECTORY_SEPARATOR . "{$class}Test.php";
119 1
        $test = true;
120 1
        if(!file_exists($filename)) {
121 1
            $testTemplate = $this->tpl->dump("generator/testCase.template.twig", array(
122 1
                "module" => $module,
123 1
                "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
124 1
                "class" => $class,
125 1
            ));
126 1
            $test = $this->writeTemplateToFile($testTemplate, $filename, true);
127
        }
128 1
        return ($controller && $controllerBase && $test);
129
    }
130
131
    /**
132
     * Servicio que ejecuta Propel y genera el modelo de datos
133
     * @param string $module
134
     * @param string $path
135
     * @throws \PSFS\base\exception\GeneratorException
136
     */
137 1
    private function createModuleModels($module, $path)
138
    {
139 1
        $modulePath = $path . $module;
140 1
        $modulePath = str_replace(CORE_DIR . DIRECTORY_SEPARATOR, '', $modulePath);
141
142 1
        $configGenerator = $this->getConfigGenerator($modulePath);
143
144 1
        $this->buildModels($configGenerator);
145 1
        $this->buildSql($configGenerator);
146
147 1
        $configTemplate = $this->tpl->dump("generator/config.propel.template.twig", array(
148 1
            "module" => $module,
149 1
        ));
150 1
        $this->writeTemplateToFile($configTemplate, CORE_DIR . DIRECTORY_SEPARATOR . $modulePath . DIRECTORY_SEPARATOR . "Config" .
151 1
            DIRECTORY_SEPARATOR . "config.php", true);
152 1
        Logger::log("Generado config genérico para propel");
153
    }
154
155
    /**
156
     * @param string $module
157
     * @param string $modPath
158
     * @param boolean $force
159
     * @param string $apiClass
160
     * @return boolean
161
     * @throws \ReflectionException
162
     */
163 1
    private function generateBaseApiTemplate($module, $modPath, $force = false, $apiClass = "")
164
    {
165 1
        $created = true;
166 1
        $modelPath = $modPath . $module . DIRECTORY_SEPARATOR . 'Models';
167 1
        $apiPath = $modPath . $module . DIRECTORY_SEPARATOR . 'Api';
168 1
        if (file_exists($modelPath)) {
169 1
            $dir = dir($modelPath);
170 1
            $this->generateApiFiles($module, $force, $apiClass, $dir, $apiPath);
171
        }
172 1
        return $created;
173
    }
174
175
    /**
176
     * @param string $modPath
177
     * @param boolean $force
178
     * @return boolean
179
     */
180 1
    private function generateConfigTemplate($modPath, $force = false)
181
    {
182
        //Generamos el fichero de configuración
183 1
        Logger::log("Generamos fichero vacío de configuración");
184 1
        return $this->writeTemplateToFile("<?php\n\t",
185 1
            $modPath . DIRECTORY_SEPARATOR . "Config" . DIRECTORY_SEPARATOR . "config.php",
186 1
            $force);
187
    }
188
189
    /**
190
     * @param string $module
191
     * @param string $modPath
192
     * @param boolean $force
193
     * @return boolean
194
     */
195 1
    private function generateSchemaTemplate($module, $modPath, $force = false)
196
    {
197
        //Generamos el autoloader del módulo
198 1
        Logger::log("Generamos el schema");
199 1
        $schema = $this->tpl->dump("generator/schema.propel.twig", array(
200 1
            "module" => $module,
201 1
            "namespace" => preg_replace('/(\\\|\/)/', '', $module),
202 1
            "prefix" => preg_replace('/(\\\|\/)/', '', $module),
203 1
            "db" => $this->config->get("db_name"),
204 1
        ));
205 1
        return $this->writeTemplateToFile($schema,
206 1
            $modPath . DIRECTORY_SEPARATOR . "Config" . DIRECTORY_SEPARATOR . "schema.xml",
207 1
            $force);
208
    }
209
210
    /**
211
     * @param string $module
212
     * @param string $modPath
213
     * @param boolean $force
214
     * @return boolean
215
     */
216 1
    private function generatePropertiesTemplate($module, $modPath, $force = false)
217
    {
218 1
        Logger::log("Generamos la configuración de Propel");
219 1
        $buildProperties = $this->tpl->dump("generator/build.properties.twig", array(
220 1
            "module" => $module,
221 1
            "namespace" => preg_replace('/(\\\|\/)/', '', $module),
222 1
        ));
223 1
        return $this->writeTemplateToFile($buildProperties,
224 1
            $modPath . DIRECTORY_SEPARATOR . "Config" . DIRECTORY_SEPARATOR . "propel.php",
225 1
            $force);
226
    }
227
228
    /**
229
     * @param string $module
230
     * @param string $modPath
231
     * @param boolean $force
232
     * @return boolean
233
     */
234 1
    private function generateIndexTemplate($module, $modPath, $force = false)
235
    {
236
        //Generamos la plantilla de index
237 1
        Logger::log("Generamos una plantilla base por defecto");
238 1
        $index = $this->tpl->dump("generator/index.template.twig", array(
239 1
            "module" => $module,
240 1
        ));
241 1
        return $this->writeTemplateToFile($index,
242 1
            $modPath . DIRECTORY_SEPARATOR . "Templates" . DIRECTORY_SEPARATOR . "index.html.twig",
243 1
            $force);
244
    }
245
246
    /**
247
     * Create ApiBase
248
     * @param string $module
249
     * @param string $modPath
250
     * @param string $api
251
     * @param string $apiClass
252
     * @param string $package
253
     *
254
     * @return bool
255
     */
256 1
    private function createApiBaseFile($module, $modPath, $api, $apiClass = '', $package = null)
257
    {
258 1
        $class = preg_replace('/(\\\|\/)/', '', $module);
259 1
        $customClass = GeneratorHelper::extractClassFromNamespace($apiClass);
260 1
        $controller = $this->tpl->dump("generator/api.base.template.twig", array(
261 1
            "module" => $module,
262 1
            "api" => $api,
263 1
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
264 1
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
265 1
            "class" => $class,
266 1
            'customClass' => $customClass,
267 1
            'customNamespace' => $apiClass,
268 1
            'package' => $package,
269 1
        ));
270
271 1
        return $this->writeTemplateToFile($controller,
272 1
            $modPath . DIRECTORY_SEPARATOR . 'base' . DIRECTORY_SEPARATOR . "{$api}BaseApi.php", true);
273
    }
274
275
    /**
276
     * Create Api
277
     * @param string $module
278
     * @param string $modPath
279
     * @param bool $force
280
     * @param string $api
281
     * @param string $package
282
     *
283
     * @return bool
284
     */
285 1
    private function createApi($module, $modPath, $force, $api, $package = null)
286
    {
287 1
        $class = preg_replace('/(\\\|\/)/', '', $module);
288 1
        $controller = $this->tpl->dump("generator/api.template.twig", array(
289 1
            "module" => $module,
290 1
            "api" => $api,
291 1
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
292 1
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
293 1
            "class" => $class,
294 1
            "package" => $package,
295 1
        ));
296
297 1
        return $this->writeTemplateToFile($controller, $modPath . DIRECTORY_SEPARATOR . "{$api}.php", $force);
298
    }
299
300
    /**
301
     * @param $module
302
     * @param $force
303
     * @param $apiClass
304
     * @param \Directory|null $dir
305
     * @param string $apiPath
306
     * @param string $package
307
     * @throws \ReflectionException
308
     */
309 1
    private function generateApiFiles($module, $force, $apiClass, \Directory $dir, string $apiPath, $package = null)
310
    {
311 1
        $base = $dir->path;
312 1
        while ($file = $dir->read()) {
313 1
            if (!in_array(strtolower($file), ['.', '..', 'base', 'map'])) {
314 1
                if (is_dir($base . DIRECTORY_SEPARATOR . $file)) {
315 1
                    $this->generateApiFiles($module, $force, $apiClass, dir($base . DIRECTORY_SEPARATOR . $file), $apiPath . DIRECTORY_SEPARATOR . $file, $file);
316 1
                } else if (!preg_match('/Query\.php$/i', $file)
317 1
                    && !preg_match('/I18n\.php$/i', $file)
318 1
                    && preg_match('/\.php$/i', $file)
319
                ) {
320 1
                    $filename = str_replace(".php", "", $file);
321 1
                    $this->log->addLog("Generamos Api BASES para {$filename}");
322 1
                    if($this->checkIfIsModel($module, $filename, $package)) {
323 1
                        $this->createApiBaseFile($module, $apiPath, $filename, $apiClass, $package);
324 1
                        $this->createApi($module, $apiPath, $force, $filename, $package);
325
                    }
326
                }
327
            }
328
        }
329
    }
330
331
    /**
332
     * @param string $module
333
     * @param string $package
334
     * @param string $filename
335
     * @return bool
336
     * @throws \ReflectionException
337
     */
338 1
    private function checkIfIsModel($module, $filename, $package = null)
339
    {
340 1
        $parts = [$module, 'Models'];
341 1
        if (strlen($package)) {
0 ignored issues
show
Bug introduced by
It seems like $package can also be of type null; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

341
        if (strlen(/** @scrutinizer ignore-type */ $package)) {
Loading history...
342 1
            $parts[] = $package;
343
        }
344 1
        $parts[] = $filename;
345 1
        $namespace = '\\' . implode('\\', $parts);
346 1
        $reflectorClass = new \ReflectionClass($namespace);
347 1
        $isModel = $reflectorClass->isInstantiable();
348 1
        return $isModel;
349
    }
350
}
351