Passed
Branch master (d0fe65)
by Daniel
02:31
created

DomBasicComponentsByDanielGP::setPagination()   F

Complexity

Conditions 15
Paths 480

Size

Total Lines 89

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
nc 480
nop 4
dl 0
loc 89
rs 2.2176
c 0
b 0
f 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
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * DOM component functions
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait DomBasicComponentsByDanielGP
37
{
38
39
    use CommonLibLocale;
40
41
    private function buildAttributesForTag($features)
42
    {
43
        if (!is_array($features)) {
44
            return '';
45
        }
46
        $attributes = '';
47
        foreach ($features as $key => $value) {
48
            $val        = $this->buildAttributesForTagValueArray($value);
49
            $attributes .= ' ' . $key . '="' . $val . '"';
50
        }
51
        return $attributes;
52
    }
53
54
    private function buildAttributesForTagValueArray($value)
55
    {
56
        $val = $value;
57
        if (is_array($value)) {
58
            $valA = [];
59
            foreach ($value as $key2 => $value2) {
60
                $valA[] = $key2 . ':' . $value2;
61
            }
62
            $val = implode(';', $valA) . ';';
63
        }
64
        return $val;
65
    }
66
67
    /**
68
     * Capatalize first letter of each word
69
     * AND filters only letters and numbers
70
     *
71
     * @param string $givenString
72
     * @return string
73
     */
74
    protected function cleanStringForId($givenString)
75
    {
76
        return preg_replace("/[^a-zA-Z0-9]/", '', ucwords($givenString));
77
    }
78
79
    /**
80
     * Cleans a string for certain internal rules
81
     *
82
     * @param string $urlString
83
     * @return string
84
     */
85
    protected function setCleanUrl($urlString)
86
    {
87
        $arrayToReplace = [
88
            '&#038;'    => '&amp;',
89
            '&'         => '&amp;',
90
            '&amp;amp;' => '&amp;',
91
            ' '         => '%20',
92
        ];
93
        $kys            = array_keys($arrayToReplace);
94
        $vls            = array_values($arrayToReplace);
95
        return str_replace($kys, $vls, filter_var($urlString, FILTER_SANITIZE_URL));
96
    }
97
98
    /**
99
     * Returns a div tag that clear any float
100
     *
101
     * @param integer $height
102
     */
103
    protected function setClearBoth1px($height = 1)
104
    {
105
        $divStyle = implode('', [
106
            'height:' . $height . 'px;',
107
            'line-height:' . $height . 'px;',
108
            'float:none;',
109
            'clear:both;',
110
            'margin:0px;'
111
        ]);
112
        return $this->setStringIntoTag('&nbsp;', 'div', ['style' => $divStyle]);
113
    }
114
115
    /**
116
     * Builds a structured modern message
117
     *
118
     * @param string $sType
119
     * @param string $sTitle
120
     * @param string $sMsg
121
     * @param boolean $skipBr
122
     */
123
    protected function setFeedbackModern($sType, $sTitle, $sMsg, $skipBr = false)
124
    {
125
        if ($sTitle == 'light') {
126
            return $sMsg;
127
        }
128
        $legend = $this->setStringIntoTag($sTitle, 'legend', ['style' => $this->setFeedbackStyle($sType)]);
129
        return implode('', [
130
            ($skipBr ? '' : '<br/>'),
131
            $this->setStringIntoTag($legend . $sMsg, 'fieldset', ['style' => $this->setFeedbackStyle($sType)]),
132
        ]);
133
    }
134
135
    private function setFeedbackStyle($sType)
136
    {
137
        $styleKnown = [
138
            'alert' => $this->setFeedbackStyleArray('orange', 'navy'),
139
            'check' => $this->setFeedbackStyleArray('green', 'white'),
140
            'error' => $this->setFeedbackStyleArray('red', 'yellow'),
141
            'info'  => $this->setFeedbackStyleArray('black', 'white'),
142
        ];
143
        return $styleKnown[$sType];
144
    }
145
146
    private function setFeedbackStyleArray($color1, $color2)
147
    {
148
        return [
149
            'Title' => 'margin-top:-5px;margin-right:20px;padding:5px;background-color:' . $color1
150
            . ';color:' . $color2 . 'border:medium solid ' . $color1 . ';',
151
            'Msg'   => 'display:inline;padding-right:5px;padding-bottom:5px;background-color:' . $color2
152
            . ';color:' . $color1 . ';border:medium solid ' . $color1 . ';',
153
        ];
154
    }
155
156
    /**
157
     * Sets the gzip footer for HTML
158
     */
159
    protected function setFooterGZiped()
160
    {
161
        if (extension_loaded('zlib')) {
162
            return $this->setGZipedUnsafe('Footer');
163
        }
164
        return '';
165
    }
166
167
    private function setGZipedUnsafe($outputType)
168
    {
169
        $this->initializeSprGlbAndSession();
170
        if (!is_null($this->tCmnRequest->server->get('HTTP_ACCEPT_ENCODING'))) {
171
            return '';
172
        } elseif (strstr($this->tCmnRequest->server->get('HTTP_ACCEPT_ENCODING'), 'gzip')) {
173
            $this->setGZipedUnsafeWithGzipEnabled($outputType);
174
        }
175
    }
176
177
    private function setGZipedUnsafeWithGzipEnabled($outputType)
178
    {
179
        if ($outputType === 'Footer') {
180
            $gzipCntntOriginal = ob_get_contents();
181
            ob_end_clean();
182
            $gzipCntnt         = gzcompress($gzipCntntOriginal, 9);
183
            echo "\x1f\x8b\x08\x00\x00\x00\x00\x00" . substr($gzipCntnt, 0, strlen($gzipCntnt) - 4)
184
            . pack('V', crc32($gzipCntntOriginal)) . pack('V', strlen($gzipCntntOriginal));
185
        } elseif ($outputType === 'Header') {
186
            ob_start();
187
            ob_implicit_flush(0);
188
            header('Content-Encoding: gzip');
189
        }
190
    }
191
192
    /**
193
     * Sets the gzip header for HTML
194
     */
195
    protected function setHeaderGZiped()
196
    {
197
        if (extension_loaded('zlib')) {
198
            return $this->setGZipedUnsafe('Header');
199
        }
200
        return '';
201
    }
202
203
    /**
204
     * Sets the no-cache header
205
     */
206
    protected function setHeaderNoCache($contentType = 'application/json')
207
    {
208
        header("Content-Type: " . $contentType . "; charset=utf-8");
209
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
210
        header("Cache-Control: no-store, no-cache, must-revalidate");
211
        header("Cache-Control: post-check=0, pre-check=0", false);
212
        header("Pragma: no-cache");
213
    }
214
215
    /**
216
     * Returns a pagination bar
217
     *
218
     * @param int $iCrtPgNo
219
     * @param int $iRecPrPg
220
     * @param int $iAllRec
221
     * @param boolean $bKpFlPg
222
     * returns string
223
     */
224
    public function setPagination($iCrtPgNo, $iRecPrPg, $iAllRec, $bKpFlPg = true)
225
    {
226
        $sReturn             = null;
227
        $iRecPrPg            = min($iRecPrPg, $iAllRec);
228
        $iStartingPageRecord = $this->setStartingPageRecord(
229
            $iCrtPgNo, $iRecPrPg, $iAllRec, $bKpFlPg);
230
        if (APP_INDICATIVE == 'cs') {
0 ignored issues
show
Bug introduced by
The constant danielgp\common_lib\APP_INDICATIVE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
231
            $prvMsg = 'Previous';
0 ignored issues
show
Unused Code introduced by
The assignment to $prvMsg is dead and can be removed.
Loading history...
232
        } else {
233
            $prvMsg = 'Anterioara';
234
        }
235
        $sReturn .= '<span style="float:left;font-size:smaller; '
236
            . 'margin-top:1px; margin-right:1px;">'
237
            . $this->setStringIntoTag($iAllRec, 'b')
238
            . $this->lclMsgCntrl('i18n_RecordsAvailableNowDisplaying')
0 ignored issues
show
Bug introduced by
The method lclMsgCntrl() does not exist on danielgp\common_lib\DomBasicComponentsByDanielGP. Did you maybe mean lclMsgCmn()? ( Ignorable by Annotation )

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

238
            . $this->/** @scrutinizer ignore-call */ lclMsgCntrl('i18n_RecordsAvailableNowDisplaying')

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...
239
            . $this->setStringIntoTag(($iStartingPageRecord + 1), 'b')
240
            . ' - ' . $this->setStringIntoTag(
241
                min($iAllRec, ($iStartingPageRecord + $iRecPrPg)), 'b')
242
            . ' </span>';
243
        switch ($iCrtPgNo) {
244
            case 'first':
245
                $iCrtPgNo = ceil(($iStartingPageRecord + 1 ) / $iRecPrPg);
246
                break;
247
            case 'last':
248
                $iCrtPgNo = ceil($iAllRec / $iRecPrPg);
249
                break;
250
        }
251
        $sReturn              .= '<span style="float:right;font-size:smaller; '
252
            . 'margin-top:1px; margin-right:1px;">';
253
        $iNumberOfPages       = ceil($iAllRec / $iRecPrPg);
254
        $sAdditionalArguments = '';
255
        if (isset($_GET)) {
256
            if ($_GET != ['page' => @$_GET['page']]) {
257
                $sAdditionalArguments = '&amp;'
258
                    . $this->setArrayToStringForUrl('&amp;'
0 ignored issues
show
Bug introduced by
It seems like setArrayToStringForUrl() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

258
                    . $this->/** @scrutinizer ignore-call */ setArrayToStringForUrl('&amp;'
Loading history...
259
                        , $_GET, ['page', 'action', 'server_action']);
260
            }
261
            if (isset($_GET['page'])) {
262
                $iCrtPgNo = $_GET['page'];
263
            }
264
        }
265
        if ($iCrtPgNo != 1) {
266
            $sReturn .= $this->setStringIntoTag($this->lclMsgCntrl('i18n_Previous'), 'a', [
267
                'href'  => ('?page=' . ($iCrtPgNo - 1 ) . $sAdditionalArguments ),
268
                'class' => 'pagination'
269
            ]);
270
        } else {
271
            $sReturn .= $this->setStringIntoTag($this->lclMsgCntrl('i18n_Previous'), 'span', [
272
                'class' => 'pagination_inactive'
273
            ]);
274
        }
275
        for ($counter = 1; $counter <= $iNumberOfPages; $counter++) {
276
            $pages2display[$counter] = $counter;
277
        }
278
        $sReturn .= '<span class="pagination"><form method="get" action="'
279
            . $_SERVER['SCRIPT_NAME'] . '">';
280
        $sReturn .= $this->setArrayToSelect($pages2display, @$_REQUEST['page']
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pages2display does not seem to be defined for all execution paths leading up to this point.
Loading history...
Bug introduced by
It seems like setArrayToSelect() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

280
        $sReturn .= $this->/** @scrutinizer ignore-call */ setArrayToSelect($pages2display, @$_REQUEST['page']
Loading history...
281
            , 'page', ['size' => 1, 'autosubmit', 'id_no' => mt_rand()]);
282
        if (isset($_GET)) {
283
            foreach ($_GET as $key => $value) {
284
                if ($key != 'page') {
285
                    if (is_array($value)) {
286
                        foreach ($value as $value2) {
287
                            $sReturn .= $this->setStringIntoShortTag('input'
288
                                , ['type'  => 'hidden'
289
                                , 'name'  => $key . '[]'
290
                                , 'value' => $value2]);
291
                        }
292
                    } else {
293
                        $sReturn .= $this->setStringIntoShortTag('input'
294
                            , ['type'  => 'hidden', 'name'  => $key
295
                            , 'value' => $value]);
296
                    }
297
                }
298
            }
299
        }
300
        $sReturn .= '</form></span>';
301
        if ($iCrtPgNo != $iNumberOfPages) {
302
            $sReturn .= $this->setStringIntoTag($this->lclMsgCntrl('i18n_Next'), 'a', [
303
                'href'  => ('?page=' . ($iCrtPgNo + 1 ) . $sAdditionalArguments ),
304
                'class' => 'pagination'
305
            ]);
306
        } else {
307
            $sReturn .= $this->setStringIntoTag($this->lclMsgCntrl('i18n_Next'), 'span', [
308
                'class' => 'pagination_inactive'
309
            ]);
310
        }
311
        $sReturn .= '</span>';
312
        return $sReturn;
313
    }
314
315
    /**
316
     * Returns starting records for LIMIT clause on SQL interrogation
317
     *
318
     * @version 20080521
319
     * @param string $sDefaultPageNo
320
     * @param int $iRecordsPerPage
321
     * @param int $iAllRecords
322
     * @param boolean $bKeepFullPage
323
     * @return int
324
     */
325
    public function setStartingPageRecord($sDefaultPageNo, $iRecordsPerPage
326
        , $iAllRecords, $bKeepFullPage = true)
327
    {
328
        if (isset($_REQUEST['page'])) {
329
            $iStartingPageRecord = ($_REQUEST['page'] - 1 ) * $iRecordsPerPage;
330
        } else {
331
            switch ($sDefaultPageNo) {
332
                case 'last':
333
                    $iStartingPageRecord = $iAllRecords - $iRecordsPerPage;
334
                    break;
335
                case 'first':
336
                default:
337
                    $iStartingPageRecord = 0;
338
                    break;
339
            }
340
        }
341
        if (($bKeepFullPage ) && (($iStartingPageRecord + $iRecordsPerPage ) > $iAllRecords)) {
342
            $iStartingPageRecord = $iAllRecords - $iRecordsPerPage;
343
        }
344
        return max(0, $iStartingPageRecord);
345
    }
346
347
    /**
348
     * Puts a given string into a specific short tag
349
     *
350
     * @param string $sTag
351
     * @param array $features
352
     * @return string
353
     */
354
    protected function setStringIntoShortTag($sTag, $features = null)
355
    {
356
        return '<' . $sTag . $this->buildAttributesForTag($features)
357
            . (isset($features['dont_close']) ? '' : '/') . '>';
358
    }
359
360
    /**
361
     * Puts a given string into a specific tag
362
     *
363
     * @param string $sString
364
     * @param string $sTag
365
     * @param array $features
366
     * @return string
367
     */
368
    protected function setStringIntoTag($sString, $sTag, $features = null)
369
    {
370
        return '<' . $sTag . $this->buildAttributesForTag($features) . '>' . $sString . '</' . $sTag . '>';
371
    }
372
373
    protected function setViewModernLinkAdd($identifier, $ftrs = null)
374
    {
375
        $btnText     = '<i class="fa fa-plus-square">&nbsp;</i>' . '&nbsp;' . $this->lclMsgCmn('i18n_AddNewRecord');
376
        $tagFeatures = [
377
            'href'  => $this->setViewModernLinkAddUrl($identifier, $ftrs),
378
            'style' => 'margin: 5px 0px 10px 0px; display: inline-block;',
379
        ];
380
        return $this->setStringIntoTag($btnText, 'a', $tagFeatures);
381
    }
382
383
    protected function setViewModernLinkAddInjectedArguments($ftrs = null)
384
    {
385
        $sArgmnts = '';
386
        if (isset($ftrs['injectAddArguments'])) {
387
            foreach ($ftrs['injectAddArguments'] as $key => $value) {
388
                $sArgmnts .= '&amp;' . $key . '=' . $value;
389
            }
390
        }
391
        return $sArgmnts;
392
    }
393
394
    protected function setViewModernLinkAddUrl($identifier, $ftrs = null)
395
    {
396
        $sArgmnts  = $this->setViewModernLinkAddInjectedArguments($ftrs);
397
        $this->initializeSprGlbAndSession();
398
        $addingUrl = $this->tCmnRequest->server->get('PHP_SELF') . '?view=add_' . $identifier . $sArgmnts;
399
        if (!isset($ftrs['NoAjax'])) {
400
            $addingUrl = 'javascript:loadAE(\'' . $addingUrl . '\');';
401
        }
402
        return $addingUrl;
403
    }
404
405
}
406