Completed
Pull Request — master (#2)
by Rougin
02:28
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  $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($newTable, $model) = $this->getModel($table, $isForeignKey);
36
37 30
        if (! array_key_exists($newTable, $this->tables)) {
38 24
            $tableInfo = $this->describe->getTable($newTable);
39
40 24
            $this->tables[$newTable] = $tableInfo;
41 24
        } else {
42 27
            $tableInfo = $this->tables[$newTable];
43
        }
44
45 30
        $properties = $this->getModelProperties($model);
0 ignored issues
show
Documentation introduced by
$model 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...
46 30
        $properties = $this->getRelationshipProperties($model, $properties);
0 ignored issues
show
Documentation introduced by
$model 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...
47
48 30
        foreach ($tableInfo as $column) {
49 30
            $key = $column->getField();
50
51 30
            $inHiddenColumns = ! empty($properties['hidden']) && in_array($key, $properties['hidden']);
52 30
            $inColumns       = ! empty($properties['columns']) && ! in_array($key, $properties['columns']);
53
54 30
            if ($inColumns || $inHiddenColumns) {
55 30
                continue;
56
            }
57
58 30
            $model->$key = $row->$key;
59
60 30
            $this->setForeignField($model, $column, $properties);
0 ignored issues
show
Documentation introduced by
$model is of type string|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...
61 30
        }
62
63 30
        return $model;
64
    }
65
66
    /**
67
     * Finds the row from the specified ID or with the list of delimiters from
68
     * the specified table.
69
     *
70
     * @param  string         $table
71
     * @param  array|integer  $delimiters
72
     * @param  boolean        $isForeignKey
73
     * @return object|boolean
74
     */
75
    abstract protected function find($table, $delimiters = [], $isForeignKey = false);
76
77
    /**
78
     * Returns the values from the model's properties.
79
     *
80
     * @param  \CI_Model|\Rougin\Wildfire\CodeigniterModel $model
81
     * @return array
82
     */
83 30
    protected function getModelProperties($model)
84
    {
85 30
        $properties = [ 'column' => [], 'hidden' => [] ];
86
87 30
        if (method_exists($model, 'getColumns')) {
88 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...
89 30
        } elseif (property_exists($model, 'columns')) {
90
            // NOTE: To be removed in v1.0.0
91 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...
92 3
        }
93
94
        // NOTE: To be removed in v1.0.0 (if condition only)
95 30
        if (method_exists($model, 'getHiddenColumns')) {
96 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...
97 30
        }
98
99 30
        return $properties;
100
    }
101
102
    /**
103
     * Returns the values from the model's properties.
104
     *
105
     * @param  \CI_Model|\Rougin\Wildfire\CodeigniterModel $model
106
     * @param  array                                       $properties
107
     * @return array
108
     */
109 30
    public function getRelationshipProperties($model, array $properties)
110
    {
111 30
        if (method_exists($model, 'getBelongsToRelationships')) {
112 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...
113 18
        }
114
115 30
        if (method_exists($model, 'getRelationships')) {
116 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...
117 18
        }
118
119 30
        $belongsTo = [];
120
121 30
        if (isset($properties['with']) && isset($properties['belongs_to'])) {
122 18
            foreach ($properties['belongs_to'] as $item) {
123 18
                if (! in_array($item, $properties['with'])) {
124 15
                    continue;
125
                }
126
127 3
                $ci = \Rougin\SparkPlug\Instance::create();
128
129 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...
130
131 3
                $model = new $item;
132
133 3
                if (method_exists($model, 'getTableName')) {
134
                    array_push($belongsTo, $model->getTableName());
135 3
                } elseif (property_exists($model, 'table')) {
136
                    // NOTE: To be removed in v1.0.0
137 3
                    array_push($belongsTo, $model->table);
138 3
                }
139 18
            }
140 18
        }
141
142 30
        $properties['belongs_to'] = $belongsTo;
143
144 30
        return $properties;
145
    }
146
147
    /**
148
     * Sets the foreign field of the column, if any.
149
     *
150
     * @param  \CI_Model               $model
151
     * @param  \Rougin\Describe\Column $column
152
     * @param  array                   $properties
153
     * @return void
154
     */
155 30
    protected function setForeignField(\CI_Model $model, Column $column, array $properties)
156
    {
157 30
        if (! $column->isForeignKey()) {
158 30
            return;
159
        }
160
161 18
        $columnName    = $column->getField();
162 18
        $foreignColumn = $column->getReferencedField();
163 18
        $foreignTable  = $column->getReferencedTable();
164
165 18
        if (in_array($foreignTable, $properties['belongs_to'])) {
166 3
            $delimiters  = [ $foreignColumn => $model->$columnName ];
167 3
            $foreignData = $this->find($foreignTable, $delimiters, true);
168 3
            $newColumn   = $this->getTableName($foreignTable, true);
169
170 3
            $model->$newColumn = $foreignData;
171 3
        }
172 18
    }
173
174
    /**
175
     * Gets the model class of the said table.
176
     *
177
     * @param  string|\CI_Model|null $table
178
     * @param  boolean               $isForeignKey
179
     * @return array
180
     */
181 39
    protected function getModel($table = null, $isForeignKey = false)
182
    {
183 39
        if (empty($table) && empty($this->table)) {
184 6
            return [ '', null ];
185
        }
186
187 39
        $newModel = $table;
188 39
        $newTable = '';
189
190 39
        if (! is_object($table)) {
191 36
            $newTable = $this->getTableName($table, $isForeignKey);
192 36
            $newModel = new $newTable;
193 36
        }
194
195 39
        if (method_exists($newModel, 'getTableName')) {
196 39
            $newTable = $newModel->getTableName();
197 39
        } elseif (property_exists($newModel, 'table')) {
198
            // NOTE: To be removed in v1.0.0
199 3
            $newTable = $newModel->table;
200 3
        }
201
202 39
        return [ strtolower($newTable), $newModel ];
203
    }
204
205
    /**
206
     * Parses the table name from Describe class.
207
     *
208
     * @param  string  $table
209
     * @param  boolean $isForeignKey
210
     * @return string
211
     */
212
    abstract protected function getTableName($table, $isForeignKey = false);
213
}
214