Completed
Push — master ( fd261f...f30db2 )
by Adeola
02:28
created

DataBaseModel::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0625

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 9
ccs 6
cts 8
cp 0.75
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
crap 2.0625
1
<?php
2
3
/**
4
 * Class DataBaseModel:
5
 * This is an abstract class which stands as a model
6
 * to another class e.g User class which can inherit from
7
 * all its methods. This class stands as a middle man
8
 * between the User class and the DataBaseQuery class.
9
 *
10
 * @author: Raimi Ademola <[email protected]>
11
 * @copyright: 2016 Andela
12
 */
13
namespace Demo;
14
15
use Doctrine\Common\Inflector\Inflector;
16
17
abstract class DataBaseModel implements DataBaseModelInterface
18
{
19
    protected $tableName;
20
    protected $dataBaseConnection;
21
    protected $DataBaseQuery;
22
    protected $properties;
23
    protected $arrayField = [];
24
25
    /**
26
     * This is a constructor; a default method  that will be called automatically during class instantiation.
27
     */
28 24
    public function __construct($dbConn = null)
29
    {
30 24
        if (is_null($dbConn)) {
31
            $dbConn = $this->dataBaseConnection;
32
        }    
33 24
        $this->tableName = self::getClassName();
34 24
        $this->DataBaseQuery = new DataBaseQuery($dbConn);
35 24
        $this->arrayField['id'] = 0;
36 24
    }
37
38
    /**
39
     * The magic setter method.
40
     *
41
     * @param $properties
42
     * @param $values
43
     *
44
     * @return array associative array properties
45
     */
46
    public function __set($properties, $values)
47
    {
48
        $this->arrayField[$properties] = $values;
49
    }
50
51
    /**
52
     * The magic getter method.
53
     *
54
     * @param $properties
55
     *
56
     * @return array key
57
     */
58
    public function __get($properties)
59
    {
60
        return $this->arrayField[$properties];
61
    }
62
63
    /**
64
     * This method gets all the record from a particular table
65
     * by accessing the read method from the DataBaseQuery class.
66
     *
67
     * @throws NoDataFoundException
68
     *
69
     * @return associative array
70
     */
71 6
    public static function getAll($dbConn = null)
72
    {
73 6
        if (is_null($dbConn)) {
74
            $dbConn = $this->dataBaseConnection;
0 ignored issues
show
Bug introduced by
The variable $this 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...
75
        }
76 6
        $sqlData = DataBaseQuery::read($id = false, self::getClassName(), $dbConn);
77
78 3
        if (count($sqlData) > 0) {
79 3
            return $sqlData;
80
        }
81
82
        throw new NoDataFoundException('There is no data to display');
83
    }
84
85
    /**
86
     * This method either create or update record in a database table
87
     * by calling either the read method or create method in the
88
     * DataBaseQuery class.
89
     *
90
     * @throws NoRecordUpdateException
91
     * @throws EmptyArrayException
92
     * @throws NoRecordCreatedException
93
     *
94
     * @return bool true or false;
95
     */
96 2
    public function save($dbConn = null)
97
    {
98
        if (is_null($dbConn)) {
99
            $dbConn = $this->dataBaseConnection;
100
        }
101
        if ($this->arrayField['id']) {
102
            $sqlData = DataBaseQuery::read($this->arrayField['id'], self::getClassName(), $dbConn);
103 2
            if ($this->checkIfRecordIsEmpty($sqlData)) {
104
                $boolCommit = $this->DataBaseQuery->update(['id' => $this->arrayField['id']], $this->arrayField, self::getClassName(), $dbConn);
105
                if ($boolCommit) {
106
                    return true;
107
                }
108
109
                throw new NoRecordUpdatedException('oops, your record did not update succesfully');
110
            }
111
112
            throw new EmptyArrayException("data passed didn't match any record");
113
        }
114
115
        $boolCommit = $this->DataBaseQuery->create($this->arrayField, self::getClassName(), $dbConn);
116
        if ($boolCommit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $boolCommit of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
117
            
118
            return true;
119
        }
120
121
        throw new NoRecordCreatedException('oops,your record did not create succesfully');
122
    }
123
124
    /**
125
     * This method find a record by id.
126
     *
127
     * @param $id
128
     *
129
     * @throws ArgumentNumberIncorrectException
130
     * @throws ArgumentNotFoundException
131
     *
132
     * @return object
133
     */
134
    public static function findById($id)
135
    {
136
        $numArgs = func_num_args();
137
        if ($numArgs > 1) {
138
            throw new ArgumentNumberIncorrectException('Please input just one Argument');
139
        }
140
        if ($numArgs == '') {
141
            throw new ArgumentNotFoundException('No Argument found, please input an argument');
142
        }
143
144
        $staticFindInstance = new static();
145
        $staticFindInstance->id = $id == '' ? false : $id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Demo\DataBaseModel>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
146
147
        return $staticFindInstance;
148
    }
149
150
    /**
151
     * This method find a record by id and returns
152
     * all the data present in the id.
153
     *
154
     *
155
     * @return associative array
156
     */
157
    public function getById($dbConn = null)
158
    {
159
        if (is_null($dbConn)) {
160
            $dbConn = $this->dataBaseConnection;
161
        }
162
        if ($this->arrayField['id']) {
163
            $sqlData = DataBaseQuery::read($this->arrayField['id'], self::getClassName(), $dbConn);
164
165
            return $sqlData;
166
        }
167
    }
168
169
    /**
170
     * This method delete a row from the table by the row id.
171
     *
172
     * @param $id
173
     *
174
     * @throws ArgumentNumberIncorrectException;
175
     * @throws ArgumentNotFoundException;
176
     *
177
     * @return bool true
178
     */
179 3
    public static function destroy($id, $dbConn)
180
    {
181 3
        if (is_null($dbConn)) {
182
            $dbConn = $this->dataBaseConnection;
0 ignored issues
show
Bug introduced by
The variable $this 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...
183
        }
184 3
        $numArgs = func_num_args();
185 3
        if ($numArgs < 0 || $numArgs > 2) {
186
            throw new ArgumentNumberIncorrectException('Please input just one Argument');
187
        }
188 3
        if ($numArgs == ' ') {
189
            throw new ArgumentNotFoundException('No Argument found, please input an argument');
190
        }
191 3
        $sqlData = DataBaseQuery::read($id, self::getClassName(), $dbConn);
0 ignored issues
show
Unused Code introduced by
$sqlData 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...
192 3
        $sqlData = DataBaseQuery::delete($id, self::getClassName(), $dbConn);
0 ignored issues
show
Unused Code introduced by
$sqlData 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...
193
194 3
        return true;
195
    }
196
197 24
    public static function getClassName()
198
    {
199 24
        $tableName = explode('\\', get_called_class());
200
201 24
        return Inflector::pluralize(strtolower(end($tableName)));
202
    }
203
204
    /**
205
     * This method check if the argument passed to this function is an array.
206
     *
207
     * @param $arrayOfRecord
208
     *
209
     * @return bool true
210
     */
211 6
    public function checkIfRecordIsEmpty($arrayOfRecord)
212
    {
213 6
        if (count($arrayOfRecord) > 0) {
214 3
            return true;
215
        }
216
217 3
        return false;
218
    }
219
220
    /**
221
     * This method check if the argument passed to this function is an array.
222
     *
223
     * @param $arrayOfRecord
224
     *
225
     * @return bool true
226
     */
227
    public function checkIfRecordExist($arrayOfRecord)
228
    {
229
        $stringValue = [];
230
        foreach ($arrayOfRecord as $key => $val) {
231
            $stringValue[] = $val;
232
        }
233
    }
234
}
235