Completed
Branch develop (0caa42)
by Oyebanji Jacob
03:06 queued 55s
created

Model::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4285
cc 1
eloc 2
nc 1
nop 0
1
<?php 
2
3
namespace Pyjac\ORM;
4
5
abstract class Model implements ModelInterface
6
{
7
8
   
9
    protected  $properties = [];
10
11
    /**
12
     * Store instance of database connection used.
13
    * @var [type]
14
    */
15
    protected  $databaseConnection;
16
17
    /**
18
     * Create a model instance.
19
     * 
20
     */
21
     public function __construct()
22
    {
23
        $this->databaseConnection = DatabaseConnection::getInstance()->databaseConnection;
24
       
25
    }
26
    /**
27
     * Sets into $properties the $key => $value pairs
28
     * 
29
    * @param string $key 
30
    * @param string $val 
31
    *
32
    */
33
    public  function __set($key, $val)
34
    {
35
        $this->properties[$key] = $val;
36
    }
37
    /**
38
    * @param string $key
39
    * 
40
    * @return array
41
    */
42
    public function __get($key)
43
    {
44
        return $this->properties[$key];
45
    }
46
    /**
47
     * Get all the model properties.
48
     *
49
     * @return array
50
     */
51
     public function getProperties()
52
     {
53
         return $this->properties;
54
     }
55
    /**
56
    * Gets the name of the child class with a 's'.
57
    *
58
    * @return string
59
    */
60
    public function getTableName()
61
    {
62
        $className = explode('\\', get_called_class());
63
        $table = strtolower(end($className) .'s');
64
        return $table;
65
    }
66
    /**
67
    * Find the particular model with the passed id.
68
    * 
69
    * @param int $id
70
    * 
71
    * @return object
72
    */
73
    public static function find($id)
74
    {
75
        $model = new static;
76
        return $model->get($id); 
77
    }
78
79
    /**
80
    * Get the particular model with the passed id.
81
    * 
82
    * @param int $id
83
    * 
84
    * @return object
85
    */
86
    public function get($id)
87
    {
88
        $sql = "SELECT * FROM {$this->getTableName()} WHERE id={$id}";
89
        $sqlStatement = $this->databaseConnection->prepare($sql);
90
        $sqlStatement->setFetchMode($this->databaseConnection::FETCH_CLASS, get_called_class());
91
        $sqlStatement->execute();
92
        if($sqlStatement->rowCount() < 1){
93
            throw new ModelNotFoundException($id);
94
        }
95
        return $sqlStatement->fetch();
96
    }
97
98
    /**
99
    * Get all the models from the database.
100
    * 
101
    * @return array
102
    */
103
    public static function getAll()
104
    {
105
        $model = new static;
106
        return $model->all();
107
    }
108
109
    /**
110
    * Returns all the models from the database.
111
    * 
112
    * @return array
113
    */
114
    public function all()
115
    {
116
        $sql = "SELECT * FROM {$this->getTableName()}";
117
        $row = $this->databaseConnection->prepare($sql);
118
        $row->execute();
119
       
120
        return $row->fetchAll($this->databaseConnection::FETCH_CLASS);
121
122
    }
123
    /** 
124
     * Update the model in the database.
125
     * 
126
     * @return int
127
    */
128
    private function update()
129
    {
130
       
131
        $columnNames = "";
0 ignored issues
show
Unused Code introduced by
$columnNames 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...
132
        $columnValues = "";
0 ignored issues
show
Unused Code introduced by
$columnValues 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...
133
        $bindNameParameters = [];
134
        $sqlUpdate = "UPDATE " . $this->getTableName() . " SET " ;
135 View Code Duplication
        foreach ($this->properties as $columnName => $columnValue) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
136
            if($key == 'id') continue;
0 ignored issues
show
Bug introduced by
The variable $key does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
137
            $bindColumnName = ':' . $columnName;
138
            $sqlUpdate .= "$columnName = $bindColumnName,";
139
            $bindNameParameters[$bindColumnName] = $columnValue;
140
        }
141
        //Remove the last comma in sql command then join it to the other query part.
142
        $sqlUpdate = substr($sqlUpdate, 0, -1)." WHERE id = :id";
143
        $sqlStatement = $this->databaseConnection->prepare($sqlUpdate);
144
        $sqlStatement->bindValue(":id", $this->properties['id']);
145
        $sqlStatement->execute($bindNameParameters);
146
        return $sqlStatement->rowCount();
147
    }
148
149
    /**
150
    * Insert the model values into the database.
151
    *
152
    * @return int
153
    */
154
    private function create()
155
    {
156
        
157
        $columnNames = "";
158
        $columnValues = "";
159
        $bindNameParameters = [];
160
        $sqlCreate = "INSERT" . " INTO " . $this->getTableName()." (";
161 View Code Duplication
        foreach ($this->properties as $columnName => $columnValue) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
163
            $bindColumnName = ':' . $columnName;
164
            $columnNames .= $columnName.",";
165
            $columnValues .= $bindColumnName.",";
166
            $bindNameParameters[$bindColumnName] = $columnValue;
167
        }
168
        // Remove ending comma and whitespace.
169
        $columnNames = substr($columnNames, 0, -1);
170
        $columnValues = substr($columnValues, 0, -1);
171
172
        $sqlCreate .= $columnNames.') VALUES (' .$columnValues.')';
173
        $sqlStatement = $this->databaseConnection->prepare($sqlCreate);
174
        $sqlStatement->execute($bindNameParameters);
175
        return $sqlStatement->rowCount();
176
    }
177
    
178
    /**
179
     * Save the model data to the database.
180
     * 
181
     * @return boolean
182
     */
183
    public function save()
184
    {
185
        return $this->id ? $this->update() : $this->create();
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Pyjac\ORM\Model>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
186
    }
187
188
   /**
189
    * Delete a model from the database. 
190
    * @param  int $id 
191
    * @return boolean
192
    */
193
    public static function destroy($id)
194
    {
195
        $model = new static;
196
        return $model->delete($id); 
197
    }
198
199
    /**
200
     * Delete model from the database.
201
     * 
202
     * @param  int $id
203
     * @return boolean
204
     */
205
    public function delete($id)
206
    {
207
        $sql = "DELETE" . " FROM " . self::getTableName()." WHERE id = ". $id;
208
        $sqlStatment = $this->databaseConnection->prepare($sql);
209
        $sqlStatment->execute();
210
        return ($sqlStatment->rowCount() > 0) ? true : false;
211
    }
212
213
}