Completed
Push — master ( 0f2840...79bbce )
by Vitaly
02:44
created

CMS::readSQL()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 2 Features 2
Metric Value
c 4
b 2
f 2
dl 0
loc 12
rs 9.4286
cc 2
eloc 5
nc 2
nop 2
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
    /** Identifier */
20
    protected $id = 'cmsapi2';
21
22
    /** @var \samsonframework\orm\DatabaseInterface */
23
    protected $database;
24
25
    /** @var string Database table names prefix */
26
    public $tablePrefix = '';
27
28
    /**
29
     * CMS constructor.
30
     * @param null|string $path
31
     * @param null|string $vid
32
     * @param mixed|null $resources
33
     */
34
    public function __construct($path, $vid, $resources)
35
    {
36
        // TODO: This should changed to normal DI
37
        $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...
38
39
        parent::__construct($path, $vid, $resources);
40
    }
41
42
    /**
43
     * Read SQL file with variables placeholders pasting
44
     * @param string $filePath SQL file for reading
45
     * @param string $prefix Prefix for addition
46
     * @return string SQL command text
47
     */
48
    public function readSQL($filePath, $prefix = '')
49
    {
50
        $sql = '';
51
52
        // Build path to SQL folder
53
        if (file_exists($filePath)) {
54
            // Replace prefix
55
            $sql = str_replace('@prefix', $prefix, file_get_contents($filePath));
56
        }
57
58
        return $sql;
59
    }
60
61
    /**
62
     * @see ModuleConnector::prepare()
63
     */
64
    public function prepare()
65
    {
66
        // Perform SQL table creation
67
        $path = __DIR__.'/../sql/';
68
        foreach (array_slice(scandir($path), 2) as $file) {
69
            $this->database->query($this->readSQL($path.$file, $this->tablePrefix));
70
        }
71
72
        // Initiate migration mechanism
73
        $this->database->migration(get_class($this), array($this, 'migrator'));
74
75
        // Define permanent table relations
76
        new TableRelation('material', 'user', 'UserID', 0, 'user_id');
77
        new TableRelation('material', 'gallery', 'MaterialID', TableRelation::T_ONE_TO_MANY);
78
        new TableRelation('material', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
79
        new TableRelation('material', 'field', 'materialfield.FieldID', TableRelation::T_ONE_TO_MANY);
80
        new TableRelation('material', 'structurematerial', 'MaterialID', TableRelation::T_ONE_TO_MANY);
81
        new TableRelation('material', 'structure', 'structurematerial.StructureID', TableRelation::T_ONE_TO_MANY);
82
        new TableRelation('materialfield', 'field', 'FieldID');
83
        new TableRelation('materialfield', 'material', 'MaterialID');
84
        new TableRelation('structurematerial', 'structure', 'StructureID');
85
        new TableRelation('structurematerial', 'materialfield', 'MaterialID', TableRelation::T_ONE_TO_MANY);
86
        new TableRelation('structurematerial', 'material', 'MaterialID', TableRelation::T_ONE_TO_MANY);
87
        new TableRelation('structure', 'material', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
88
        new TableRelation('structure', 'gallery', 'structurematerial.MaterialID', TableRelation::T_ONE_TO_MANY, null, 'manymaterials');
89
        /*new TableRelation( 'structure', 'material', 'MaterialID' );*/
90
        new TableRelation('structure', 'user', 'UserID', 0, 'user_id');
91
        new TableRelation('structure', 'materialfield', 'material.MaterialID', TableRelation::T_ONE_TO_MANY, 'MaterialID', '_mf');
92
        new TableRelation('structure', 'structurematerial', 'StructureID', TableRelation::T_ONE_TO_MANY);
93
        new TableRelation('related_materials', 'material', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
94
        new TableRelation('related_materials', 'materialfield', 'first_material', TableRelation::T_ONE_TO_MANY, 'MaterialID');
95
        new TableRelation('field', 'structurefield', 'FieldID');
96
        new TableRelation('field', 'structure', 'structurefield.StructureID');
97
        new TableRelation('structurefield', 'field', 'FieldID');
98
        new TableRelation('structurefield', 'materialfield', 'FieldID');
99
        new TableRelation('structurefield', 'material', 'materialfield.MaterialID');
100
        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id', 'children_relations');
101
        new TableRelation('structure', 'structure', 'children_relations.child_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'children');
102
        new TableRelation('structure', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'child_id', 'parents_relations');
103
        new TableRelation('structure', 'structure', 'parents_relations.parent_id', TableRelation::T_ONE_TO_MANY, 'StructureID', 'parents');
104
        new TableRelation('structurematerial', 'structure_relation', 'StructureID', TableRelation::T_ONE_TO_MANY, 'parent_id');
105
        new TableRelation('groupright', 'right', 'RightID', TableRelation::T_ONE_TO_MANY);
106
107
        return 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 . "';");
0 ignored issues
show
Deprecated Code introduced by
The method samsonframework\orm\Database::query() has been deprecated with message: Use execute()

This method 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 method will be removed from the class and what other method or class to use instead.

Loading history...
121
            die('Database successfully migrated to [' . $to_version . ']');
122
        } else { // Return current database version
123
            $version_row = db()->fetch('SHOW COLUMNS FROM `' . dbMySQLConnector::$prefix . 'cms_version`');
124
            if (isset($version_row[0]['Default'])) {
125
                return $version_row[0]['Default'];
126
            } else {
127
                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...
128
            }
129
        }
130
    }
131
}
132