RefactorCI::run()   F
last analyzed

Complexity

Conditions 29
Paths 1060

Size

Total Lines 85
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
cc 29
eloc 54
c 8
b 0
f 0
nc 1060
nop 2
dl 0
loc 85
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
defined('BASEPATH') OR exit('No direct script access allowed');
3
4
class RefactorCI
5
{
6
  /**
7
   * [private description]
8
   * @var [type]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
9
   */
10
  private $ci;
11
12
  /**
13
   * [private description]
14
   * @var [type]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
15
   */
16
  private $primaryKey;
17
18
  /**
19
   * [public description]
20
   * @var [type]
21
   */
22
  public const PACKAGE = 'francis94c/refactor-ci';
23
24
  /**
25
   * [__construct description]
26
   * @date  2020-04-10
27
   * @param [type]     $params [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
28
   */
29
  public function __construct($params=null)
30
  {
31
    $this->ci =& get_instance();
0 ignored issues
show
Bug introduced by
The function get_instance was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

31
    $this->ci =& /** @scrutinizer ignore-call */ get_instance();
Loading history...
32
    $this->ci->load->config("refactor", false, true);
33
    $this->ci->load->splint('francis94c/jsonp', '+JSONP', null, 'jsonp');
34
35
    $this->init($params == null ? [] : $params);
36
37
    spl_autoload_register(function($name) {
38
      if ($name == 'RefactorPayload') {
39
        require(APPPATH . 'splints/' . self::PACKAGE . '/libraries/RefactorPayload.php');
0 ignored issues
show
Bug introduced by
The constant APPPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
40
        return;
41
      }
42
43
      if (file_exists(APPPATH . "payloads/$name.php")) {
44
        require(APPPATH . "payloads/$name.php");
45
        return;
46
      }
47
48
      if (file_exists(APPPATH . "libraries/refactor/$name.php")) {
49
        require(APPPATH . "libraries/refactor/$name.php"); // @deprecated
50
      }      
51
    });
52
  }
53
  /**
54
   * [init description]
55
   * @date  2019-11-02
56
   * @param array      $params [description]
57
   */
58
  public function init(array $params):void
59
  {
60
    $this->primaryKey = $params['primary_key'] ?? 'id';
61
  }
62
  /**
63
   * [load description]
64
   * @date   2019-11-02
65
   * @return RefactorCI [description]
66
   */
67
  public function load($class):RefactorCI
68
  {
69
    require_once(APPPATH.'libraries/refactor/'.$class.'.php');
0 ignored issues
show
Bug introduced by
The constant APPPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
70
    return $this;
71
  }
72
  /**
73
   * [payload description]
74
   * @date   2019-11-02
75
   * @param  string     $class  [description]
76
   * @param  [type]     $object [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
77
   * @return [type]             [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
78
   */
79
  public function payload(string $class, $object)
80
  {
81
    return (new $class($object))->toArray();
82
  }
83
  /**
84
   * [array description]
85
   * @date   2019-11-02
86
   * @param  string     $class [description]
87
   * @param  array      $array [description]
88
   * @return array             [description]
89
   */
90
  public function array(string $class, array $array):array
91
  {
92
    $refactor = new $class();
93
    $buff;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $buff seems to be never defined.
Loading history...
94
    for ($x = 0; $x < count($array); $x++) {
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...
95
      $refactor->switchPayload($array[$x]);
96
      $buff = $refactor->toArray();
97
      if ($buff != null) $array[$x] = $buff;
98
    }
99
    return $array;
100
  }
101
  /**
102
   * [run description]
103
   * @param array|string  $object   [description]
104
   * @param string        $ruleName [description]
105
   */
106
  function run(array &$object, $ruleName):void
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
107
  {
108
    if ($object == null) return;
109
    // Reolve Rules.
110
    if (is_scalar($ruleName)) {
0 ignored issues
show
introduced by
The condition is_scalar($ruleName) is always true.
Loading history...
111
      $rule = $this->ci->config->item("refactor_$ruleName");
112
    } else {
113
      // Rule was probablt passed in as an array (associative) and we support
114
      // that.
115
      $rule = is_array($ruleName) ? $ruleName : null;
116
    }
117
118
    if ($rule == null) return; // No need to go further as rule doesn't exist.
119
    // Keep
120
    if (isset($rule['keep'])) {
121
      $keys = array_keys($object);
122
      for ($x = 0; $x < count($object); $x++) {
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...
123
        if (!in_array($keys[$X], $rule['keep'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $X seems to be never defined.
Loading history...
124
          unset($object[$keys[$x]]);
125
        }
126
      }
127
    }
128
    // Unset
129
    if (isset($rule['unset'])) {
130
      $this->unset_values($object, $rule);
131
    }
132
    // Replace
133
    if (isset($rule['replace'])) {
134
      $this->replace_fields($object, $rule);
135
    }
136
    // Bools
137
    if (isset($rule['bools'])) {
138
      foreach($rule['bools'] as $boolKey) {
139
        $object[$boolKey] = $object[$boolKey] == 1 || $object[$boolKey] == 'true';
140
      }
141
    }
142
    // Cast
143
    if (isset($rule['cast']))  {
144
      $this->cast_fields($object, $rule);
145
    }
146
    // Inflate
147
    if (isset($rule['inflate'])) {
148
      foreach($rule['inflate'] as $field => $data) {
149
        $ids = json_decode($object[$field], true);
150
        if (is_scalar($ids)) {
151
          // JSON Array wasn't supplied. Let's treat it as a scaler ID.
152
          $this->ci->db->where($this->primaryKey, $ids);
153
          $query = $this->ci->db->get($data['table']);
154
          if ($query->num_rows() == 0) {
155
            $object[$field] = json_encode (json_decode ("{}"));
156
            continue;
157
          }
158
          $object[$field] = $query->result_array()[0];
159
          if (isset($data['refactor'])) $this->run($object[$field], $data['refactor']);
160
          continue;
161
        }
162
        if (isset($data['path'])) {
163
          if ($ids == null) return;
164
          $object[$field] = $ids;
165
          $this->ci->jsonp->parse($object[$field]);
166
          if (is_array($object[$field])) {
167
            $refs = $this->ci->jsonp->get_reference($data['path']);
168
            for ($x = 0; $x < count($refs); $x++) {
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...
169
              $refs[$x] = $this->inflate_value($data['table'], $refs[$x]);
170
              // Recursion
171
              if (isset($data['refactor'])) $this->run($refs[$x], $data['refactor']);
172
            }
173
          } else {
174
            $this->ci->jsonp->set($data['path'], $this->inflate_value($data['table'], $ids));
175
            // Recursion
176
            if (isset($data['refactor'])) $this->run($this->ci->jsonp->get_reference($data['path']), $data['refactor']);
0 ignored issues
show
Bug introduced by
$this->ci->jsonp->get_reference($data['path']) cannot be passed to RefactorCI::run() as the parameter $object expects a reference. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

176
            if (isset($data['refactor'])) $this->run(/** @scrutinizer ignore-type */ $this->ci->jsonp->get_reference($data['path']), $data['refactor']);
Loading history...
177
          }
178
          return;
179
        }
180
        $object[$field] = [];
181
        if ($ids == null) return;
182
        foreach($ids as $id) {
183
          $this->ci->db->where($this->primaryKey, $id);
184
          $query = $this->ci->db->get($data['table']);
185
          if ($query->num_rows() == 0) {
186
            continue;
187
          }
188
          $object[$field][] = $query->result_array()[0];
189
          // Recursion
190
          if (isset($data['refactor'])) $this->run($object[$field][count($object[$field]) - 1], $data['refactor']);
191
        }
192
      }
193
    }
194
  }
195
  private function inflate_value(string $table, $value)
196
  {
197
    $this->ci->db->where($this->primaryKey, $value);
198
    $query = $this->ci->db->get($table);
199
    return $query->num_rows() > 0 ? $query->result_array()[0] : null;
200
  }
201
  /**
202
   * [unset_values description]
203
   * @param array  $object Object to Refactor.
204
   * @param array  $rule   Rule data, containing keys to unset in  the given
205
   *                       associative array.
206
   */
207
  private function unset_values(array &$object, &$rule):void {
208
    foreach($rule['unset'] as $key) {
209
      unset($object[$key]);
210
    }
211
  }
212
  /**
213
   * [replace_fields description]
214
   * @param array  $object [description]
215
   * @param [type] $rule   [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
216
   */
217
  private function replace_fields(array &$object, &$rule):void
218
  {
219
    foreach ($rule['replace'] as $oldKey => $newKey) {
220
      $object[$newKey] = $object[$oldKey];
221
      unset($object[$oldKey]);
222
    }
223
  }
224
  /**
225
   * [cast_fields description]
226
   * @param array  $object [description]
227
   * @param [type] $rule   [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
228
   */
229
  private function cast_fields(array &$object, &$rule):void
230
  {
231
    foreach ($rule['cast'] as $key => $type) {
232
      switch ($type) {
233
        case 'int':
234
          $object[$key] = (int) $object[$key];
235
          break;
236
        case 'string':
237
          $object[$key] = (string) $object[$key];
238
          break;
239
      }
240
    }
241
  }
242
}
243
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
244