Completed
Push — master ( 28949e...af97ad )
by Vítězslav
03:39
created

FlexiBee::performRequest()   F

Complexity

Conditions 18
Paths 232

Size

Total Lines 95
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 50
CRAP Score 21.9833

Importance

Changes 7
Bugs 0 Features 1
Metric Value
cc 18
eloc 64
c 7
b 0
f 1
nc 232
nop 3
dl 0
loc 95
ccs 50
cts 65
cp 0.7692
crap 21.9833
rs 3.9723

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
 * FlexiPeeHP - Třída pro práci s FlexiBee.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015,2016 Spoje.Net
7
 */
8
9
namespace FlexiPeeHP;
10
11
class FlexiBee extends \Ease\Brick
12
{
13
    /**
14
     * Základní namespace pro komunikaci s FlexiBEE.
15
     *
16
     * @var string Jmený prostor datového bloku odpovědi
17
     */
18
    public $nameSpace = 'winstrom';
19
20
    /**
21
     * Datový blok v poli odpovědi.
22
     *
23
     * @var string
24
     */
25
    public $resultField = 'results';
26
27
    /**
28
     * Verze protokolu použitého pro komunikaci.
29
     *
30
     * @var string Verze použitého API
31
     */
32
    public $protoVersion = '1.0';
33
34
    /**
35
     * Evidence užitá objektem.
36
     *
37
     * @var string
38
     */
39
    public $evidence = null;
40
41
    /**
42
     * Výchozí formát pro komunikaci.
43
     *
44
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
45
     *
46
     * @var string json|xml|...
47
     */
48
    public $format = 'json';
49
50
    /**
51
     * Curl Handle.
52
     *
53
     * @var resource
54
     */
55
    public $curl = null;
56
57
    /**
58
     * @var type
59
     */
60
    public $company = FLEXIBEE_COMPANY;
61
62
    /**
63
     * @var string
64
     */
65
    public $url = FLEXIBEE_URL;
66
67
    /**
68
     * @var string
69
     */
70
    public $user = FLEXIBEE_LOGIN;
71
72
    /**
73
     * @var string
74
     */
75
    public $password = FLEXIBEE_PASSWORD;
76
77
    /**
78
     * Identifikační řetězec.
79
     *
80
     * @var string
81
     */
82
    public $init = null;
83
84
    /**
85
     * Sloupeček s názvem.
86
     *
87
     * @var string
88
     */
89
    public $nameColumn = 'nazev';
90
91
    /**
92
     * Sloupeček obsahující datum vložení záznamu do shopu.
93
     *
94
     * @var string
95
     */
96
    public $myCreateColumn = 'false';
97
98
    /**
99
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
100
     *
101
     * @var string
102
     */
103
    public $myLastModifiedColumn = 'lastUpdate';
104
105
    /**
106
     * Klíčový idendifikátor záznamu.
107
     *
108
     * @var string
109
     */
110
    public $fbKeyColumn = 'id';
111
112
    /**
113
     * Informace o posledním HTTP requestu.
114
     *
115
     * @var array
116
     */
117
    public $info;
118
119
    /**
120
     * Informace o poslední HTTP chybě.
121
     *
122
     * @var array
123
     */
124
    public $error;
125
126
    /**
127
     * Used codes storage.
128
     *
129
     * @var array
130
     */
131
    public $codes = null;
132
133
    /**
134
     * Last Inserted ID.
135
     *
136
     * @var int
137
     */
138
    public $lastInsertedID = null;
139
140
    /**
141
     * Default Line Prefix.
142
     *
143
     * @var string
144
     */
145
    public $prefix = '/c/';
146
147
    /**
148
     * HTTP Response code of last request
149
     * 
150
     * @var int
151
     */
152
    public $lastResponseCode = null;
153
154
    /**
155
     * Třída pro práci s FlexiBee.
156
     *
157
     * @param string $init výchozí selektor dat
158
     */
159 28
    public function __construct($init = null)
160
    {
161 28
        $this->init = $init;
162
163 28
        parent::__construct();
164 28
        $this->curlInit();
165 28
    }
166
167 28
    public function curlInit()
168
    {
169 28
        $this->curl = \curl_init(); // create curl resource
170 28
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
171 28
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
172 28
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
173 28
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
174 28
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
175 28
        curl_setopt($this->curl, CURLOPT_VERBOSE, true); // For debugging
176 28
        curl_setopt($this->curl, CURLOPT_USERPWD,
177 28
            $this->user.':'.$this->password); // set username and password
178 28
    }
179
180
    /**
181
     * Nastaví Agendu pro Komunikaci.
182
     *
183
     * @param string $evidence
184
     */
185 14
    public function setEvidence($evidence)
186
    {
187 14
        $this->evidence = $evidence;
188 14
    }
189
190
    /**
191
     * Převede rekurzivně Objekt na pole.
192
     *
193
     * @param object|array $object
194
     *
195
     * @return array
196
     */
197 14
    public static function object2array($object)
198
    {
199 14
        $result = null;
200 14
        if (is_object($object)) {
201 14
            $objectData = get_object_vars($object);
202 14
            if (is_array($objectData) && count($objectData)) {
203 14
                $result = array_map('self::object2array', $objectData);
204 14
            }
205 14
        } else {
206 14
            if (is_array($object)) {
207 14
                foreach ($object as $item => $value) {
208 14
                    $result[$item] = self::object2array($value);
209 14
                }
210 14
            } else {
211 14
                $result = $object;
212
            }
213
        }
214
215 14
        return $result;
216
    }
217
218
    /**
219
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
220
     *
221
     * @param string $urlSuffix část URL za identifikátorem firmy.
222
     * @param string $method    HTTP/REST metoda
223
     * @param string $format    Requested format
224
     */
225 14
    public function performRequest($urlSuffix = null, $method = 'GET',
226
                                   $format = null)
227
    {
228 14
        if (is_null($format)) {
229 14
            $format = $this->format;
230 14
        }
231 14
        if (is_null($urlSuffix)) {
232 3
            $urlSuffix = $this->evidence.'.'.$format;
233 3
        }
234 14
        $url = $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
235 14
        curl_setopt($this->curl, CURLOPT_URL, $url);
236
// Nastavení samotné operace
237 14
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method);
238
239
// Proveď samotnou operaci
240 14
        $response = curl_exec($this->curl);
241
242 14
        $this->info = curl_getinfo($this->curl);
0 ignored issues
show
Documentation Bug introduced by
It seems like curl_getinfo($this->curl) of type * is incompatible with the declared type array of property $info.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
243
244 14
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
245
246 14
        if ($this->lastResponseCode != 200 && $this->lastResponseCode != 201) {
247 14
            $this->error = curl_error($this->curl);
0 ignored issues
show
Documentation Bug introduced by
It seems like curl_error($this->curl) of type string is incompatible with the declared type array of property $error.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
248
            switch ($format) {
249 14
                case 'json':
250 14
                    $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
251 14
                        function ($match) {
252
                        return mb_convert_encoding(pack('H*', $match[1]),
253
                            'UTF-8', 'UCS-2BE');
254 14
                    }, $response);
255 14
                    $response = (json_encode(json_decode($response, true, 10),
256 14
                            JSON_PRETTY_PRINT));
257 14
                    break;
258
                case 'xml':
259
                    $response = self::xml2array($response);
260
                    break;
261
            }
262
263 14
            if (is_array($response)) {
264
                $result = http_build_query($response);
265
            } else {
266 14
                $result = http_build_query(self::object2array(current(json_decode($response))));
267
            }
268
269 14
            if ($this->lastResponseCode == 400) {
270 1
                $this->logResult($result);
0 ignored issues
show
Documentation introduced by
$result is of type string, but the function expects a array.

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...
271 1
            } else {
272 14
                $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
273 14
                        curl_getinfo($this->curl, CURLINFO_HTTP_CODE), $result,
274 14
                        $this->error), 'error');
