CMS::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 3
ccs 0
cts 2
cp 0
crap 2
1
<?php
2
namespace samsoncms\api;
3
4
// Backward compatibility
5
//require('generated/Material.php');
6
//require('generated/Field.php');
7
//require('generated/MaterialField.php');
8
//require('generated/Structure.php');
9
//require('generated/StructureField.php');
10
11
use samson\activerecord\dbMySQLConnector;
12
use samson\activerecord\TableRelation;
13
use samsoncms\api\generated\Materialfield;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, samsoncms\api\Materialfield.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
14
use samsoncms\api\generated\Structurefield;
15
use samsoncms\api\generated\Structurematerial;
16
use samsoncms\api\generator\GenericWriter;
17
use samsonframework\container\definition\analyzer\annotation\annotation\Service;
18
use samsonframework\core\ResourcesInterface;
19
use samsonframework\core\SystemInterface;
20
use samsonframework\core\CompressInterface;
21
use samsonphp\generator\Generator;
22
use samson\core\CompressableExternalModule;
23
24
/**
25
 * SamsonCMS API
26
 * @package samsoncms\api
27
 * @Service("cmsapi2")
28
 */
29
class CMS extends CompressableExternalModule implements CompressInterface
0 ignored issues
show
Deprecated Code introduced by
The class samson\core\CompressableExternalModule has been deprecated with message: Just implement samsonframework\core\CompressInterface

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
30
{
31
    /** Database entity name for relations between material and navigation */
32
    const MATERIAL_NAVIGATION_RELATION_ENTITY = Structurematerial::class;
33
    /** Database entity name for relations between material and images */
34
    const MATERIAL_IMAGES_RELATION_ENTITY = GalleryField::class;
35
    /** Database entity name for relations between additional fields and navigation */
36
    const FIELD_NAVIGATION_RELATION_ENTITY = Structurefield::class;
37
    /** Database entity name for relations between material and additional fields values */
38
    const MATERIAL_FIELD_RELATION_ENTITY = Materialfield::class;
39
    /** @var string Database table names prefix */
40
    public $tablePrefix = '';
41
    /** Identifier */
42
    protected $id = 'cmsapi2';
43
    /** @var \samsonframework\orm\DatabaseInterface */
44
    protected $database;
45
    /** @var array[string] Collection of generated queries */
46
    protected $queries;
47
48
    /**
49
     * CMS constructor.
50
     *
51
     * @param string $path
52
     * @param ResourcesInterface $resources
53
     * @param SystemInterface $system
54
     */
55
    public function  __construct($path, ResourcesInterface $resources, SystemInterface $system)
0 ignored issues
show
Coding Style introduced by
Expected "function abc(...)"; found "function abc(...)"
Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 2 found
Loading history...
56
    {
57
        $this->database = db();
58
59
        parent::__construct($path, $resources, $system);
60
    }
61
62
    /**
63
     * Module initialization.
64
     *
65
     * @param array $params Initialization parameters
66
     * @return boolean|null Initialization result
67
     */
68
    public function init(array $params = array())
69
    {
70
        $this->rewriteEntityLocale();
71
    }
72
73
    /**
74
     * Entity additional fields localization support.
75
     */
76
    protected function rewriteEntityLocale()
77
    {
78
        // Iterate all generated entity classes
79
        foreach (get_declared_classes() as $entityClass) {
80
            if (is_subclass_of($entityClass, '\samsoncms\api\Entity')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
81
                // Insert current application locale
82
                str_replace('@locale', locale(), $entityClass::$_sql_select);
83
            }
84
        }
85
    }
86
87
    public function beforeCompress(& $obj = null, array & $code = null)
88
    {
89
90
    }
91
92
    public function afterCompress(& $obj = null, array & $code = null)
93
    {
94
        // Iterate through generated php code
95
        $files = array();
96
        foreach (\samson\core\File::dir($this->cache_path, 'php', '', $files, 1) as $file) {
97
            // No namespace for global function file
98
            $ns = strpos($file, 'func') === false ? __NAMESPACE__ : '';
99
100
            // Compress generated php code
101
            $obj->compress_php($file, $this, $code, $ns);
102
        }
103
    }
104
105
    //[PHPCOMPRESSOR(remove,start)]
106
107
    /**
108
     * @see ModuleConnector::prepare()
109
     */
110
    public function prepare()
111
    {
112
        // Create cms_version
113
        $this->database->execute('
114
CREATE TABLE IF NOT EXISTS `cms_version`  (
115
  `version` varchar(15) NOT NULL DEFAULT \'30\'
116
) ENGINE=InnoDB DEFAULT CHARSET=utf8;'
117
        );
118
119
        // Perform this migration and execute only once
120
        if ($this->migrator() != 40) {
121
            // Perform SQL table creation
122
            $path = __DIR__ . '/../sql/';
123
            foreach (array_slice(scandir($path), 2) as $file) {
124
                trace('Performing database script [' . $file . ']');
125
                try {
126
                    foreach ($this->readSQL($path . $file, $this->tablePrefix) as $sql) {
127
                        $this->database->execute($sql);
128
                    }
129
                } catch(\Exception $e) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after CATCH keyword; 0 found
Loading history...
130
                    throw new \Exception('Canot execute file: "'.$file.'"'."\n".$e->getMessage());
131
                }
132
            }
133
            $this->migrator(40);
134
        }
135
136
        // Initiate migration mechanism
137
//        $this->database->migration(get_class($this), array($this, 'migrator'));
138
139
        // Define permanent table relations
140
//        new TableRelation('material', 'user', 'UserID', 0, 'user_id');
141
//        new TableRelation('material', 'gallery', 'MaterialID', TableRelation::T_ONE_TO_MANY);
142
//        new TableRelation('material', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
143
//        new TableRelation('material', 'field', 'materialfield.FieldID', TableRelation::T_ONE_TO_MANY);
144
//        new TableRelation('material', 'structurematerial', 'MaterialID', TableRelation::T_ONE_TO_MANY);
145
//        new TableRelation('material', 'structure', 'structurematerial.StructureID', TableRelation::T_ONE_TO_MANY);
146
//        new TableRelation('materialfield', 'field', 'FieldID');
147
//        new TableRelation('materialfield', 'material', 'MaterialID');
148
//        new TableRelation('structurematerial', 'structure', 'StructureID');
149
//        new TableRelation('structurematerial', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
150
//        new TableRelation('structurematerial', 'material', 'MaterialID', TableRelation::T_ONE_TO_MANY);
151
//        new TableRelation('structure', 'material', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
152
//        new TableRelation('structure', 'gallery', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
153
//        /*new TableRelation( 'structure', 'material', 'MaterialID' );*/
154
//        new TableRelation('structure', 'user', 'UserID', 0, 'user_id');
155
//        new TableRelation('structure', 'materialfield', 'material.MaterialID', TableRelation::T_ONE_TO_MANY, 'MaterialID', '_mf');
156
//        new TableRelation('structure', 'structurematerial', 'StructureID', TableRelation::T_ONE_TO_MANY);
157
//        //new TableRelation('related_materials', 'material', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
158
//        //new TableRelation('related_materials', 'materialfield', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
159
//        new TableRelation('field', 'structurefield', 'FieldID');
160
//        new TableRelation('field', 'structure', 'structurefield.StructureID');
161
//        new TableRelation('structurefield', 'field', 'FieldID');
162
//        new TableRelation('structurefield', 'materialfield', 'FieldID');
163
//        new TableRelation('structurefield', 'material', 'materialfield.MaterialID');
164
//        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id', 'children_relations');
165
//        new TableRelation('structure', 'structure', 'children_relations.child_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'children');
166
//        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'child_id', 'parents_relations');
167
//        new TableRelation('structure', 'structure', 'parents_relations.parent_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'parents');
168
//        new TableRelation('structurematerial', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id');
169
//        new TableRelation('groupright', 'right', 'RightID', TableRelation::T_ONE_TO_MANY);
170
171
        // TODO: Should be removed
172
//        $this->system->module('activerecord')->relations();
173
174
        $classWriter = new GenericWriter(
175
            $this->database,
176
            new Generator(),
177
            __NAMESPACE__ . '\\generated',
178
            [
179
                \samsoncms\api\generator\analyzer\RealAnalyzer::class => [
180
                    \samsoncms\api\generator\RealEntity::class,
181
                    \samsoncms\api\generator\RealQuery::class,
182
                    \samsoncms\api\generator\RealCollection::class,
183
                ],
184
                \samsoncms\api\generator\analyzer\TableTraitAnalyzer::class => [
185
                    \samsoncms\api\generator\TableTrait::class
186
                ],
187
                \samsoncms\api\generator\analyzer\VirtualAnalyzer::class => [
188
                    \samsoncms\api\generator\VirtualEntity::class,
189
                    \samsoncms\api\generator\VirtualQuery::class,
190
                    \samsoncms\api\generator\VirtualCollection::class,
191
                ],
192
                \samsoncms\api\generator\analyzer\GalleryAnalyzer::class => [
193
                    \samsoncms\api\generator\Gallery::class,
194
                ],
195
                \samsoncms\api\generator\analyzer\TableAnalyzer::class => [
196
                    \samsoncms\api\generator\TableVirtualEntity::class,
197
                    \samsoncms\api\generator\TableVirtualQuery::class,
198
                    \samsoncms\api\generator\TableVirtualCollection::class,
199
                    \samsoncms\api\generator\Table::class,
200
                    \samsoncms\api\generator\Row::class
201
                ]
202
            ],
203
            $this->cache_path
204
        );
205
206
        $classWriter->write();
207
208
        return parent::prepare();
209
    }
