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

ObjectTrait::getModel()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 3
nop 2
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) {
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
98 39
        if (! is_object($table)) {
99 36
            $newTable = $this->getClassTableName($table, $isForeignKey);
100 36
            $newModel = new $newTable;
101 36
        }
102
103 39
        $newTable = $this->getModelTableName($newModel);
104
105 39
        return [ strtolower($newTable), $newModel ];
106
    }
107
108
    /**
109
     * Returns the values from the model's properties.
110
     *
111
     * @param  \CI_Model|\Rougin\Wildfire\CodeigniterModel $model
112
     * @return array
113
     */
114 30
    protected function getModelProperties($model)
115
    {
116 30
        $properties = [ 'column' => [], 'hidden' => [] ];
117
118 30
        if (method_exists($model, 'getColumns')) {
119 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...
120 30
        } elseif (property_exists($model, 'columns')) {
121
            // NOTE: To be removed in v1.0.0
122 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...
123 3
        }
124
125
        // NOTE: To be removed in v1.0.0 (if condition only)
126 30
        if (method_exists($model, 'getHiddenColumns')) {
127 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...
128 30
        }
129
130 30
        return $properties;
131
    }
132
133
    /**
134
     * Gets the table name specified in the model.
135
     * NOTE: To be removed in v1.0.0
136
     *
137
     * @param  string|null|object $model
138
     * @return string
139
     */
140 39
    protected function getModelTableName($model)
141
    {
142 39
        if (method_exists($model, 'getTableName')) {
143 39
            return $model->getTableName();
144
        }
145
146 3
        if (property_exists($model, 'table')) {
147 3
            return $model->table;
148
        }
149
150
        return '';
151
    }
152
153
    /**
154
     * Returns the values from the model's properties.
155
     *
156
     * @param  \CI_Model|\Rougin\Wildfire\CodeigniterModel $model
157
     * @param  array                                       $properties
158
     * @return array
159
     */
160 30
    public function getRelationshipProperties($model, array $properties)
161
    {
162 30
        if (method_exists($model, 'getBelongsToRelationships')) {
163 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...
164 18
        }
165
166 30
        if (method_exists($model, 'getRelationships')) {
167 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...
168 18
        }
169
170 30
        $belongsTo = [];
171
172 30
        if (isset($properties['with']) && isset($properties['belongs_to'])) {
173 18
            foreach ($properties['belongs_to'] as $item) {
174 18
                if (! in_array($item, $properties['with'])) {
175 15
                    continue;
176
                }
177
178 3
                $ci = \Rougin\SparkPlug\Instance::create();
179
180 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...
181
182 3
                $model = new $item;
183
184 3
                array_push($belongsTo, $this->getModelTableName($model));
185 18
            }
186 18
        }
187
188 30
        $properties['belongs_to'] = $belongsTo;
189
190 30
        return $properties;
191
    }
192
193
    /**
194
     * Returns the database information of the specified table.
195
     *
196
     * @param  string $tableName
197
     * @return array
198
     */
199 30
    public function getTableInformation($tableName)
200
    {
201 30
        if (! array_key_exists($tableName, $this->tables)) {
202 24
            $tableInfo = $this->describe->getTable($tableName);
203
204 24
            $this->tables[$tableName] = $tableInfo;
205
206 24
            return $tableInfo;
207
        }
208
209 27
        return $this->tables[$tableName];
210
    }
211
212
    /**
213
     * Sets the foreign field of the column, if any.
214
     *
215
     * @param  \CI_Model               $model
216
     * @param  \Rougin\Describe\Column $column
217
     * @param  array                   $properties
218
     * @return void
219
     */
220 30
    protected function setForeignField(\CI_Model $model, Column $column, array $properties)
221
    {
222 30
        if (! $column->isForeignKey()) {
223 30
            return;
224
        }
225
226 18
        $columnName    = $column->getField();
227 18
        $foreignColumn = $column->getReferencedField();
228 18
        $foreignTable  = $column->getReferencedTable();
229
230 18
        if (in_array($foreignTable, $properties['belongs_to'])) {
231 3
            $delimiters  = [ $foreignColumn => $model->$columnName ];
232 3
            $foreignData = $this->find($foreignTable, $delimiters, true);
233 3
            $newColumn   = $this->getClassTableName($foreignTable, true);
234
235 3
            $model->$newColumn = $foreignData;
236 3
        }
237 18
    }
238
}
239