275 14
                $this->addStatusMessage($url);
276
            }
277 14
            if ($response == 'null') {
278
                if ($this->lastResponseCode == 200) {
279
                    $response = true;
280
                } else {
281
                    $response = null;
282
                }
283
            } else {
284 14
                if (is_string($response)) {
285 14
                    $response = self::object2array(current(json_decode($response)));
286 14
                }
287
            }
288 14
            return $response;
289
        }
290
291
        // Parse response
292
        switch ($format) {
293 13
            case 'json':
294 13
                $decoded = json_decode($response, true, 10);
295 13
                if (($method == 'PUT') && isset($decoded[$this->nameSpace][$this->resultField][0]['id'])) {
296
                    $this->lastInsertedID = $decoded[$this->nameSpace][$this->resultField][0]['id'];
297
                } else {
298 13
                    $this->lastInsertedID = null;
299
                }
300
//                $decodeError = json_last_error_msg();
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
301
//                $this->addStatusMessage($decodeError);
302
303 13
                break;
304 3
            case 'xml':
305 3
                if (strlen($response)) {
306 3
                    $decoded = self::xml2array($response);
307 3
                } else {
308
                    $decoded = null;
309
                }
310 3
                break;
311
        }
312
313
        // Get response body root automatically
314 13
        if (isset($decoded[$this->nameSpace])) {
315 13
            $decoded = $decoded[$this->nameSpace];
316 13
        }
