Completed
Pull Request — master (#3)
by Pavlo
09:53
created

Generator::entityNavigations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4286
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: VITALYIEGOROV
5
 * Date: 09.12.15
6
 * Time: 14:34
7
 */
8
namespace samsoncms\api;
9
10
use samson\activerecord\dbMySQLConnector;
11
use samson\cms\CMSMaterial;
12
use samsoncms\api\query\Generic;
13
use samsonframework\orm\DatabaseInterface;
14
15
/**
16
 * Entity classes generator.
17
 * @package samsoncms\api
18
 */
19
class Generator
20
{
21
    /** @var DatabaseInterface */
22
    protected $database;
23
24
    /** @var \samsonphp\generator\Generator */
25
    protected $generator;
26
27
    /**
28
     * Transliterate string to english.
29
     *
30
     * @param string $string Source string
31
     * @return string Transliterated string
32
     */
33
    protected function transliterated($string)
34
    {
35
        return str_replace(
36
            ' ',
37
            '',
38
            ucwords(iconv("UTF-8", "UTF-8//IGNORE", strtr($string, array(
39
                            "'" => "",
40
                            "`" => "",
41
                            "-" => " ",
42
                            "_" => " ",
43
                            "а" => "a", "А" => "a",
44
                            "б" => "b", "Б" => "b",
45
                            "в" => "v", "В" => "v",
46
                            "г" => "g", "Г" => "g",
47
                            "д" => "d", "Д" => "d",
48
                            "е" => "e", "Е" => "e",
49
                            "ж" => "zh", "Ж" => "zh",
50
                            "з" => "z", "З" => "z",
51
                            "и" => "i", "И" => "i",
52
                            "й" => "y", "Й" => "y",
53
                            "к" => "k", "К" => "k",
54
                            "л" => "l", "Л" => "l",
55
                            "м" => "m", "М" => "m",
56
                            "н" => "n", "Н" => "n",
57
                            "о" => "o", "О" => "o",
58
                            "п" => "p", "П" => "p",
59
                            "р" => "r", "Р" => "r",
60
                            "с" => "s", "С" => "s",
61
                            "т" => "t", "Т" => "t",
62
                            "у" => "u", "У" => "u",
63
                            "ф" => "f", "Ф" => "f",
64
                            "х" => "h", "Х" => "h",
65
                            "ц" => "c", "Ц" => "c",
66
                            "ч" => "ch", "Ч" => "ch",
67
                            "ш" => "sh", "Ш" => "sh",
68
                            "щ" => "sch", "Щ" => "sch",
69
                            "ъ" => "", "Ъ" => "",
70
                            "ы" => "y", "Ы" => "y",
71
                            "ь" => "", "Ь" => "",
72
                            "э" => "e", "Э" => "e",
73
                            "ю" => "yu", "Ю" => "yu",
74
                            "я" => "ya", "Я" => "ya",
75
                            "і" => "i", "І" => "i",
76
                            "ї" => "yi", "Ї" => "yi",
77
                            "є" => "e", "Є" => "e"
78
                        )
79
                    )
80
                )
81
            )
82
        );
83
    }
84
85
    /**
86
     * Get class constant name by its value.
87
     *
88
     * @param string $value Constant value
89
     * @param string $className Class name
90
     * @return string Full constant name
91
     */
92
    protected function constantNameByValue($value, $className = Field::ENTITY)
93
    {
94
        // Get array where class constants are values and their values are keys
95
        $nameByValue = array_flip((new \ReflectionClass($className))->getConstants());
96
97
        // Try to find constant by its value
98
        if (isset($nameByValue[$value])) {
99
            // Return constant name
100
            return $nameByValue[$value];
101
        }
102
    }
103
104
    /**
105
     * Get correct entity name.
106
     *
107
     * @param string $navigationName Original navigation entity name
108
     * @return string Correct PHP-supported entity name
109
     */
110
    protected function entityName($navigationName)
111
    {
112
        return ucfirst($this->transliterated($navigationName));
113
    }
114
115
    /**
116
     * Get correct full entity name with name space.
117
     *
118
     * @param string $navigationName Original navigation entity name
119
     * @param string $namespace Namespace
120
     * @return string Correct PHP-supported entity name
121
     */
122
    protected function fullEntityName($navigationName, $namespace = __NAMESPACE__)
123
    {
124
        return str_replace('\\', '\\\\' , '\\'.$namespace.'\\'.$this->entityName($navigationName));
0 ignored issues
show
Coding Style introduced by
Space found before comma in function call
Loading history...
125
    }
126
127
    /**
128
     * Get correct field name.
129
     *
130
     * @param string $fieldName Original field name
131
     * @return string Correct PHP-supported field name
132
     */
133
    protected function fieldName($fieldName)
134
    {
135
        return $fieldName = lcfirst($this->transliterated($fieldName));
0 ignored issues
show
Unused Code introduced by
$fieldName 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...
136
    }
137
138
    /**
139
     * Get additional field type in form of Field constant name
140
     * by database additional field type identifier.
141
     *
142
     * @param integer $fieldType Additional field type identifier
143
     * @return string Additional field type constant
144
     */
145
    protected function additionalFieldType($fieldType)
146
    {
147
        return 'Field::'.$this->constantNameByValue($fieldType);
148
    }
149
150
    /**
151
     * Generate Query::where() analog for specific field.
152
     *
153
     * @param string $fieldName Field name
154
     * @param string $fieldId Field primary identifier
155
     * @param string $fieldType Field PHP type
156
     * @return string Generated PHP method code
157
     */
158
    protected function generateFieldConditionMethod($fieldName, $fieldId, $fieldType)
159
    {
160
        $code = "\n\t" . '/**';
161
        $code .= "\n\t" . ' * Add '.$fieldName.'(#' . $fieldId . ') field query condition.';
162
        $code .= "\n\t" . ' * @param '.Field::phpType($fieldType).' $value Field value';
163
        $code .= "\n\t" . ' * @return self Chaining';
164
        $code .= "\n\t" . ' * @see Generic::where()';
165
        $code .= "\n\t" . ' */';
166
        $code .= "\n\t" . 'public function ' . $fieldName . '($value)';
167
        $code .= "\n\t" . "{";
168
        $code .= "\n\t\t" . 'return $this->where("'.$fieldName.'", $value);';
169
170
        return $code . "\n\t" . "}"."\n";
171
    }
172
173
    /**
174
     * Create entity PHP class code.
175
     *
176
     * @param string $navigationName Original entity name
177
     * @param string $entityName PHP entity name
178
     * @param array $navigationFields Collection of entity additional fields
179
     * @return string Generated entity query PHP class code
180
     */
181
    protected function createEntityClass($navigationName, $entityName, $navigationFields)
182
    {
183
        $this->generator->multicomment(array('"'.$navigationName.'" entity class'));
184
        $this->generator->defclass($entityName, 'Entity');
185
186
        $this->generator->comment('Entity full class name');
187
        $this->generator->defvar('const ENTITY', $this->fullEntityName($entityName));
188
189
        $this->generator->comment('@var string Not transliterated entity name');
190
        $this->generator->defvar('protected static $viewName', $navigationName);
191
192
        $select = \samson\activerecord\material::$_sql_select;
193
        $attributes = \samson\activerecord\material::$_attributes;
194
        $map = \samson\activerecord\material::$_map;
195
        $from = \samson\activerecord\material::$_sql_from;
196
        $group = \samson\activerecord\material::$_own_group;
197
198
        $select['this'] = ' STRAIGHT_JOIN ' . $select['this'];
199
        $from['this'] .= "\n" . 'LEFT JOIN ' . dbMySQLConnector::$prefix . 'materialfield as _mf on ' . dbMySQLConnector::$prefix . 'material.MaterialID = _mf.MaterialID';
200
        $group[] = dbMySQLConnector::$prefix . 'material.MaterialID';
201
202
        foreach ($navigationFields as $fieldID => $fieldRow) {
203
            $fieldName = $this->fieldName($fieldRow['Name']);
204
205
            $attributes[$fieldName] = $fieldName;
206
            $map[$fieldName] = dbMySQLConnector::$prefix . 'material.' . $fieldName;
207
208
            $equal = '((_mf.FieldID = ' . $fieldID . ')&&(_mf.locale = \"' . ($fieldRow['local'] ? locale() : "") . '\"))';
209
210
            // Save additional field
211
            $select['this'] .= "\n\t\t".',MAX(IF(' . $equal . ', _mf.`' . Field::valueColumn($fieldRow['Type']) . '`, NULL)) as `' . $fieldName . '`';
212
213
            $this->generator->comment(Field::phpType($fieldRow['Type']) . ' '.$fieldRow['Description'].' Field #' . $fieldID . ' variable name');
214
            $this->generator->defvar('const F_' . strtoupper($fieldName), $fieldName);
215
            $this->generator->comment(Field::phpType($fieldRow['Type']) . ' '.$fieldRow['Description'].' Field #' . $fieldID);
216
            $this->generator->defvar('public $'.$fieldName.';');
217
        }
218
219
        $this->generator->defvar('public static $_sql_select', $select);
0 ignored issues
show
Documentation introduced by
$select is of type array<string,string,{"this":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
220
        $this->generator->defvar('public static $_attributes', $attributes);
0 ignored issues
show
Documentation introduced by
$attributes is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
221
        $this->generator->defvar('public static $_map', $map);
0 ignored issues
show
Documentation introduced by
$map is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
222
        $this->generator->defvar('public static $_sql_from', $from);
0 ignored issues
show
Documentation introduced by
$from is of type array<string,string,{"this":"string"}>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
223
        $this->generator->defvar('public static $_own_group', $group);
0 ignored issues
show
Documentation introduced by
$group is of type array<integer,string>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
224
225
        $this->generator->endclass();
226
227
        return $this->generator->flush();
228
    }
229
230
    /**
231
     * Generate FieldsTable::values() analog for specific field.
232
     *
233
     * @param string $fieldName Field name
234
     * @param string $fieldId Field primary identifier
235
     * @param string $fieldType Field PHP type
236
     * @return string Generated PHP method code
237
     */
238
    protected function generateTableFieldMethod($fieldName, $fieldId, $fieldType)
239
    {
240
        $code = "\n\t" . '/**';
241
        $code .= "\n\t" . ' * Get table column '.$fieldName.'(#' . $fieldId . ') values.';
242
        $code .= "\n\t" . ' * @return array Collection('.Field::phpType($fieldType).') of table column values';
243
        $code .= "\n\t" . ' */';
244
        $code .= "\n\t" . 'public function ' . $fieldName . '()';
245
        $code .= "\n\t" . "{";
246
        $code .= "\n\t\t" . 'return $this->values('.$fieldId.');';
247
248
        return $code . "\n\t" . "}"."\n";
249
    }
250
251
    /**
252
     * Create fields table PHP class code.
253
     *
254
     * @param integer $navigationID Entity navigation identifier
255
     * @param string $navigationName Original entity name
256
     * @param string $entityName PHP entity name
257
     * @param array $navigationFields Collection of entity additional fields
258
     * @return string Generated entity query PHP class code
259
     */
260
    protected function createTableClass($navigationID, $navigationName, $entityName, $navigationFields)
261
    {
262
        $class = "\n";
263
        $class .= "\n" . '/**';
264
        $class .= "\n" . ' * Class for getting "'.$navigationName.'" fields table';
265
        $class .= "\n" . ' */';
266
        $class .= "\n" . 'class ' . $entityName . ' extends FieldsTable';
267
        $class .= "\n" . '{';
268
269
        // Iterate additional fields
270
        $constants = '';
271
        $variables = '';
272
        $methods = '';
273
        foreach ($navigationFields as $fieldID => $fieldRow) {
274
            $fieldName = $this->fieldName($fieldRow['Name']);
275
276
            $methods .= $this->generateTableFieldMethod(
277
                $fieldName,
278
                $fieldRow[Field::F_PRIMARY],
279
                $fieldRow[Field::F_TYPE]
280
            );
281
            $constants .= "\n\t" . '/** ' . Field::phpType($fieldRow['Type']) . ' '.$fieldRow['Description'].' Field #' . $fieldID . ' variable name */';
282
            $constants .= "\n\t" . 'const F_' . strtoupper($fieldName) . ' = "'.$fieldName.'";';
283
284
            $variables .= "\n\t" . '/** @var array Collection of '.$fieldRow['Description'].' Field #' . $fieldID . ' values */';
285
            $variables .= "\n\t" . 'protected $' . $fieldName . ';';
286
        }
287
288
        $class .= $constants;
289
        $class .= "\n\t";
290
        $class .= "\n\t" . '/** @var array Collection of navigation identifiers */';
291
        $class .= "\n\t" . 'protected static $navigationIDs = array(' . $navigationID . ');';
292
        $class .= "\n\t";
293
        $class .= $variables;
294
        $class .= "\n\t";
295
        $class .= $methods;
296
        $class .= "\n\t".'/**';
297
        $class .= "\n\t".' * @param QueryInterface $query Database query instance';
298
        $class .= "\n\t".' * @param integer $entityID Entity identifier to whom this table belongs';
299
        $class .= "\n\t".' * @param string $locale Localization identifier';
300
        $class .= "\n\t".' */';
301
        $class .= "\n\t".'public function __construct(QueryInterface $query, $entityID, $locale = "")';
302
        $class .= "\n\t".'{';
303
        $class .= "\n\t\t".'parent::__construct($query, static::$navigationIDs, $entityID, $locale);';
304
        $class .= "\n\t".'}';
305
        $class .= "\n" . '}';
306
307
        return $class;
308
    }
309
310
    /**
311
     * Create entity query PHP class code.
312
     *
313
     * @param integer $navigationID Entity navigation identifier
314
     * @param string $navigationName Original entity name
315
     * @param string $entityName PHP entity name
316
     * @param array $navigationFields Collection of entity additional fields
317
     * @return string Generated entity query PHP class code
318
     */
319
    protected function createQueryClass($navigationID, $navigationName, $entityName, $navigationFields)
320
    {
321
        $class = "\n";
322
        $class .= "\n" . '/**';
323
        $class .= "\n" . ' * Class for getting "'.$navigationName.'" instances from database';
324
        $class .= "\n" . ' * @method '.$this->entityName($navigationName).'[] find() Get entities collection';
325
        $class .= "\n" . ' * @method '.$this->entityName($navigationName).' first() Get entity';
326
        $class .= "\n" . ' * @method '.$entityName.' where($fieldName, $fieldValue = null, $fieldRelation = ArgumentInterface::EQUAL)';
327
        $class .= "\n" . ' * @method '.$entityName.' primary($value) Query for chaining';
328
        $class .= "\n" . ' * @method '.$entityName.' identifier($value) Query for chaining';
329
        $class .= "\n" . ' * @method '.$entityName.' created($value) Query for chaining';
330
        $class .= "\n" . ' * @method '.$entityName.' modified($value) Query for chaining';
331
        $class .= "\n" . ' * @method '.$entityName.' published($value) Query for chaining';
332
        $class .= "\n" . ' */';
333
        $class .= "\n" . 'class ' . $entityName . ' extends \samsoncms\api\query\Entity';
334
        $class .= "\n" . '{';
335
336
        // Iterate additional fields
337
        $localizedFieldIDs = array();
338
        $notLocalizedFieldIDs = array();
339
        $allFieldIDs = array();
340
        $allFieldNames = array();
341
        $allFieldValueColumns = array();
342
        foreach ($navigationFields as $fieldID => $fieldRow) {
343
            $fieldName = $this->fieldName($fieldRow['Name']);
344
345
            // TODO: Add different method generation depending on their field type
346
            $class .= $this->generateFieldConditionMethod(
347
                $fieldName,
348
                $fieldRow[Field::F_PRIMARY],
349
                $fieldRow[Field::F_TYPE]
350
            );
351
352
            // Store field metadata
353
            $allFieldIDs[] = '"' . $fieldID . '" => "' . $fieldName . '"';
354
            $allFieldNames[] = '"' . $fieldName . '" => "' . $fieldID . '"';
355
            $allFieldValueColumns[] = '"' . $fieldID . '" => "' . Field::valueColumn($fieldRow[Field::F_TYPE]) . '"';
356
            if ($fieldRow[Field::F_LOCALIZED] == 1) {
357
                $localizedFieldIDs[] = '"' . $fieldID . '" => "' . $fieldName . '"';
358
            } else {
359
                $notLocalizedFieldIDs[] = '"' . $fieldID . '" => "' . $fieldName . '"';
360
            }
361
        }
362
363
        $class .= "\n\t";
364
        $class .= "\n\t" . '/** @var string Not transliterated entity name */';
365
        $class .= "\n\t" . 'protected static $identifier = "'.$this->fullEntityName($navigationName).'";';
366
        $class .= "\n\t" . '/** @var array Collection of navigation identifiers */';
367
        $class .= "\n\t" . 'protected static $navigationIDs = array(' . $navigationID . ');';
368
        $class .= "\n\t" . '/** @var array Collection of localized additional fields identifiers */';
369
        $class .= "\n\t" . 'protected static $localizedFieldIDs = array(' . "\n\t\t". implode(','."\n\t\t", $localizedFieldIDs) . "\n\t".');';
370
        $class .= "\n\t" . '/** @var array Collection of NOT localized additional fields identifiers */';
371
        $class .= "\n\t" . 'protected static $notLocalizedFieldIDs = array(' . "\n\t\t". implode(','."\n\t\t", $notLocalizedFieldIDs) . "\n\t".');';
372
        $class .= "\n\t" . '/** @var array Collection of all additional fields identifiers */';
373
        $class .= "\n\t" . 'protected static $fieldIDs = array(' . "\n\t\t". implode(','."\n\t\t", $allFieldIDs) . "\n\t".');';
374
        $class .= "\n\t" . '/** @var array Collection of additional fields value column names */';
375
        $class .= "\n\t" . 'protected static $fieldValueColumns = array(' . "\n\t\t". implode(','."\n\t\t", $allFieldValueColumns) . "\n\t".');';
376
        $class .= "\n\t" . '/** @var array Collection of additional field names */';
377
        $class .= "\n\t" . 'public static $fieldNames = array(' . "\n\t\t". implode(','."\n\t\t", $allFieldNames) . "\n\t".');';
378
        $class .= "\n" . '}';
379
380
        // Replace tabs with spaces
381
        return $class;
382
    }
383
384
    /** @return string Entity state hash */
385
    public function entityHash()
386
    {
387
        // Получим информацию о всех таблицах из БД
388
        return md5(serialize($this->database->fetch(
389
            'SELECT `TABLES`.`TABLE_NAME` as `TABLE_NAME`
390
              FROM `information_schema`.`TABLES` as `TABLES`
391
              WHERE `TABLES`.`TABLE_SCHEMA`="' . $this->database->database() . '";'
392
        )));
393
    }
394
395
    /** @return array Get collection of navigation objects */
396
    protected function entityNavigations($type = 0)
397
    {
398
        return $this->database->fetch('
399
        SELECT * FROM `structure`
400
        WHERE `Active` = "1" AND `Type` = "'.$type.'"'
401
        );
402
    }
403
404
    /** @return array Collection of navigation additional fields */
405
    protected function navigationFields($navigationID)
406
    {
407
        $return = array();
408
        // TODO: Optimize queries make one single query with only needed data
409
        foreach ($this->database->fetch('SELECT * FROM `structurefield` WHERE `StructureID` = "' . $navigationID . '" AND `Active` = "1"') as $fieldStructureRow) {
410
            foreach ($this->database->fetch('SELECT * FROM `field` WHERE `FieldID` = "' . $fieldStructureRow['FieldID'] . '"') as $fieldRow) {
411
                $return[$fieldRow['FieldID']] = $fieldRow;
412
            }
413
        }
414
415
        return $return;
416
    }
417
418
    /**
419
     * Generate entity classes.
420
     *
421
     * @param string $namespace Base namespace for generated classes
422
     * @return string Generated PHP code for entity classes
423
     */
424
    public function createEntityClasses($namespace = __NAMESPACE__)
425
    {
426
        $classes = "\n" . 'namespace ' . $namespace . ';';
427
        $classes .= "\n";
428
        $classes .= "\n" . 'use '.$namespace.'\Field;';
429
        $classes .= "\n" . 'use '.$namespace.'\query\EntityQuery;';
430
        $classes .= "\n" . 'use '.$namespace.'\FieldsTable;';
431
        $classes .= "\n" . 'use \samsonframework\orm\ArgumentInterface;';
432
        $classes .= "\n" . 'use \samsonframework\orm\QueryInterface;';
433
434
        // Iterate all structures
435
        foreach ($this->entityNavigations() as $structureRow) {
436
            $navigationFields = $this->navigationFields($structureRow['StructureID']);
437
            $entityName = $this->entityName($structureRow['Name']);
438
439
            $classes .= $this->createEntityClass(
440
                $structureRow['Name'],
441
                $entityName,
442
                $navigationFields
443
            );
444
445
            $classes .= $this->createQueryClass(
446
                $structureRow['StructureID'],
447
                $structureRow['Name'],
448
                $entityName.'Query',
449
                $navigationFields
450
            );
451
        }
452
453
        // Iterate table structures
454
        foreach ($this->entityNavigations(2) as $structureRow) {
455
            $navigationFields = $this->navigationFields($structureRow['StructureID']);
456
            $entityName = $this->entityName($structureRow['Name']);
457
458
            $classes .= $this->createTableClass(
459
                $structureRow['StructureID'],
460
                $structureRow['Name'],
461
                $entityName.'Table',
462
                $navigationFields
463
            );
464
465
        }
466
467
        // Make correct code formatting
468
        return str_replace("\t", '    ', $classes);
469
    }
470
471
    /**
472
     * Generator constructor.
473
     * @param DatabaseInterface $database Database instance
474
     */
475
    public function __construct(DatabaseInterface $database)
476
    {
477
        $this->generator = new \samsonphp\generator\Generator(__NAMESPACE__);
478
        $this->database = $database;
479
    }
480
}
481