Completed
Branch master (e3a0da)
by
unknown
15:36
created

Model::setProperties()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4286
cc 3
eloc 4
nc 3
nop 1
1
<?php
2
3
namespace Opeyemiabiodun\PotatoORM\Models;
4
5
use RuntimeException;
6
use InvalidArgumentException;
7
use Opeyemiabiodun\PotatoORM\Connections\Connection;
8
use Opeyemiabiodun\PotatoORM\Connections\PgSqlConnection;
9
use Opeyemiabiodun\PotatoORM\Exceptions\AssignmentException;
10
use Opeyemiabiodun\PotatoORM\Exceptions\PropertyNotFoundException;
11
12
trait Model
13
{
14
    /**
15
     * The model's attributes.
16
     *
17
     * @var array
18
     */
19
    protected static $_attributes = [];
20
21
    /**
22
     * The model's database connection.
23
     *
24
     * @var Opeyemiabiodun\PotatoORM\Connections\Connection
25
     */
26
    protected static $_connection;
27
28
    /**
29
     * The primary key of the model's database table.
30
     *
31
     * @var string
32
     */
33
    protected static $_primaryKey;
34
35
    /**
36
     * The model's database table.
37
     *
38
     * @var string
39
     */
40
    protected static $_table;
41
42
    /**
43
     * The model's constructor method.
44
     *
45
     * @param Connection|null $connection An Opeyemiabiodun\PotatoORM\Connections\Connection instance or null
46
     * @param string          $table      The name of the model's table in the database
47
     */
48
    public function __construct($array = [], Connection $connection = null, $table = null)
49
    {
50
        if (null === $connection) {
51
            $connection = PgSqlConnection::load();
52
        }
53
54
        if (null === $table) {
55
            $table = strtolower(substr(get_class($this),strripos(get_class($this), "\\") + 1))."_table";
56
        }
57
58
        $this->setConnection($connection);
59
        $this->setTable($table);
60
61
        if (! empty($array)) {
62
            $this->setProperties($array);
63
        }
64
    }
65
66
    /**
67
     * The getter method for the model's properties.
68
     *
69
     * @param string $property The particular property
70
     *
71
     * @return int|float|string|bool The value of the property
72
     */
73
    public function __get($property)
74
    {
75
        if (array_key_exists($property, self::$_attributes)) {
76
            return self::$_attributes[$property];
77
        } else {
78
            throw new PropertyNotFoundException("The {get_class($this)} instance has no {$property} property.");
79
        }
80
    }
81
82
    /**
83
     * The setter method for the model's properties.
84
     *
85
     * @param string                $property The particular property
86
     * @param int|float|string|bool $value    The value of the property
87
     */
88
    public function __set($property, $value)
89
    {
90
        if (! is_scalar($value)) {
91
            throw new AssignmentException("{$value} is not a scalar value. Only scalar values can be assigned to the {$property} property.");
92
        }
93
94
        if (array_key_exists($property, self::$_attributes)) {
95
            self::$_attributes[$property] = $value;
96
        } else {
97
            throw new PropertyNotFoundException("The ".get_class($this)." instance has no {$property} property.");
98
        }
99
    }
100
101
    /**
102
     * Deletes a specified instance of the model in the database.
103
     *
104
     * @param int $number Specifies which model instance to delete; the 1st, 2nd, 3rd, .....
105
     *
106
     * @return bool Returns boolean true if the instance was successfully deleted or else it returns false.
107
     */
108 View Code Duplication
    public static function destroy($number)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
109
    {
110
        if (! is_int($number)) {
111
            throw new InvalidArgumentException("The parameter {$number} is not an integer. An integer is required instead.");
112
        }
113
114
        if ($number <= 0) {
115
            throw new InvalidArgumentException("The parameter {$number} is not a positive integer. A positive integer is required instead.");
116
        }
117
118
        return self::$_connection->deleteRecord(self::$_table, $number - 1);
119
    }
120
121
    /**
122
     * Finds a specified instance of the model in the database.
123
     *
124
     * @param int $number Specifies which model instance to find; the 1st, 2nd, 3rd, .....
125
     *
126
     * @return array Returns the particular instance of the model.
127
     */
128 View Code Duplication
    public static function find($number)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
129
    {
130
        if (! is_int($number)) {
131
            throw new InvalidArgumentException("The parameter {$number} is not an integer. An integer is required instead.");
132
        }
133
134
        if ($number <= 0) {
135
            throw new InvalidArgumentException("The parameter {$number} is not a positive integer. A positive integer is required instead.");
136
        }
137
        
138
        $record = self::$_connection->findRecord(self::$_table, $number - 1);
139
        
140
        return new self($record);
141
    }
142
143
    /**
144
     * Returns all instances of the model in the database.
145
     *
146
     * @return array All instances of the model in the database.
147
     */
148
    public static function getAll()
149
    {
150
        return self::$_connection->getAllRecords(self::$_table);
151
    }
152
153
    /**
154
     * Checks the attributes of the model to ensure they are not all null.
155
     *
156
     * @return bool true if at least one of the models's attributes is not null else false.
157
     */
158
    private function hasAttributes()
159
    {
160
        $hasAttributes = false;
161
162
        foreach (self::$_attributes as $key => $value) {
163
            if (! is_null($value)) {
164
                $hasAttributes = true;
165
            }
166
        }
167
168
        return $hasAttributes;
169
    }
170
171
    /**
172
     * Saves or updates an instance of the model in the database.
173
     *
174
     * @return bool Returns true if the operation was successfully else returns false.
175
     */
176
    public function save()
177
    {
178
        if (! $this->hasAttributes()) {
179
            throw new RuntimeException("{get_class($this)} model has nothing to persist to the database.");
180
        }
181
182
        $pk = (empty(self::$_attributes[self::$_primaryKey])) ? "NULL" :  self::$_attributes[self::$_primaryKey];
183
184
        $record = self::$_connection->findRecord(self::$_table, (string) $pk);
185
186
        if (empty($record)) {
187
            return self::$_connection->createRecord(self::$_table, self::$_attributes);
188
        } else {
189
            return self::$_connection->updateRecord(self::$_table, self::$_primaryKey, self::$_attributes);
190
        }
191
    }
192
193
    /**
194
     * Sets the model's connection.
195
     *
196
     * @param Connection $connection An instance of Opeyemiabiodun\PotatoORM\Connections\Connection.
197
     */
198
    protected function setConnection(Connection $connection)
199
    {
200
        self::$_connection = $connection;
0 ignored issues
show
Documentation Bug introduced by
It seems like $connection of type object<Opeyemiabiodun\Po...Connections\Connection> is incompatible with the declared type object<Opeyemiabiodun\Po...Connections\Connection> of property $_connection.

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...
201
    }
202
203
    protected function setProperties($array)
204
    {
205
        foreach (self::$_attributes as $key => $value) {
206
207
            if (isset($array[$key])) {
208
                self::$_attributes[$key] = $array[$key];
209
            }
210
211
        }
212
    }
213
214
    /**
215
     * Sets the model's table.
216
     *
217
     * @param string $table An existing table in the database.
218
     */
219
    protected function setTable($table)
220
    {
221
        if (gettype($table) !== 'string') {
222
            throw new InvalidArgumentException("The parameter {$table} is not a string. A string is required instead.");
223
        }
224
225
        self::$_table = $table;
226
227
        $columns = self::$_connection->getColumns($table);
228
229
        for ($i = 0; $i < count($columns); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
230
            self::$_attributes[$columns[$i]["column_name"]] = null;
231
        }
232
233
        self::$_primaryKey = self::$_connection->getPrimaryKey($table);
234
    }
235
}
236