317
318 13
        return $decoded;
0 ignored issues
show
Bug introduced by
The variable $decoded does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
319
    }
320
321
    /**
322
     * Give you last inserted record ID.
323
     * 
324
     * @return int
325
     */
326
    public function getLastInsertedId()
327
    {
328
        return $this->lastInsertedID;
329
    }
330
331
    /**
332
     * Convert XML to array.
333
     * 
334
     * @param string $xml
335
     *
336
     * @return array
337
     */
338 14
    public static function xml2array($xml)
339
    {
340 14
        $arr = [];
341
342 14
        if (is_string($xml)) {
343 14
            $xml = simplexml_load_string($xml);
344 14
        }
345
346 14
        foreach ($xml->children() as $r) {
347 14
            $t = [];
0 ignored issues
show
Unused Code introduced by
$t is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
348 14
            if (count($r->children()) == 0) {
349 14
                $arr[$r->getName()] = strval($r);
350 14
            } else {
351 14
                $arr[$r->getName()][] = self::xml2array($r);
352
            }
353 14
        }
354
355 14
        return $arr;
356
    }
357
358
    /**
359
     * Odpojení od FlexiBee.
360
     */
361 15
    public function disconnect()
362
    {
363 15
        if (is_resource($this->curl)) {
364 15
            curl_close($this->curl);
365 15
        }
366 15
        $this->curl = null;
367 15
    }
368
369 15
    public function __destruct()
370
    {
371 15
        $this->disconnect();
372 15
    }
373
374
    /**
375
     * Načte data z FlexiBee.
376
     *
377
     * @param string $suffix dotaz
378
     */
379
    public function loadFlexiData($suffix = null)
380
    {
381
        return $this->takeData($this->getFlexiData($suffix));
382
    }
383
384
    /**
385
     * Načte řádek dat z FlexiBee.
386
     *
387
     * @param int $recordID id požadovaného záznamu
388
     *
389
     * @return array
390
     */
391 14
    public function getFlexiRow($recordID)
392
    {
393 14
        $record   = null;
394 14
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
395 14
        if (isset($response[$this->evidence])) {
396 9
            $record = $response[$this->evidence][0];
397 9
        }
398
399 14
        return $record;
400
    }
401
402
    /**
403
     * Načte data z FlexiBee.
404
     *
405
     * @param string $suffix     dotaz
406
     * @param string $conditions Volitelný filtrovací výraz
407
     */
408 13
    public function getFlexiData($suffix = null, $conditions = null)
409
    {
410 13
        if (!is_null($conditions)) {
411 10
            if ($conditions[0] != '/') {
412 10
                $conditions = '/'.rawurlencode('('.($conditions).')');
413 10
            }
414 10
        } else {
415 13
            $conditions = '';
416
        }
417 13
        if ($suffix) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $suffix of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
418
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix,
419
                'GET');
420
        } else {
421 13
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format,
422 13
                'GET');
423
        }
424 13
        if (isset($transactions[$this->evidence])) {
425 10
            $result = $transactions[$this->evidence];
426 10
        } else {
427 3
            $result = $transactions;
428
        }
429
430 13
        return $result;
431
    }
432
433
    /**
434
     * Načte záznam z FlexiBee.
435
     *
436
     * @param int $id ID záznamu
437
     *
438
     * @return int počet načtených položek
439
     */
440 14
    public function loadFromFlexiBee($id = null)
