Completed
Push — test ( fc9274...3ae66b )
by Temitope
02:43
created

BaseModel::find()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 18
rs 8.8571
cc 5
eloc 9
nc 4
nop 1
1
<?php
2
3
/**
4
 * @package  Laztopaz\potato-ORM
5
 * @author   Temitope Olotin <[email protected]>
6
 * @license  <https://opensource.org/license/MIT> MIT
7
 */
8
9
namespace Laztopaz\potatoORM;
10
11
use Laztopaz\potatoORM\DatabaseHandler;
12
use Laztopaz\potatoORM\InterfaceBaseClass;
13
use Laztopaz\potatoORM\NoRecordDeletionException;
14
use Laztopaz\potatoORM\NoRecordFoundException;
15
use Laztopaz\potatoORM\NoRecordInsertionException;
16
use Laztopaz\potatoORM\NullArgumentPassedToFunction;
17
use Laztopaz\potatoORM\WrongArgumentException;
18
use Laztopaz\potatoORM\NoArgumentPassedToFunctionException;
19
use Laztopaz\potatoORM\EmptyArrayException;
20
21
class BaseModel  implements InterfaceBaseClass
0 ignored issues
show
Coding Style introduced by
Expected 1 space after class name; 2 found
Loading history...
Coding Style introduced by
Expected 1 space before implements keyword; 2 found
Loading history...
22
{
23
    protected $databaseModel; // Private variable that contains instance of database
24
    protected $tableName; // Class variable holding class name pluralized
25
    protected $properties = []; // Properties will later contain key, value pairs from the magic setter, getter methods
26
27
    use Inflector; // Inject the inflector trait
28
29
    public function  __construct()
30
    {
31
        $this->tableName = $this->getClassName();
32
33
        $this->databaseModel = new DatabaseHandler($this->tableName);
34
35
        $this->properties['id'] = 0;
36
    }
37
    
38
    /**
39
     * The magic getter method
40
     * @params key
41
     * @return array key
42
     */
43
    public function __get($key)
44
    {
45
        $this->properties[$key];
46
47
    }
48
    
49
    /**
50
     * The magic setter method
51
     * @params property, key
52
     * @return array associative array properties
53
     */
54
    public function  __set($property, $value)
55
    {
56
        $this->properties[$property] = $value;
57
58
    }
59
    
60
    /**
61
     * This method gets all the record from a particular table
62
     * @params void
63
     * @return associative array
64
     * @throws NoRecordFoundException
65
     */
66
    public static function getAll()
67
    {
68
        $allData = DatabaseHandler::read($id = false, self::getClassName());
69
70
        if (count($allData) > 0) {
71
            return $allData;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $allData; (array) is incompatible with the return type declared by the interface Laztopaz\potatoORM\InterfaceBaseClass::getAll of type Laztopaz\potatoORM\associative.

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...
72
73
        }
74
75
        throw NoRecordFoundException::checkNoRecordFoundException("There is no record to display");
76
77
    }
78
    
79
    /**
80
     * This method create or update record in a database table
81
     * @params void
82
     * @return bool true or false;
83
     * @throws EmptyArrayException
84
     * @throws NoRecordInsertionException
85
     * @throws NoRecordUpdateException
86
     */
87
    public function save()
88
    {
89
        $boolCommit = false;
0 ignored issues
show
Unused Code introduced by
$boolCommit 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...
90
91
        if ($this->properties['id']) {
92
            $allData = DatabaseHandler::read($id = $this->properties['id'], self::getClassName());
93
94
            if ($this->checkIfRecordIsEmpty($allData)) {
95
                $boolCommit = $this->databaseModel->update(['id' => $this->properties['id']], $this->tableName, $this->properties);
96
97
                if ($boolCommit) {
98
                    return true;
99
100
                }
101
102
                throw NoRecordUpdateException::checkNoRecordUpdateException("Record not updated successfully");
103
            }
104
105
            throw EmptyArrayException::checkEmptyArrayException("Value passed didn't match any record");
106
        }
107
108
        $boolCommit = $this->databaseModel->create($this->properties, $this->tableName);
109
110
        if ($boolCommit) {
111
            return true;
112
        }
113
114
        throw NoRecordInsertionException::checkNoRecordAddedException("Record not created successfully");
115
    }
116
117
    /**
118
     * This method find a record by id
119
     * @params int id
120
     * @return Object
121
     * @throws NoArgumentPassedToFunctionException
122
     */
123
    public static function find($id)
124
    {
125
        $num_args = (int) func_num_args(); // get number of arguments passed to
126
127
        if ($num_args == 0 || $num_args > 1) {
128
            throw NoArgumentPassedToFunctionException::checkNoArgumentPassedToFunction("Argument missing: only one argument is allowed");
129
        }
130
131
        if ($id == "") {
132
            throw NullArgumentPassedToFunction::checkNullArgumentPassedToFunction("This function expect a value");
133
        }
134
135
        $staticFindInstance = new static();
136
        $staticFindInstance->id = $id == "" ? false : $id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Laztopaz\potatoORM\BaseModel>. 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...
137
138
        return $staticFindInstance;
139
        
140
    }
141
    
142
    /**
143
     * This method delete a row from the table by the row id
144
     * @params int id
145
     * @return boolean true or false
146
     * @throws NoRecordDeletionException;
147
     */
148
    public static function destroy($id)
149
    {
150
        $boolDeleted = false;
0 ignored issues
show
Unused Code introduced by
$boolDeleted 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...
151
152
        $num_args = (int) func_num_args(); // get number of arguments passed to
153
        
154
        if ($num_args == 0 || $num_args > 1) {
155
            throw NoArgumentPassedToFunctionException::checkNoArgumentPassedToFunction("Argument missing: only one argument is allowed");
156
        }
157
158
        $boolDeleted = DatabaseHandler::delete($id, self::getClassName());
159
160
        if ($boolDeleted) {
161
            return true;
162
163
        }
164
165
        throw NoRecordDeletionException::checkNoRecordUpdateException("Record deletion unsuccessful because id does not match any record");
0 ignored issues
show
Bug introduced by
The method checkNoRecordUpdateException() does not seem to exist on object<Laztopaz\potatoOR...ecordDeletionException>.

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...
166
    }
167
168
   /**
169
    * This method return the current class name
170
    * $params void
171
    * @return classname
172
    */
173
   public static function getClassName()
174
   {
175
       $tableName = preg_split('/(?=[A-Z])/', get_called_class());
176
       
177
       $className = end($tableName);
178
179
       return self::pluralize(strtolower($className));
180
181
   }
182
   
183
   /**
184
    * This method check if the argument passed to this function is an array
185
    * @param $arrayOfRecord
186
    * @return bool
187
    */
188
    public function checkIfRecordIsEmpty($arrayOfRecord)
189
    {
190
        if (count($arrayOfRecord) > 0) {
191
            return true;
192
193
        }
194
        
195
        return false;
196
    }
197
198
}
199