210
211
    /**
212
     * Handler for CMSAPI database version manipulating
213
     *
214
     * @param string $toVersion Version to switch to
215
     *
216
     * @return string Current database version
217
     */
218
    public function migrator($toVersion = null)
219
    {
220
        // If something passed - change database version to it
221
        if (func_num_args()) {
222
            // Save current version to special db table
223
            $this->database->execute(
224
                "ALTER TABLE  `" . dbMySQLConnector::$prefix . "cms_version`
225
                CHANGE  `version`  `version` VARCHAR( 15 ) CHARACTER SET utf8
226
                COLLATE utf8_general_ci NOT NULL DEFAULT  '" . $toVersion . "';"
227
            );
228
            die('Database successfully migrated to [' . $toVersion . ']');
229
        } else { // Return current database version
230
            $version_row = $this->database->fetch('SHOW COLUMNS FROM `' . $this->database::$prefix . 'cms_version`');
231
            if (isset($version_row[0]['Default'])) {
232
                return $version_row[0]['Default'];
233
            } else {
234
                return 0;
235
            }
236
        }
237
    }
238
239
    /**
240
     * Read SQL file with variables placeholders pasting
241
     *
242
     * @param string $filePath SQL file for reading
243
     * @param string $prefix   Prefix for addition
244
     *
245
     * @return array Collection of SQL command texts
246
     */
247
    public function readSQL($filePath, $prefix = '')
248
    {
249
        $sql = '';
250
251
        // Build path to SQL folder
252
        if (file_exists($filePath)) {
253
            // Replace prefix
254
            $sql = str_replace('@prefix', $prefix, file_get_contents($filePath));
255
        }
256
257
        // Split queries
258
        $sqlCommands = explode(';', str_replace("\n", '', $sql));
259
260
        // Always return array
261
        return array_filter(is_array($sqlCommands) ? $sqlCommands : array($sqlCommands));
262
    }
263
    //[PHPCOMPRESSOR(remove,end)]
264
}
265