Completed
Push — develop ( aba1ed...ebe2d3 )
by Oyebanji Jacob
02:15
created

Model::getAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php 
2
3
namespace Pyjac\ORM;
4
5
use PDO;
6
use Pyjac\ORM\Exception\ModelNotFoundException;
7
8
abstract class Model implements ModelInterface
9
{
10
11
   
12
    protected  $properties = [];
13
14
    /**
15
     * Store instance of database connection used.
16
    * @var [type]
17
    */
18
    protected  $databaseConnection;
19
20
    /**
21
     *  The id of the model.
22
     *  
23
     * @property string $id
24
    */
25
     
26
    /**
27
     * Create a model instance.
28
     * 
29
     */
30
     public function __construct(DatabaseConnectionInterface $databaseConnection = null)
31
    {
32
        if($databaseConnection == null){
33
            $this->databaseConnection = DatabaseConnection::getInstance()->databaseConnection;    
34
        }
35
        $this->databaseConnection = $databaseConnection;
36
    }
37
    /**
38
     * Sets into $properties the $key => $value pairs
39
     * 
40
    * @param string $key 
41
    * @param string $val 
42
    *
43
    */
44
    public  function __set($key, $val)
45
    {
46
        $this->properties[$key] = $val;
47
    }
48
    /**
49
    * @param string $key
50
    * 
51
    * @return array
52
    */
53
    public function __get($key)
54
    {
55
        return $this->properties[$key];
56
    }
57
    /**
58
     * Get all the model properties.
59
     *
60
     * @return array
61
     */
62
     public function getProperties()
63
     {
64
         return $this->properties;
65
     }
66
67
     /**
68
     * Set model properties.
69
     *
70
     */
71
     public function setProperties(array $properties)
72
     {
73
         $this->properties = $properties;
74
     }
75
    /**
76
    * Gets the name of the child class with a 's'.
77
    *
78
    * @return string
79
    */
80
    public function getTableName()
81
    {
82
        $className = explode('\\', get_called_class());
83
        $table = strtolower(end($className) .'s');
84
        return $table;
85
    }
86
    /**
87
    * Find the particular model with the passed id.
88
    * 
89
    * @param int $id
90
    * 
91
    * @return object
92
    */
93
    public static function find($id)
94
    {
95
        $model = new static;
96
        return $model->get($id); 
97
    }
98
99
    /**
100
    * Get the particular model with the passed id.
101
    * 
102
    * @param int $id
103
    * 
104
    * @return object
105
    */
106
    public function get($id)
107
    {
108
        $sql = "SELECT * FROM {$this->getTableName()} WHERE id={$id}";
109
        $sqlStatement = $this->databaseConnection->prepare($sql);
0 ignored issues
show
Bug introduced by
The method prepare() does not seem to exist on object<Pyjac\ORM\DatabaseConnectionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
110
        $sqlStatement->setFetchMode(PDO::FETCH_CLASS, get_called_class());
111
        $sqlStatement->execute();
112
        if($sqlStatement->rowCount() < 1){
113
            throw new ModelNotFoundException($id);
114
        }
115
        return $sqlStatement->fetch();
116
    }
117
118
    /**
119
    * Get all the models from the database.
120
    * 
121
    * @return array
122
    */
123
    public static function getAll()
124
    {
125
        $model = new static;
126
        return $model->all();
127
    }
128
129
    /**
130
    * Returns all the models from the database.
131
    * 
132
    * @return array
133
    */
134
    public function all()
135
    {
136
        $sql = "SELECT * FROM {$this->getTableName()}";
137
        $sqlStatement = $this->databaseConnection->prepare($sql);
0 ignored issues
show
Bug introduced by
The method prepare() does not seem to exist on object<Pyjac\ORM\DatabaseConnectionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
138
        $sqlStatement->execute();
139
       
140
        return $sqlStatement->fetchAll(PDO::FETCH_CLASS);
141
142
    }
143
    /** 
144
     * Update the model in the database.
145
     * 
146
     * @return int
147
    */
148
    public function update()
149
    {
150
       
151
        $bindNameParameters = [];
152
        $sqlUpdate = "UPDATE " . $this->getTableName() . " SET " ;
153 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...
154
            if($columnName == 'id') continue;
155
            $bindColumnName = ':' . $columnName;
156
            $sqlUpdate .= "$columnName = $bindColumnName,";
157
            $bindNameParameters[$bindColumnName] = $columnValue;
158
        }
159
        //Remove the last comma in sql command then join it to the other query part.
160
        $sqlUpdate = substr($sqlUpdate, 0, -1)." WHERE id = :id";
161
        $sqlStatement = $this->databaseConnection->prepare($sqlUpdate);
0 ignored issues
show
Bug introduced by
The method prepare() does not seem to exist on object<Pyjac\ORM\DatabaseConnectionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
162
        $bindNameParameters[":id"] = $this->properties['id'];
163
        $sqlStatement->execute($bindNameParameters);
164
        return $sqlStatement->rowCount();
165
    }
166
167
    /**
168
    * Insert the model values into the database.
169
    *
170
    * @return int
171
    */
172
    public function create()
173
    {
174
        
175
        $columnNames = "";
176
        $columnValues = "";
177
        $bindNameParameters = [];
178
        $sqlCreate = "INSERT" . " INTO " . $this->getTableName()." (";
179 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...
180
181
            $bindColumnName = ':' . $columnName;
182
            $columnNames .= $columnName.",";
183
            $columnValues .= $bindColumnName.",";
184
            $bindNameParameters[$bindColumnName] = $columnValue;
185
        }
186
        // Remove ending comma and whitespace.
187
        $columnNames = substr($columnNames, 0, -1);
188
        $columnValues = substr($columnValues, 0, -1);
189
190
        $sqlCreate .= $columnNames.') VALUES (' .$columnValues.')';
191
        $sqlStatement = $this->databaseConnection->prepare($sqlCreate);
0 ignored issues
show
Bug introduced by
The method prepare() does not seem to exist on object<Pyjac\ORM\DatabaseConnectionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
192
        $sqlStatement->execute($bindNameParameters);
193
        return $sqlStatement->rowCount();
194
    }
195
    
196
    /**
197
     * Save the model data to the database.
198
     * 
199
     * @return boolean
200
     */
201
    public function save()
202
    {
203
        return isset($this->properties['id']) ? $this->update() : $this->create();
204
    }
205
206
   /**
207
    * Delete a model from the database. 
208
    * @param  int $id 
209
    * @return boolean
210
    */
211
    public static function destroy($id)
212
    {
213
        $model = new static;
214
        return $model->delete($id); 
215
    }
216
217
    /**
218
     * Delete model from the database.
219
     * 
220
     * @param  int $id
221
     * @return boolean
222
     */
223
    public function delete($id)
224
    {
225
        $sql = "DELETE" . " FROM " . self::getTableName()." WHERE id = ". $id;
226
        $sqlStatment = $this->databaseConnection->prepare($sql);
0 ignored issues
show
Bug introduced by
The method prepare() does not seem to exist on object<Pyjac\ORM\DatabaseConnectionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
227
        $sqlStatment->execute();
228
        return ($sqlStatment->rowCount() > 0) ? true : false;
229
    }
230
231
}