Completed
Pull Request — master (#4)
by
unknown
20:46 queued 05:47
created

Model::parseWhereConditions()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 15
rs 8.8571
cc 5
eloc 11
nc 8
nop 2
1
<?php
2
3
namespace Vundi\Potato;
4
5
use Vundi\Potato\Exceptions\IDShouldBeNumber;
6
7
class Model
8
{
9
    private static $db;
10
    public $db_fields = [];
11
    public static $ID;
12
    protected static $child_class;
13
14
    public function __construct()
15
    {
16
        self::$db = new Database();
17
        self::$child_class = get_called_class();
18
    }
19
20
    /**
21
     * Will make it possible to assign key value pairs dynamically
22
     * in the child class
23
     */
24
    public function __set($key, $value)
25
    {
26
        $this->db_fields[$key] = $value;
27
    }
28
29
    /**
30
     * Save a record in the table
31
     * calls the insert method in the Database class
32
     */
33
    public function save()
34
    {
35
        $s = new static();
36
37
        return self::$db->insert($s::$entity_table, $this->db_fields);
38
    }
39
40
    /**
41
     * Update a record in the table
42
     */
43
    public function update()
44
    {
45
        $s = new static();
46
47
        $where = "id = {$s::$ID}";
48
49
        return self::$db->update($s::$entity_table, $this->db_fields, $where);
50
    }
51
52
    /**
53
     * Remove a record from the table with the specified ID
54
     * @param  in $id ID of record you want to remove
55
     */
56
    public static function remove($id)
57
    {
58
        $s = new static();
59
60
        if (is_int($id)) {
61
            $where = "id = {$id}";
62
            self::$db->delete($s::$entity_table, $where);
63
        } else {
64
            throw new IDShouldBeNumber('Pass in an ID as the parameter, ID has to be a number', 1);
65
        }
66
    }
67
68
    /**
69
     * @param  int $id ID of the record to be retrieved
70
     * @return object  Instance of the Class
71
     */
72
    public static function find($id)
73
    {
74
        // var_dump(get_called_class());
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
75
        // die();
76
        $s = new static();
77
78
        if (is_int($id)) {
79
            //Set the ID of the class instance returned to $id since during update we shall update the
80
            //record with ID that matches the id passed during find
81
            $s::$ID = $id;
82
83
            $where = "id = {$id}";
84
            self::$db->select($s::$entity_table, $where);
85
86
            return self::$db->singleObject(self::$child_class);
87
        } else {
88
            throw new IDShouldBeNumber('Find only takes a number as a parameter', 1);
89
        }
90
    }
91
92
    public static function findWhere($conditions = array(), $fields = '*', $order = '', $limit = null, $offset = '')
93
    {
94
        $s = new static();
95
        $where = self::parseWhereConditions($conditions);
96
        self::$db->select($s::$entity_table, $where, $fields, $order, $limit, $offset);
97
98
        return self::$db->objectSet(self::$child_class);
0 ignored issues
show
Unused Code introduced by
The call to Database::objectSet() has too many arguments starting with self::$child_class.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
99
    }
100
    
101
    private static function parseWhereConditions($conditions, $logicOp = '&&') {
102
        foreach ($conditions as $key => $value) {
103
            if (is_array($value)) { // support aggregating conditions with another boolean operator
104
                $where[] = '(' . self::parseWhereConditions($value, $key) . ')';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$where was never initialized. Although not strictly required by PHP, it is generally a good practice to add $where = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
105
            } elseif (is_string($value)) {
106
                $where[] = $key.' ="'.addslashes($value).'"';
0 ignored issues
show
Bug introduced by
The variable $where does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
107
            } else {
108
                $where[] = $key.' = '.$value;
109
            }
110
        }
111
        if (!is_string($logicOp)) // caller sent us an indexed array.
112
            // they probably only have 1 condition, but better safe than sorry
113
            $logicOp = '&&';
114
        return join(" $logicOp ", $where);
115
    }
116
117
    /**
118
     * Finds all records in the table
119
     * @return array
120
     */
121
    public static function findAll()
122
    {
123
        $s = new static();
124
125
        self::$db->select($s::$entity_table);
126
127
        return self::$db->objectSet();
128
    }
129
}
130