Completed
Push — master ( 7d534e...7e3e80 )
by Vitaly
04:24
created

CMS::prepare()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 47
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 47
rs 9.0303
cc 3
eloc 35
nc 4
nop 0
1
<?php
2
namespace samsoncms\api;
3
4
use samson\activerecord\dbRelation;
5
use samson\activerecord\field;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, samsoncms\api\field.

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...
6
use samson\activerecord\materialfield;
7
use samson\activerecord\structure;
8
use samson\activerecord\structurefield;
9
use samson\activerecord\structurematerial;
10
use samson\activerecord\TableRelation;
11
use samson\activerecord\material;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, samsoncms\api\material.

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...
12
use samson\core\CompressableService;
13
use samson\activerecord\dbRecord;
14
use samson\activerecord\dbMySQLConnector;
15
16
/**
17
 * SamsonCMS API
18
 * @package samsoncms\api
19
 */
20
class CMS extends CompressableService
21
{
22
    /** @var string[] Collection of material fields SQL commands to include into SQL SELECT statement */
23
    public static $fields = array();
24
25
    /** @var array Collection of original material table attributes before spoofing */
26
    public static $materialAttributes = array();
27
28
    /** Identifier */
29
    protected $id = 'cmsapi';
30
31
    /** @var string Database table names prefix */
32
    public $tablePrefix = '';
33
34
    /**
35
     * Collection of material additional fields
36
     * @deprecated TODO: Remove!
37
     */
38
    public $material_fields = array();
39
40
    /**
41
     * Read SQL file with variables placeholders pasting
42
     * @param string $filePath SQL file for reading
43
     * @param string $prefix Prefix for addition
44
     * @return string SQL command text
45
     */
46
    public function readSQL($filePath, $prefix = '')
47
    {
48
        $sql = '';
49
50
        // Build path to SQL folder
51
        if (file_exists($filePath)) {
52
            // Replace prefix
53
            $sql = str_replace('@prefix', $prefix, file_get_contents($filePath));
54
        }
55
56
        return $sql;
57
    }
58
59
    /**
60
     * @see ModuleConnector::prepare()
61
     */
62
    public function prepare()
63
    {
64
        // Perform SQL table creation
65
        $path = __DIR__.'/../sql/';
66
        foreach (array_slice(scandir($path), 2) as $file) {
67
            db()->query($this->readSQL($path.$file, $this->tablePrefix));
68
        }
69
70
        // Initiate migration mechanism
71
        db()->migration(get_class($this), array($this, 'migrator'));
0 ignored issues
show
Documentation introduced by
array($this, 'migrator') is of type array<integer,this<samso...i\\CMS>","1":"string"}>, but the function expects a string.

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...
72
73
        // Define permanent table relations
74
        new TableRelation('material', 'user', 'UserID', 0, 'user_id');
75
        new TableRelation('material', 'gallery', 'MaterialID', TableRelation::T_ONE_TO_MANY);
76
        new TableRelation('material', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
77
        new TableRelation('material', 'field', 'materialfield.FieldID', TableRelation::T_ONE_TO_MANY);
78
        new TableRelation('material', 'structurematerial', 'MaterialID', TableRelation::T_ONE_TO_MANY);
79
        new TableRelation('material', 'structure', 'structurematerial.StructureID', TableRelation::T_ONE_TO_MANY);
80
        new TableRelation('materialfield', 'field', 'FieldID');
81
        new TableRelation('materialfield', 'material', 'MaterialID');
82
        new TableRelation('structurematerial', 'structure', 'StructureID');
83
        new TableRelation('structurematerial', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
84
        new TableRelation('structurematerial', 'material', 'MaterialID', TableRelation::T_ONE_TO_MANY);
85
        new TableRelation('structure', 'material', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
1 ignored issue
show
Coding Style introduced by
This line has 136 characters which exceeds the configured maximum of 120.
Loading history...
86
        new TableRelation('structure', 'gallery', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
1 ignored issue
show
Coding Style introduced by
This line has 135 characters which exceeds the configured maximum of 120.
Loading history...
87
        /*new TableRelation( 'structure', 'material', 'MaterialID' );*/
88
        new TableRelation('structure', 'user', 'UserID', 0, 'user_id');
89
        new TableRelation('structure', 'materialfield', 'material.MaterialID', TableRelation::T_ONE_TO_MANY, 'MaterialID', '_mf');
1 ignored issue
show
Coding Style introduced by
This line has 130 characters which exceeds the configured maximum of 120.
Loading history...
90
        new TableRelation('structure', 'structurematerial', 'StructureID', TableRelation::T_ONE_TO_MANY);
91
        new TableRelation('related_materials', 'material', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
1 ignored issue
show
Coding Style introduced by
This line has 121 characters which exceeds the configured maximum of 120.
Loading history...
92
        new TableRelation('related_materials', 'materialfield', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
1 ignored issue
show
Coding Style introduced by
This line has 126 characters which exceeds the configured maximum of 120.
Loading history...
93
        new TableRelation('field', 'structurefield', 'FieldID');
94
        new TableRelation('field', 'structure', 'structurefield.StructureID');
95
        new TableRelation('structurefield', 'field', 'FieldID');
96
        new TableRelation('structurefield', 'materialfield', 'FieldID');
97
        new TableRelation('structurefield', 'material', 'materialfield.MaterialID');
98
        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id', 'children_relations');
1 ignored issue
show
Coding Style introduced by
This line has 141 characters which exceeds the configured maximum of 120.
Loading history...
99
        new TableRelation('structure', 'structure', 'children_relations.child_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'children');
1 ignored issue
show
Coding Style introduced by
This line has 140 characters which exceeds the configured maximum of 120.
Loading history...
100
        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'child_id', 'parents_relations');
1 ignored issue
show
Coding Style introduced by
This line has 139 characters which exceeds the configured maximum of 120.
Loading history...
101
        new TableRelation('structure', 'structure', 'parents_relations.parent_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'parents');
1 ignored issue
show
Coding Style introduced by
This line has 139 characters which exceeds the configured maximum of 120.
Loading history...
102
        new TableRelation('structurematerial', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id');
1 ignored issue
show
Coding Style introduced by
This line has 127 characters which exceeds the configured maximum of 120.
Loading history...
103
        new TableRelation('groupright', 'right', 'RightID', TableRelation::T_ONE_TO_MANY);
104
        //elapsed('CMS:prepare');
105
106
        // Все прошло успешно
107
        return true && parent::prepare();
108
    }
109
110
    /**
111
     * Handler for CMSAPI database version manipulating
112
     * @param string $to_version Version to switch to
113
     * @return string Current database version
114
     */
115
    public function migrator($to_version = null)
116
    {
117
        // If something passed - change database version to it
118
        if (func_num_args()) {
119
            // Save current version to special db table
120
            db()->query("ALTER TABLE  `" . dbMySQLConnector::$prefix . "cms_version` CHANGE  `version`  `version` VARCHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  '" . $to_version . "';");
1 ignored issue
show
Coding Style introduced by
This line has 214 characters which exceeds the configured maximum of 120.
Loading history...
121
            die('Database successfully migrated to [' . $to_version . ']');
122
        } else { // Return current database version
1 ignored issue
show
Coding Style introduced by
Expected 1 newline after opening brace; 0 found
Loading history...
123
            $version_row = db()->fetch('SHOW COLUMNS FROM `' . dbMySQLConnector::$prefix . 'cms_version`');
124
            return $version_row[0]['Default'];
125
        }
126
    }
127
128
    /** @see \samson\core\CompressableExternalModule::afterCompress() */
129
    public function afterCompress(& $obj = null, array & $code = null)
130
    {
131
        // Fill additional fields data to material db request data for automatic altering material request
132
        self::$fields = array();
133
134
        $t_name = '_mf';
135
136
        // Save original material attributes
137
        self::$materialAttributes = &Material::$_attributes;
138
139
        // Copy original material table attributes
140
        Material::$_attributes = \samson\activerecord\material::$_attributes;
141
        Material::$_sql_select = \samson\activerecord\material::$_sql_select;
142
        Material::$_sql_from = \samson\activerecord\material::$_sql_from;
143
        Material::$_own_group = \samson\activerecord\material::$_own_group;
144
        Material::$_map = \samson\activerecord\material::$_map;
145
146
        // Perform db query to get all possible material fields
147
        if (dbQuery('field')->Active(1)->Name('', dbRelation::NOT_EQUAL)->exec($this->material_fields)) foreach ($this->material_fields as $db_field) {
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
This line has 151 characters which exceeds the configured maximum of 120.
Loading history...
Deprecated Code introduced by
The property samsoncms\api\CMS::$material_fields has been deprecated with message: TODO: Remove!

This property has been deprecated. The supplier of the class has supplied an explanatory message.

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

Loading history...
148
            // Add additional field localization condition
149
            if ($db_field->local == 1) $equal = '((' . $t_name . '.FieldID = ' . $db_field->id . ')&&(' . $t_name . ".locale = '" . locale() . "'))";
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
This line has 149 characters which exceeds the configured maximum of 120.
Loading history...
150
            else $equal = '((' . $t_name . '.FieldID = ' . $db_field->id . ')&&(' . $t_name . ".locale = ''))";
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
151
152
            // Define field value DB column for storing data
153
            $v_col = 'Value';
154
            // We must get data from other column for this type of field
155
            if ($db_field->Type == 7 || $db_field->Type == 3 || $db_field->Type == 10) {
156
                $v_col = 'numeric_value';
157
            } else if ($db_field->Type == 6) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the usage of else if is discouraged; instead using elseif is recommended.
Loading history...
158
                $v_col = 'key_value';
159
            }
160
161
            // Save additional field
162
            self::$fields[$db_field->Name] = "\n" . ' MAX(IF(' . $equal . ',' . $t_name . '.`' . $v_col . '`, NULL)) as `' . $db_field->Name . '`';
0 ignored issues
show
Coding Style introduced by
This line has 147 characters which exceeds the configured maximum of 120.
Loading history...
163
164
            // Set additional object metadata
165
            Material::$_attributes[$db_field->Name] = $db_field->Name;
166
            Material::$_map[$db_field->Name] = dbMySQLConnector::$prefix . 'material.' . $db_field->Name;
167
        }
168
169
        // Set additional object metadata
170
        Material::$_sql_select['this'] = ' STRAIGHT_JOIN ' . Material::$_sql_select['this'];
171
        if (sizeof(self::$fields)) {
172
            Material::$_sql_select['this'] .= ',' . implode(',', self::$fields);
173
        }
174
        Material::$_sql_from['this'] .= "\n" . 'LEFT JOIN ' . dbMySQLConnector::$prefix . 'materialfield as ' . $t_name . ' on ' . dbMySQLConnector::$prefix . 'material.MaterialID = ' . $t_name . '.MaterialID';
0 ignored issues
show
Coding Style introduced by
This line has 210 characters which exceeds the configured maximum of 120.
Loading history...
175
        Material::$_own_group[] = dbMySQLConnector::$prefix . 'material.MaterialID';
176
    }
177
178
    /** @see \samson\core\ExternalModule::init() */
179
    public function init(array $params = array())
180
    {
181
        // Change static class data
182
        $this->afterCompress();
183
    }
184
}
185