Completed
Pull Request — master (#2)
by Rougin
02:50
created

ObjectTrait::getModelProperties()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 6
nop 1
crap 4
1
<?php
2
3
namespace Rougin\Wildfire\Traits;
4
5
use Rougin\Describe\Column;
6
7
use Rougin\Wildfire\CodeigniterModel;
8
9
/**
10
 * Object Trait
11
 *
12
 * @package Wildfire
13
 * @author  Rougin Royce Gutib <[email protected]>
14
 *
15
 * @property \Rougin\Describe\Describe $describe
16
 * @property string                    $table
17
 */
18
trait ObjectTrait
19
{
20
    /**
21
     * @var array
22
     */
23
    protected $tables = [];
24
25
    /**
26
     * Creates an object from the specified table and row.
27
     *
28
     * @param  string|\Rougin\Wildfire\CodeigniterModel $table
29
     * @param  object                                   $row
30
     * @param  boolean                                  $isForeignKey
31
     * @return array
32
     */
33 30
    protected function createObject($table, $row, $isForeignKey = false)
34
    {
35 30
        list($tableName, $model) = $this->getModel($table, $isForeignKey);
36
37 30
        if (! $model instanceof \CI_Model) {
38
            return $model;
39
        }
40
41 30
        $properties = $this->getModelProperties($model);
42 30
        $properties = $this->getRelationshipProperties($model, $properties);
43 30
        $tableInfo  = $this->getTableInformation($tableName);
44
45 30
        foreach ($tableInfo as $column) {
0 ignored issues
show
Bug introduced by
The expression $tableInfo of type string is not traversable.
Loading history...
46 30
            $key = $column->getField();
47
48 30
            $inHiddenColumns = ! empty($properties['hidden']) && in_array($key, $properties['hidden']);
49 30
            $inColumns       = ! empty($properties['columns']) && ! in_array($key, $properties['columns']);
50
51 30
            if ($inColumns || $inHiddenColumns) {
52 30
                continue;
53
            }
54
55 30
            $model->$key = $row->$key;
56
57 30
            $this->setForeignField($model, $column, $properties);
58 30
        }
59
60 30
        return $model;
61
    }
62
63
    /**
64
     * Finds the row from the specified ID or with the list of delimiters from
65
     * the specified table.
66
     *
67
     * @param  string         $table
68
     * @param  array|integer  $delimiters
69
     * @param  boolean        $isForeignKey
70
     * @return object|boolean
71
     */
72
    abstract protected function find($table, $delimiters = [], $isForeignKey = false);
73
74
    /**
75
     * Parses the table name from Describe class.
76
     *
77
     * @param  string  $table
78
     * @param  boolean $isForeignKey
79
     * @return string
80
     */
81
    abstract protected function getClassTableName($table, $isForeignKey = false);
82
83
    /**
84
     * Gets the model class of the said table.
85
     *
86
     * @param  \Rougin\Wildfire\CodeigniterModel|string|null $table
87
     * @param  boolean                                       $isForeignKey
88
     * @return array
89
     */
90 39
    protected function getModel($table = null, $isForeignKey = false)
91
    {
92 39
        if (empty($table) && empty($this->table)) {
93 6
            return [ '', null ];
94
        }
95
96 39
        $newModel = $table;
97 39
        $newTable = '';
0 ignored issues
show
Unused Code introduced by
$newTable 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...
98
99 39
        if (! is_object($table)) {
100 36
            $newTable = $this->getClassTableName($table, $isForeignKey);
101 36
            $newModel = new $newTable;
102 36
        }
103
104 39
        $newTable = $this->getModelTableName($newModel);
0 ignored issues
show
Documentation introduced by
$newModel is of type string|null|object, but the function expects a object<CI_Model>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
105
106 39
        return [ strtolower($newTable), $newModel ];
107
    }
108
109
    /**
110
     * Returns the values from the model's properties.
111
     *
112
     * @param  \CI_Model|\Rougin\Wildfire\CodeigniterModel $model
113
     * @return array
114
     */
115 30
    protected function getModelProperties($model)
116
    {
117 30
        $properties = [ 'column' => [], 'hidden' => [] ];
118
119 30
        if (method_exists($model, 'getColumns')) {
120 30
            $properties['columns'] = $model->getColumns();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class CI_Model as the method getColumns() does only exist in the following sub-classes of CI_Model: Rougin\Wildfire\CodeigniterModel. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
121 30
        } elseif (property_exists($model, 'columns')) {
122
            // NOTE: To be removed in v1.0.0
123 3
            $properties['columns'] = $model->columns;
0 ignored issues
show
Bug introduced by
The property columns does not seem to exist in CI_Model.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
124 3
        }
125
126
        // NOTE: To be removed in v1.0.0 (if condition only)
127 30
        if (method_exists($model, 'getHiddenColumns')) {
128 30
            $properties['hidden'] = $model->getHiddenColumns();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class CI_Model as the method getHiddenColumns() does only exist in the following sub-classes of CI_Model: Rougin\Wildfire\CodeigniterModel. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
129 30
        }
130
131 30
        return $properties;
132
    }
133
134
    /**
135
     * Gets the table name specified in the model.
136
     * NOTE: To be removed in v1.0.0
137
     *
138
     * @param  \CI_Model $model
139
     * @return string
140
     */
141 39
    protected function getModelTableName($model)
142
    {
143 39
        if (method_exists($model, 'getTableName')) {
144 39
            return $model->getTableName();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class CI_Model as the method getTableName() does only exist in the following sub-classes of CI_Model: Rougin\Wildfire\CodeigniterModel. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
145
        }
146
147 3
        if (property_exists($model, 'table')) {
148 3
            return $model->table;
149
        }
150
151
        return '';
152
    }
153
154
    /**
155
     * Returns the values from the model's properties.
156
     *
157
     * @param  \CI_Model|\Rougin\Wildfire\CodeigniterModel $model
158
     * @param  array                                       $properties
159
     * @return array
160
     */
161 30
    public function getRelationshipProperties($model, array $properties)
162
    {
163 30
        if (method_exists($model, 'getBelongsToRelationships')) {
164 18
            $properties['belongs_to'] = $model->getBelongsToRelationships();
0 ignored issues
show
Bug introduced by
The method getBelongsToRelationships() does not seem to exist on object<CI_Model>.

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...
165 18
        }
166
167 30
        if (method_exists($model, 'getRelationships')) {
168 18
            $properties['with'] = $model->getRelationships();
0 ignored issues
show
Bug introduced by
The method getRelationships() does not seem to exist on object<CI_Model>.

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...
169 18
        }
170
171 30
        $belongsTo = [];
172
173 30
        if (isset($properties['with']) && isset($properties['belongs_to'])) {
174 18
            foreach ($properties['belongs_to'] as $item) {
175 18
                if (! in_array($item, $properties['with'])) {
176 15
                    continue;
177
                }
178
179 3
                $ci = \Rougin\SparkPlug\Instance::create();
180
181 3
                $ci->load->model($item);
0 ignored issues
show
Bug introduced by
The property load does not seem to exist in CI_Controller.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
182
183 3
                $model = new $item;
184
185 3
                array_push($belongsTo, $this->getModelTableName($model));
186 18
            }
187 18
        }
188
189 30
        $properties['belongs_to'] = $belongsTo;
190
191 30
        return $properties;
192
    }
193
194
    /**
195
     * Returns the database information of the specified table.
196
     *
197
     * @param  string $tableName
198
     * @return string
199
     */
200 30
    public function getTableInformation($tableName)
201
    {
202 30
        if (! array_key_exists($tableName, $this->tables)) {
203 24
            $tableInfo = $this->describe->getTable($tableName);
204
205 24
            $this->tables[$tableName] = $tableInfo;
206
207 24
            return $tableInfo;
208
        }
209
210 27
        return $this->tables[$tableName];
211
    }
212
213
    /**
214
     * Sets the foreign field of the column, if any.
215
     *
216
     * @param  \CI_Model               $model
217
     * @param  \Rougin\Describe\Column $column
218
     * @param  array                   $properties
219
     * @return void
220
     */
221 30
    protected function setForeignField(\CI_Model $model, Column $column, array $properties)
222
    {
223 30
        if (! $column->isForeignKey()) {
224 30
            return;
225
        }
226
227 18
        $columnName    = $column->getField();
228 18
        $foreignColumn = $column->getReferencedField();
229 18
        $foreignTable  = $column->getReferencedTable();
230
231 18
        if (in_array($foreignTable, $properties['belongs_to'])) {
232 3
            $delimiters  = [ $foreignColumn => $model->$columnName ];
233 3
            $foreignData = $this->find($foreignTable, $delimiters, true);
234 3
            $newColumn   = $this->getClassTableName($foreignTable, true);
235
236 3
            $model->$newColumn = $foreignData;
237 3
        }
238 18
    }
239
}
240