441
    {
442 14
        if (is_null($id)) {
443 14
            $id = $this->getMyKey();
444 14
        }
445
446 14
        return $this->takeData($this->getFlexiData('/'.$id));
447
    }
448
449
    /**
450
     * Uloží data do FlexiBee.
451
     *
452
     * @param array $data
453
     *
454
     * @return array výsledek
455
     */
456 View Code Duplication
    public function saveToFlexiBee($data = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
457
    {
458
        if (is_null($data)) {
459
            $data = $this->getData();
460
        }
461
462
        $jsonizedData = $this->jsonizeData($data);
463
464
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $jsonizedData);
465
466
        return $this->performRequest($this->evidence.'.'.$this->format, 'PUT');
467
    }
468
469
    /**
470
     * Převede data do Json formátu pro FlexiBee.
471
     *
472
     * @param array $data
473
     *
474
     * @return string
475
     */
476 14
    public function jsonizeData($data)
477
    {
478
        $jsonize = [
479 14
            $this->nameSpace => [
480 14
                '@version' => $this->protoVersion,
481 14
                $this->evidence => $data,
482 14
            ],
483 14
        ];
484
485 14
        return json_encode($jsonize);
486
    }
487
488
    /**
489
     * Uloží záznam.
490
     *
491
     * @param array $data
492
     *
493
     * @return array odpověď
494
     */
495 View Code Duplication
    public function insertToFlexiBee($data = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
496
    {
497
        if (is_null($data)) {
498
            $data = $this->getData();
499
        }
500
        $jsonizedData = $this->jsonizeData($data);
501
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $jsonizedData);
502
503
        return $this->performRequest($this->evidence.'.'.$this->format, 'PUT');
504
    }
505
506
    /**
507
     * Test if given record ID exists in FlexiBee.
508
     *
509
     * @param string|int $identifer
510
     */
511
    public function idExists($identifer = null)
512
    {
513
        if (is_null($identifer)) {
514
            $identifer = $this->getMyKey();
515
        }
516
        $flexiData = $this->getFlexiData(
517
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
518
519
        return $flexiData;
520
    }
521
522
    /**
523
     * Test if given record exists in FlexiBee.
524
     *
525
     * @param array $data
526
     */
527
    public function recordExists($data = null)
528
    {
529
        if (is_null($data)) {
530
            $data = $this->getData();
531
        }
532
533
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
534
            self::flexiUrl($data));
535
536
        return $res;
537
    }
538
539
    /**
540
     * Vrací z FlexiBee sloupečky podle podmínek.
541
     *
542
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
543
     * @param array|string     $orderBy    třídit dle
544
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
545
     *                                     sloupečku
546
     * @param int              $limit      maximální počet vrácených záznamů
547
     *
548
     * @return array
549
     */
550
    public function getAllFromFlexibee($conditions = null, $orderBy = null,
0 ignored issues
show
Unused Code introduced by
The parameter $orderBy is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
551
                                       $indexBy = null, $limit = null)
0 ignored issues
show
Unused Code introduced by
The parameter $limit is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
552
    {
553
        if (is_int($conditions)) {
554
            $conditions = [$this->getmyKeyColumn() => $conditions];
555
        }
556
557
        $flexiData = $this->getFlexiData('', $conditions);
0 ignored issues
show
Bug introduced by
It seems like $conditions can also be of type array; however, FlexiPeeHP\FlexiBee::getFlexiData() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
558
559 View Code Duplication
        if ($indexBy) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $indexBy of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
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...
560
            $flexiData2 = [];
561
            foreach ($flexiData as $dataID => $data) {
562
                $flexiData2[$data[$indexBy]] = $data;
563
            }
564
            $flexiData = $flexiData2;
565
        }
566
567
        return $flexiData;
568
    }
569
570
    /**
571
     * Vrací z FlexiBee sloupečky podle podmínek.
572
     *
573
     * @param string[]         $columnsList seznam položek
574
     * @param array|int|string $conditions  pole podmínek nebo ID záznamu
575
     * @param array|string     $orderBy     třídit dle
576
     * @param string           $indexBy     klice vysledku naplnit hodnotou ze
577
     *                                      sloupečku
578
     * @param int              $limit       maximální počet vrácených záznamů
579
     *
580
     * @return array
581
     */
582
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
583
                                           $orderBy = null, $indexBy = null,
