Completed
Push — master ( 0667de...953996 )
by Christopher
69:25 queued 54:26
created

Potato::getAll()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 5
Ratio 23.81 %

Importance

Changes 11
Bugs 1 Features 3
Metric Value
c 11
b 1
f 3
dl 5
loc 21
rs 9.0534
cc 4
eloc 12
nc 4
nop 1
1
<?php
2
3
namespace Ganga\Potato;
4
5
use ReflectionClass;
6
use PDO;
7
8
/**
9
 * Class that defines Potato ORM
10
 * Will be extended by Model Classes
11
 */
12
class Potato
13
{
14
    protected $tableName;
15
    protected static $id = null;
16
    protected static $table;
17
18
    /**
19
     * Constructor
20
     * TableName is set when the class is extended
21
     */
22
    public function __construct()
23
    {
24
        /**
25
         * Tests if the Model has defined a table name
26
         * if not it assigns it to the name of the class
27
         */
28
        if (!$this->tableName) {
29
            $ref = new ReflectionClass($this);
30
            $tableName = strtolower($ref->getShortName()).'s';
31
        }
32
33
        // Test if table exists else throw an exception
34
        if (!self::tableExists($tableName)) {
35
            throw new PotatoException("Table $tableName does not exist.");
36
        } else {
37
            $this->tableName = $tableName;
0 ignored issues
show
Bug introduced by
The variable $tableName 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...
38
            self::$table = $tableName;
39
        }
40
    }
41
42
    /**
43
     * Checks if a given table exists in the database
44
     * @param  string $tableName name of the table to be checked
45
     * @return bool           true if table is found, false otherwise
46
     */
47
    public static function tableExists($tableName)
48
    {
49
        $query = "SELECT 1 FROM $tableName LIMIT 1";
50
51
        try {
52
            $result = Connection::db()->query($query);
53
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Ganga\Potato\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
54
            return false;
55
        }
56
57
        return $result !== false;
58
    }
59
60
    /**
61
     * Get the name of the current table
62
     * @return String table name
63
     */
64
    public function getTableName()
65
    {
66
        return $this->tableName;
67
    }
68
69
    /**
70
     * Getting table names from a class
71
     * This is important when no instance of the class is defined
72
     * Like User::getAll()
73
     * @return string table name
74
     */
75
    public static function getTableNameFromClass()
76
    {
77
        $instance = new static();
78
        $ref = new ReflectionClass($instance);
79
        $name = $ref->getShortName();
80
        $table = strtolower($name) . 's';
81
82
        if (!self::tableExists($table)) {
83
            throw new PotatoException("Table $table does not exist.");
84
        }
85
86
        return $table;
87
    }
88
89
    /**
90
     * Get all records from the record table
91
     * @param array $fields array of fields to be retrieved
92
     * @return array associative array of the records received from the database
93
     */
94
    public static function getAll($fields = null)
95
    {
96
        $table = self::getTableNameFromClass();
97
98 View Code Duplication
        if ($fields != null && is_array($fields)) {
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...
99
            $query =  "SELECT ". implode(', ', $fields) ." FROM $table";
100
        } else {
101
            $query = "SELECT * FROM $table";
102
        }
103
104
        $res = [];
105
106
        $results = Connection::db()->query($query);
107
        $results->setFetchMode(PDO::FETCH_ASSOC);
108
109
        while ($row = $results->fetch()) {
110
            array_push($res, $row);
111
        }
112
113
        return $res;
114
    }
115
116
    /**
117
     * Get one record from the table based on the id provided
118
     * @param  integer $id id of the record to be retrieved
119
     * @param array $fields array of fields to be retrieved
120
     * @return array     associative array of the record retrieved
121
     */
122
    public static function getOne($id, $fields = null)
123
    {
124
        $table = self::getTableNameFromClass();
125
126 View Code Duplication
        if ($fields != null && is_array($fields)) {
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...
127
            $query = "SELECT ". implode(', ', $fields) ." FROM $table WHERE id = $id";
128
        } else {
129
            $query = "SELECT * FROM $table WHERE id = $id";
130
        }
131
132
        $res = [];
133
134
        $results = Connection::db()->query($query);
135
        $results->setFetchMode(PDO::FETCH_ASSOC);
136
137
        while ($row = $results->fetch()) {
138
            array_push($res, $row);
139
        }
140
141
        if (!empty($res)) {
142
            return $res;
143
        } else {
144
            throw new PotatoException('There is no user with id '. $id);
145
        }
146
    }
147
148
    /**
149
     * Get table column names
150
     * @return array array containing the table column names
151
     */
152
    public function getColumnNames()
153
    {
154
        $query = "SELECT * from $this->tableName limit 1";
155
        $result = Connection::db()->query($query);
156
        $fields = array_keys($result->fetch(PDO::FETCH_ASSOC));
157
        return $fields;
158
    }
159
160
    /**
161
     * Save either a new or existing record
162
     * @return integer 1 is successful, 0 if false
163
     */
164
    public function save()
165
    {
166
        $columnNames = $this->getColumnNames();
167
        $availableColumnNames = [];
168
        $availableColumnValues = [];
169
170
        foreach ($columnNames as $columnName) {
171
            if (isset($this->{$columnName})) {
172
                array_push($availableColumnNames, $columnName);
173
                array_push($availableColumnValues, $this->{$columnName});
174
            }
175
        }
176
177
        if (!self::$id) {
178
            // new record so we insert
179
            $query = "INSERT INTO $this->tableName (".implode(", ", $availableColumnNames).") VALUES(";
180
181
            for ($i = 0; $i < count($availableColumnNames); $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...
182
                $query .= "?";
183
184
                if ($i != count($availableColumnNames) - 1) {
185
                    $query .= ",";
186
                }
187
            }
188
189
            $query .= ");";
190
191
            $insert = Connection::db()->prepare($query);
192
            $insert->execute($availableColumnValues);
193
        } else {
194
            // existing record, se we update
195
            $query = "UPDATE $this->tableName SET ";
196
197
            for ($i = 0; $i < count($availableColumnNames); $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...
198
                $prop = $availableColumnNames[$i];
199
                $query .= " $prop = '". $this->{$prop}."'";
200
201
                if ($i != count($availableColumnNames) - 1) {
202
                    $query .= ",";
203
                }
204
            }
205
206
            $query .= " WHERE id = ".self::$id;
207
        }
208
209
        $result = Connection::db()->query($query);
210
211
        if (!$result) {
212
            return 0;
213
        } else {
214
            return 1;
215
        }
216
    }
217
218
    /**
219
     * Find a record by id and change static id param
220
     * @param  int $id id of the record to be found
221
     * @return ClassInstance     an instance of the TableClass so that properties can be assigned automatically
222
     */
223
    public static function find($id)
224
    {
225
        self::getOne($id);
226
        self::$id = $id;
227
        return new static();
228
    }
229
230
    /**
231
     * Delete a record by id from the table in context
232
     * @param  id $id the id of the record to be deleted
233
     * @return [type]     [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
234
     */
235
    public static function destroy($id)
236
    {
237
        $table = self::getTableNameFromClass();
238
239
        self::getOne($id);
240
241
        $query = "DELETE FROM $table WHERE id = ".$id;
242
243
        try {
244
            Connection::db()->query($query);
245
            return true;
246
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Ganga\Potato\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
247
            return false;
248
        }
249
    }
250
}
251