Passed
Push — main ( 657d00...0bc1d8 )
by Yasser
02:02
created

helpers.php ➔ init_rapid_paginator_cache()   C

Complexity

Conditions 12
Paths 48

Size

Total Lines 39

Duplication

Lines 5
Ratio 12.82 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
cc 12
nc 48
nop 2
dl 5
loc 39
ccs 0
cts 18
cp 0
crap 156
rs 6.9666
c 0
b 0
f 0

How to fix   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
use Illuminate\Support\Facades\Route;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Route.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
3
4
if(!function_exists('urlsafe_b64encode')){
5
    function urlsafe_b64encode($string) {
6
        $data = base64_encode($string);
7
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
8
        return $data;
9
    }
10
}
11
if(!function_exists('urlsafe_b64decode')){
12
    function urlsafe_b64decode($string) {
13
        $data = str_replace(array('-','_'),array('+','/'),$string);
14
        $mod4 = strlen($data) % 4;
15
        if ($mod4) {
16
            $data .= substr('====', $mod4);
17
        }
18
        return base64_decode($data);
19
    }
20
}
21
22
if(!function_exists('init_rapid_paginator_cache')){
23
    /* This function is supposed to cache 'Form' values...
24
    *
25
    * @param  Array     $fields
26
    * @return Array     $result
27
    *
28
    */
29
    function init_rapid_paginator_cache($fields = null, $tab=1){
30
        //init cache
31
        $cache = isset($fields) ? count($fields) > 0 ? [] : null : null;
32
        
33
        if($cache == [] || $cache == null){
34
            $cache['sort'] = '>';
35
            $cache['perPage'] = '10';
36
        }
37
38
        // If form is submitted...
39
        // Cache Form values
40
        if (request()->isMethod('POST')) {
41
            foreach ($fields as $fieldName) {
0 ignored issues
show
Bug introduced by
The expression $fields of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
42
                if(request($fieldName)){
43
                    $cache[$fieldName] = request($fieldName);
44
                }
45
            }
46
        }
47
        else // else we have to retrieve old cache from the state 
48
        {
49
            $state_array = null;
50
51
            // Decode The State
52 View Code Duplication
            if(request('state') && request('tab') == $tab){
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...
53
                $state_base64 = request('state');
54
                $state_decoded = urlsafe_b64decode($state_base64);
55
                $state_array = json_decode($state_decoded,true);
56
            }
57
58
            // Append the state cache key/value pairs to the new cache...
59
            if(isset($state_array['cache'])){
60
                foreach ($state_array['cache'] as $key => $value) {
61
                    $cache[$key] = $value;
62
                }
63
            }
64
        }
65
66
        return $cache;
67
    }
68
}
69
if(!function_exists('rapid_paginator')){
70
    /* Custom pagination System Based on RapidPagination package
71
    * @param  Query     $query
72
    * @param  Array     $field
73
    * @param  Char      $sort 
74
    * @param  Integer   $sort
75
    * @param  Boolean   $seekable
76
    * @return Array     $result
77
    */
78
    function rapid_paginator($query, $field = 'id', $cache = null, $sort = '>', $perPage = 10, $tab=1, $seekable = true)
79
    {
80
        if($cache == null)
81
            init_rapid_paginator_cache(null);
82
        /*
83
        ** Setup Default values
84
        */
85
        if($sort == null)
86
            $sort = '>';
87
        else
88
            $cache['sort'] = $sort;
89
90
        if($field == null)
91
            $field = 'id';
92
        
93
        if($perPage == null)
94
            $perPage = 10;
95
        else
96
            $cache['perPage'] = $perPage;
97
    
98
        /*
99
        ** Extract Cursor from the State route parameter
100
        ** Cursor is used as a reference to navigate to the next or previous 'pages'...
101
        */
102
103
        $state_array = null;
104
105
        // Decode the State
106 View Code Duplication
        if(request('state') && request('tab') == $tab){
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...
107
            $state_base64 = request('state');
108
            $state_decoded = urlsafe_b64decode($state_base64);
109
            $state_array = json_decode($state_decoded,true);
110
        }
111
112
        $cursor = null;
113
        
114
        // Add cursor from state to the newCursor array
115
        if($state_array){
116
            if(isset($state_array['cursor'][$field]))
117
                $cursor[$field] = $state_array['cursor'][$field];
118
        }
119
        
120
121
        // Create a new paginator
122
        $paginator = $query->rapid_pagination()
123
                    ->limit($perPage); // Set Number of elements Per Page (default=10)
124
        
125
        // Sort by 'field'..
126
        if($sort == '>' || $sort == null)
127
            $paginator = $paginator->orderBy($field);
128
        else
129
            $paginator = $paginator->orderByDesc($field);
130
        
131
        // Get 'Previous Cursor' to be able to navigate backwards
132
        if($seekable)
133
            $paginator = $paginator->seekable(); 
134
135
        // If 'Next' Button is Clicked
136
        if(request()->direction == "next" || request()->direction == null){
137
            $paginator = $paginator->forward(); // Use forward method to change the direction of the navigation
138
        } 
139
        // If 'Previous' Button is Clicked
140
        else{
141
            $paginator = $paginator->backward(); // Use backward method to change the direction of the navigation
142
        }
143
144
        // Navigation rules
145
        if($cursor != null){
146
            $paginator = $paginator
147
                ->paginate($cursor);
148
        }
149
        else{
150
            $paginator = $paginator
151
                ->paginate();
152
        }
153
154
        /*
155
        ** Prepare a new State
156
        */
157
        
158
        // Extract cursors from paginator
159
        $paginatorArray = (array)$paginator;
160
        unset($paginatorArray['records']); // We don't need to encode records in the state
161
162
163
        // Next and Previous buttons have different cursors that's why we need state for every button
164
165
        // Next Btn State...
166
        $state_next = [
167
            'cursor' => $paginatorArray['nextCursor'],
168
            'cache' => $cache
169
        ];
170
171
        // Previous Btn State...
172
        $state_prev = [
173
            'cursor' => $paginatorArray['previousCursor'],
174
            'cache' => $cache
175
        ];
176
177
        // Encode States
178
        $base64_next_state = urlsafe_b64encode(json_encode($state_next));
179
        $base64_prev_state = urlsafe_b64encode(json_encode($state_prev));
180
        
181
        //Set tab id
182
        $paginator->setTabID($tab);
183
        
184
        // Set paginator previous and next Urls
185
        $paginator->makePreviousUrl($base64_prev_state);
186
        $paginator->makeNextUrl($base64_next_state);
187
188
        $result = [
189
            'items' => $paginator,
190
            'cache' => $cache
191
        ];
192
193
        return $result;
194
    }
195
}
196