0 ignored issues
show
Unused Code introduced by
The parameter $orderBy is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
584
                                           $limit = null)
0 ignored issues
show
Unused Code introduced by
The parameter $limit is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
585
    {
586
        if (($columnsList != '*') && !count($columnsList)) {
587
            $this->error('getColumnsFromFlexiBee: Missing ColumnList');
588
589
            return;
590
        }
591
592
        if (is_int($conditions)) {
593
            $conditions = [$this->getmyKeyColumn() => $conditions];
594
        }
595
596
        if (is_array($columnsList)) {
597
            $columns = implode(',', array_unique($columnsList));
598
        } else {
599
            $columns = $columnsList;
600
        }
601
602
        $flexiData = $this->getFlexiData('detail=custom:'.$columns, $conditions);
0 ignored issues
show
Bug introduced by
It seems like $conditions can also be of type array; however, FlexiPeeHP\FlexiBee::getFlexiData() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
603
604 View Code Duplication
        if ($indexBy) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $indexBy of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
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...
605
            $flexiData2 = [];
606
            foreach ($flexiData as $dataID => $data) {
607
                $flexiData2[$data[$indexBy]] = $data;
608
            }
609
            $flexiData = $flexiData2;
610
        }
611
612
        return $flexiData;
613
    }
614
615
    /**
616
     * Vrací kód záznamu.
617
     *
618
     * @param mixed $data
619
     *
620
     * @todo papat i string
621
     *
622
     * @return string
623
     */
624 14
    public function getKod($data = null, $unique = true)
625
    {
626 14
        $kod = null;
627
628 14
        if (is_null($data)) {
629 14
            $data = $this->getData();
630 14
        }
631
632 14
        if (is_string($data)) {
633 14
            $data = [$this->nameColumn => $data];
634 14
        }
635
636 14
        if (isset($data['kod'])) {
637 14
            $kod = $data['kod'];
638 14
        } else {
639 14
            if (isset($data[$this->nameColumn])) {
640 14
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
641 14
                    \Ease\Sand::rip($data[$this->nameColumn]));
642 14
            } else {
643 14
                if (isset($data[$this->myKeyColumn])) {
644 14
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
645 14
                }
646
            }
647
        }
648
649 14
        if (!strlen($kod)) {
650 14
            $kod = 'NOTSET';
651 14
        }
652
653 14
        if (strlen($kod) > 18) {
654 14
            $kodfinal = strtoupper(substr($kod, 0, 18));
655 14
        } else {
656 14
            $kodfinal = strtoupper($kod);
657
        }
658
659 14
        if ($unique) {
660 14
            $counter = 0;
661 14
            if ($this->codes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->codes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
662 14
                foreach ($this->codes as $codesearch => $keystring) {
663 14
                    if (strstr($codesearch, $kodfinal)) {
664 14
                        ++$counter;
665 14
                    }
666 14
                }
667 14
            }
668 14
            if ($counter) {
669 14
                $kodfinal = $kodfinal.$counter;
670 14
            }
671
672 14
            $this->codes[$kodfinal] = $kod;
673 14
        }
674
675 14
        return $kodfinal;
676
    }
677
678
    /**
679
     * Vyhledavani v záznamech objektu FlexiBee.
680
     *
681
     * @param string $what hledaný výraz
682
     *
683
     * @return array pole výsledků
684
     */
685
    public function searchString($what)
