Completed
Push — master ( b0617c...74d816 )
by Vitaly
03:18
created

CMS::prepare()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 49
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 3 Features 2
Metric Value
c 4
b 3
f 2
dl 0
loc 49
rs 9.2258
cc 3
eloc 37
nc 2
nop 0
1
<?php
2
namespace samsoncms\api;
3
4
use samson\activerecord\dbRelation;
5
use samson\activerecord\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...
6
use samson\activerecord\structurefield;
7
use samson\activerecord\structurematerial;
8
use samson\activerecord\TableRelation;
9
use samson\core\CompressableService;
10
use samson\activerecord\dbRecord;
11
use samson\activerecord\dbMySQLConnector;
12
13
/**
14
 * SamsonCMS API
15
 * @package samsoncms\api
16
 */
17
class CMS extends CompressableService
18
{
19
    /** Database entity name for relations between material and navigation */
20
    const MATERIAL_NAVIGATION_RELATION_ENTITY = '\samson\activerecord\structurematerial';
21
    /** Database entity name for relations between additional fields and navigation */
22
    const FIELD_NAVIGATION_RELATION_ENTITY = '\samson\activerecord\structurefield';
23
    /** Database entity name for relations between material and additional fields values */
24
    const MATERIAL_FIELD_RELATION_ENTITY = '\samson\activerecord\materialfield';
25
26
    /** Identifier */
27
    protected $id = 'cmsapi2';
28
29
    /** @var \samsonframework\orm\DatabaseInterface */
30
    protected $database;
31
32
    /** @var string Database table names prefix */
33
    public $tablePrefix = '';
34
35
    /**
36
     * CMS constructor.
37
     * @param null|string $path
38
     * @param null|string $vid
39
     * @param mixed|null $resources
40
     */
41
    public function __construct($path, $vid, $resources)
42
    {
43
        // TODO: This should changed to normal DI
44
        $this->database = db();
0 ignored issues
show
Documentation Bug introduced by
It seems like db() of type object<samson\activerecord\dbMySQL> is incompatible with the declared type object<samsonframework\orm\DatabaseInterface> of property $database.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
45
46
        parent::__construct($path, $vid, $resources);
47
    }
48
49
    //[PHPCOMPRESSOR(remove,start)]
50
    /**
51
     * Read SQL file with variables placeholders pasting
52
     * @param string $filePath SQL file for reading
53
     * @param string $prefix Prefix for addition
54
     * @return string SQL command text
55
     */
56
    public function readSQL($filePath, $prefix = '')
57
    {
58
        $sql = '';
59
60
        // Build path to SQL folder
61
        if (file_exists($filePath)) {
62
            // Replace prefix
63
            $sql = str_replace('@prefix', $prefix, file_get_contents($filePath));
64
        }
65
66
        return $sql;
67
    }
68
69
    /**
70
     * @see ModuleConnector::prepare()
71
     */
72
    public function prepare()
73
    {
74
        // Perform this migration and execute only once
75
        if ($this->migrator() != 40) {
76
            // Perform SQL table creation
77
            $path = __DIR__ . '/../sql/';
78
            foreach (array_slice(scandir($path), 2) as $file) {
79
                $this->database->execute($this->readSQL($path . $file, $this->tablePrefix));
80
            }
81
            $this->migrator(40);
82
        }
83
84
        // Initiate migration mechanism
85
        $this->database->migration(get_class($this), array($this, 'migrator'));
86
87
        // Define permanent table relations
88
        new TableRelation('material', 'user', 'UserID', 0, 'user_id');
89
        new TableRelation('material', 'gallery', 'MaterialID', TableRelation::T_ONE_TO_MANY);
90
        new TableRelation('material', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
91
        new TableRelation('material', 'field', 'materialfield.FieldID', TableRelation::T_ONE_TO_MANY);
92
        new TableRelation('material', 'structurematerial', 'MaterialID', TableRelation::T_ONE_TO_MANY);
93
        new TableRelation('material', 'structure', 'structurematerial.StructureID', TableRelation::T_ONE_TO_MANY);
94
        new TableRelation('materialfield', 'field', 'FieldID');
95
        new TableRelation('materialfield', 'material', 'MaterialID');
96
        new TableRelation('structurematerial', 'structure', 'StructureID');
97
        new TableRelation('structurematerial', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
98
        new TableRelation('structurematerial', 'material', 'MaterialID', TableRelation::T_ONE_TO_MANY);
99
        new TableRelation('structure', 'material', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
100
        new TableRelation('structure', 'gallery', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
101
        /*new TableRelation( 'structure', 'material', 'MaterialID' );*/
102
        new TableRelation('structure', 'user', 'UserID', 0, 'user_id');
103
        new TableRelation('structure', 'materialfield', 'material.MaterialID', TableRelation::T_ONE_TO_MANY, 'MaterialID', '_mf');
104
        new TableRelation('structure', 'structurematerial', 'StructureID', TableRelation::T_ONE_TO_MANY);
105
        new TableRelation('related_materials', 'material', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
106
        new TableRelation('related_materials', 'materialfield', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
107
        new TableRelation('field', 'structurefield', 'FieldID');
108
        new TableRelation('field', 'structure', 'structurefield.StructureID');
109
        new TableRelation('structurefield', 'field', 'FieldID');
110
        new TableRelation('structurefield', 'materialfield', 'FieldID');
111
        new TableRelation('structurefield', 'material', 'materialfield.MaterialID');
112
        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id', 'children_relations');
113
        new TableRelation('structure', 'structure', 'children_relations.child_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'children');
114
        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'child_id', 'parents_relations');
115
        new TableRelation('structure', 'structure', 'parents_relations.parent_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'parents');
116
        new TableRelation('structurematerial', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id');
117
        new TableRelation('groupright', 'right', 'RightID', TableRelation::T_ONE_TO_MANY);
118
119
        return parent::prepare();
120
    }
121
122
    /**
123
     * Handler for CMSAPI database version manipulating
124
     * @param string $to_version Version to switch to
125
     * @return string Current database version
126
     */
127
    public function migrator($to_version = null)
128
    {
129
        // If something passed - change database version to it
130
        if (func_num_args()) {
131
            // Save current version to special db table
132
            $this->database->execute(
133
                "ALTER TABLE  `" . dbMySQLConnector::$prefix . "cms_version`
134
                CHANGE  `version`  `version` VARCHAR( 15 ) CHARACTER SET utf8
135
                COLLATE utf8_general_ci NOT NULL DEFAULT  '" . $to_version . "';"
136
            );
137
            die('Database successfully migrated to [' . $to_version . ']');
138
        } else { // Return current database version
139
            $version_row = $this->database->fetch('SHOW COLUMNS FROM `' . dbMySQLConnector::$prefix . 'cms_version`');
140
            if (isset($version_row[0]['Default'])) {
141
                return $version_row[0]['Default'];
142
            } else {
143
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by samsoncms\api\CMS::migrator of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
144
            }
145
        }
146
    }
147
    //[PHPCOMPRESSOR(remove,end)]
148
}
149