686
    {
687
        $results   = [];
688
        $conds     = [];
689
        $columns[] = $this->myKeyColumn;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$columns was never initialized. Although not strictly required by PHP, it is generally a good practice to add $columns = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
690
        foreach ($this->useKeywords as $keyword => $keywordInfo) {
0 ignored issues
show
Bug introduced by
The property useKeywords does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
691
            if (isset($this->keywordsInfo[$keyword]['virtual']) && ($this->keywordsInfo[$keyword]['virtual']
0 ignored issues
show
Bug introduced by
The property keywordsInfo does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
692
                == true)) {
693
                if ($keyword == $this->nameColumn) {
694
                    $this->nameColumn = $this->myKeyColumn;
695
                }
696
                continue;
697
            }
698
            switch ($keywordInfo) {
699
                case 'INT':
700 View Code Duplication
                case 'FLOAT':
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...
701
                    if (is_numeric($what)) {
702
                        $conds[]   = "($keyword = ".$what.')';
703
                        $columns[] = "$keyword";
704
                    }
705
                    break;
706
                case 'TEXT':
707 View Code Duplication
                case 'STRING':
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...
708
                    if (is_string($what)) {
709
                        $conds[]   = "( $keyword like '".$what."')";
710
                        $columns[] = "$keyword";
711
                    }
712
                    break;
713
                default:
714
                    break;
715
            }
716
        }
717
718
//        $res = \Ease\Shared::db()->queryToArray('SELECT ' . implode(',', $columns) . ',' . $this->nameColumn . ' FROM ' . $this->myTable . ' WHERE ' . implode(' OR ', $conds) . ' ORDER BY ' . $this->nameColumn, $this->myKeyColumn);
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
719
720
        $res = $this->getColumnsFromFlexibee($columns, implode(' or ', $conds));
721
722
        foreach ($res as $result) {
723
            $occurences = '';
724
            foreach ($result as $key => $value) {
725
                if (is_array($value)) {
726
                    continue;
727
                }
728
                if (mb_stristr($value, $what)) {
729
                    $occurences .= '('.$key.': '.$value.')';
730
                }
731
            }
732
            $results[$result[$this->myKeyColumn]] = [$this->nameColumn => $result[$this->nameColumn],
733
                'what' => $occurences,];
734
        }
735
736
        return $results;
737
    }
738
739
    /**
740
     * Write Operation Result.
741
     * 
742
     * @param array  $resultData
743
     * @param string $url        URL
744
     */
745 14
    public function logResult($resultData, $url = null)
746
    {
747 14
        if ($url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
748 14
            $this->logger->addStatusMessage($url);
749 14
        }
750
751 14
        if (isset($resultData['results'])) {
752 14
            $status = null;
0 ignored issues
show
Unused Code introduced by
$status is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
753 14
            if ($resultData['success'] == 'false') {
754 14
                $status = 'error';
755 14
            } else {
756 14
                $status = 'success';
757
            }
758 14
            foreach ($resultData['results'] as $result) {
759 14
                if (isset($result['request-id'])) {
760 14
                    $rid = $result['request-id'];
761 14
                } else {
762 14
                    $rid = '';
763
                }
764 14
                if (isset($result['errors'])) {
765 14
                    foreach ($result['errors'] as $error) {
766 14
                        $message = $error['message'];
767 14
                        if (isset($error['for'])) {
768
                            $message.=' for: '.$error['for'];
769
                        }
770 14
                        if (isset($error['value'])) {
771
                            $message.=' value:'.$error['value'];
772
                        }
773 14
                        if (isset($error['code'])) {
774
                            $message.=' code:'.$error['code'];
775
                        }
776 14
                        $this->logger->addStatusMessage($rid.': '.$message,
777 14
                            $status);
778 14
                    }
779 14
                }
780 14
            }
781 14
        }
782 14
        if (is_object($this->logger)) {
783 14
            $this->logger->flush(get_class($this));
784 14
        }
785 14
    }
786
787
    /**
788
     * Generuje fragment url pro filtrování.
789
     *
790
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
791
     *
792
     * @param array  $data
793
     * @param string $operator and/or
794
     *
795
     * @return string
796
     */
797 14
    public static function flexiUrl(array $data, $operator = 'and')
798
    {
799 14
        $flexiUrl = '';
0 ignored issues
show
Unused Code introduced by
$flexiUrl is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
800 14
        $parts    = [];
801
802 14
        foreach ($data as $column => $value) {
803 14
            if (is_numeric($data[$column])) {
804 14
                $parts[$column] = $column.' = '.$data[$column];
805 14
            } else {
806 14
                $parts[$column] = $column." = '".$data[$column]."'";
807
            }
808 14
        }
809
810 14
        $flexiUrl = implode(' '.$operator.' ', $parts);
811
812 14
        return $flexiUrl;
813
    }
814
815
    /**
816
     * Smaže záznam
817
     *
818
     * @param int|string $id identifikátor záznamu
819
     */
820
    public function deleteFromFlexiBee($id)
821
    {
822
        $this->performRequest($this->evidence.'/'.$id.'.'.$this->format,
823
            'DELETE');
824
    }
825
}