Completed
Push — master ( cdd0e8...52c54c )
by Vítězslav
09:14
created

FlexiBeeRO::getColumnsFromFlexibee()   C

Complexity

Conditions 8
Paths 16

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 17
nc 16
nop 3
dl 0
loc 29
rs 5.3846
c 0
b 0
f 0
1
<?php
2
/**
3
 * FlexiPeeHP - Read Only Access to FlexiBee class.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015,2016 Spoje.Net
7
 */
8
9
namespace FlexiPeeHP;
10
11
/**
12
 * Základní třída pro čtení z FlexiBee
13
 *
14
 * @url https://demo.flexibee.eu/devdoc/
15
 */
16
class FlexiBeeRO extends \Ease\Brick
17
{
18
    /**
19
     * Version of FlexiPeeHP library
20
     *
21
     * @var string
22
     */
23
    static public $libVersion = '1.6.3.6';
24
25
    /**
26
     * Základní namespace pro komunikaci s FlexiBee.
27
     * Basic namespace for communication with FlexiBee
28
     *
29
     * @var string Jmený prostor datového bloku odpovědi
30
     */
31
    public $nameSpace = 'winstrom';
32
33
    /**
34
     * Datový blok v poli odpovědi.
35
     * Data block in response field.
36
     *
37
     * @var string
38
     */
39
    public $resultField = 'results';
40
41
    /**
42
     * Verze protokolu použitého pro komunikaci.
43
     * Communication protocol version used.
44
     *
45
     * @var string Verze použitého API
46
     */
47
    public $protoVersion = '1.0';
48
49
    /**
50
     * Evidence užitá objektem.
51
     * Evidence used by object
52
     *
53
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
54
     * @var string
55
     */
56
    public $evidence = null;
57
58
    /**
59
     * Výchozí formát pro komunikaci.
60
     * Default communication format.
61
     *
62
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
63
     *
64
     * @var string json|xml|...
65
     */
66
    public $format = 'json';
67
68
    /**
69
     * Curl Handle.
70
     *
71
     * @var resource
72
     */
73
    public $curl = null;
74
75
    /**
76
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
77
     * @var string
78
     */
79
    public $company = null;
80
81
    /**
82
     * Server[:port]
83
     * @var string
84
     */
85
    public $url = null;
86
87
    /**
88
     * REST API Username
89
     * @var string
90
     */
91
    public $user = null;
92
93
    /**
94
     * REST API Password
95
     * @var string
96
     */
97
    public $password = null;
98
99
    /**
100
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
101
     */
102
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
103
104
    /**
105
     * Default additional request url parameters after question mark
106
     * 
107
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
108
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
109
     * @var array
110
     */
111
    public $defaultUrlParams = ['limit' => 0];
112
113
    /**
114
     * Identifikační řetězec.
115
     *
116
     * @var string
117
     */
118
    public $init = null;
119
120
    /**
121
     * Sloupeček s názvem.
122
     *
123
     * @var string
124
     */
125
    public $nameColumn = 'nazev';
126
127
    /**
128
     * Sloupeček obsahující datum vložení záznamu do shopu.
129
     *
130
     * @var string
131
     */
132
    public $myCreateColumn = 'false';
133
134
    /**
135
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
136
     *
137
     * @var string
138
     */
139
    public $myLastModifiedColumn = 'lastUpdate';
140
141
    /**
142
     * Klíčový idendifikátor záznamu.
143
     *
144
     * @var string
145
     */
146
    public $fbKeyColumn = 'id';
147
148
    /**
149
     * Informace o posledním HTTP requestu.
150
     *
151
     * @var *
152
     */
153
    public $info;
154
155
    /**
156
     * Informace o poslední HTTP chybě.
157
     *
158
     * @var string
159
     */
160
    public $lastCurlError = null;
161
162
    /**
163
     * Used codes storage.
164
     *
165
     * @var array
166
     */
167
    public $codes = null;
168
169
    /**
170
     * Last Inserted ID.
171
     *
172
     * @var int
173
     */
174
    public $lastInsertedID = null;
175
176
    /**
177
     * Default Line Prefix.
178
     *
179
     * @var string
180
     */
181
    public $prefix = '/c/';
182
183
    /**
184
     * Raw Content of last curl response
185
     * 
186
     * @var string
187
     */
188
    public $lastCurlResponse;
189
190
    /**
191
     * HTTP Response code of last request
192
     *
193
     * @var int
194
     */
195
    public $lastResponseCode = null;
196
197
    /**
198
     * Array of fields for next curl POST operation
199
     *
200
     * @var array
201
     */
202
    protected $postFields = [];
203
204
    /**
205
     * Last operation result data or message(s)
206
     *
207
     * @var array
208
     */
209
    public $lastResult = null;
210
211
    /**
212
     * Nuber from  @rowCount
213
     * @var int
214
     */
215
    public $rowCount = null;
216
217
    /**
218
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
219
     * @var string
220
     */
221
    protected $action;
222
223
    /**
224
     * Pole akcí které podporuje ta která evidence
225
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
226
     * @var array
227
     */
228
    public $actionsAvailable = null;
229
230
    /**
231
     * Parmetry pro URL
232
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
233
     * @var array
234
     */
235
    public $urlParams = [
236
        'dry-run',
237
        'fail-on-warning',
238
        'report-name',
239
        'report-lang',
240
        'report-sign',
241
        'detail',
242
        'mode',
243
        'limit',
244
        'start',
245
        'order',
246
        'sort',
247
        'add-row-count',
248
        'relations',
249
        'includes',
250
        'use-ext-id',
251
        'use-internal-id',
252
        'stitky-as-ids',
253
        'only-ext-ids',
254
        'no-ext-ids',
255
        'no-ids',
256
        'code-as-id',
257
        'no-http-errors',
258
        'export-settings',
259
        'as-gui',
260
        'code-in-response',
261
        'add-global-version',
262
        'encoding',
263
        'delimeter',
264
        'format',
265
        'auth',
266
        'skupina-stitku',
267
        'dir',
268
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
269
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
270
        'inDesktopApp' // Note: Undocumented function (html only)
271
    ];
272
273
    /**
274
     * Class for read only interaction with FlexiBee.
275
     *
276
     * @param mixed $init default record id or initial data
277
     * @param array $options Connection settings override
278
     */
279
    public function __construct($init = null, $options = [])
280
    {
281
        $this->init = $init;
282
283
        parent::__construct();
284
        $this->setUp($options);
285
        $this->curlInit();
286
        if (!is_null($init)) {
287
            $this->processInit($init);
288
        }
289
    }
290
291
    /**
292
     * SetUp Object to be ready for connect
293
     *
294
     * @param array $options Object Options
295
     */
296
    public function setUp($options = [])
297
    {
298 View Code Duplication
        if (isset($options['company'])) {
1 ignored issue
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...
299
            $this->company = $options['company'];
300
        } else {
301
            if (is_null($this->company) && defined('FLEXIBEE_COMPANY')) {
302
                $this->company = constant('FLEXIBEE_COMPANY');
303
            }
304
        }
305 View Code Duplication
        if (isset($options['url'])) {
1 ignored issue
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...
306
            $this->url = $options['url'];
307
        } else {
308
            if (is_null($this->url) && defined('FLEXIBEE_URL')) {
309
                $this->url = constant('FLEXIBEE_URL');
310
            }
311
        }
312 View Code Duplication
        if (isset($options['user'])) {
1 ignored issue
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...
313
            $this->user = $options['user'];
314
        } else {
315
            if (is_null($this->user) && defined('FLEXIBEE_LOGIN')) {
316
                $this->user = constant('FLEXIBEE_LOGIN');
317
            }
318
        }
319 View Code Duplication
        if (isset($options['password'])) {
1 ignored issue
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...
320
            $this->password = $options['password'];
321
        } else {
322
            if (is_null($this->password) && defined('FLEXIBEE_PASSWORD')) {
323
                $this->password = constant('FLEXIBEE_PASSWORD');
324
            }
325
        }
326
        if (isset($options['evidence'])) {
327
            $this->setEvidence($options['evidence']);
328
        }
329
        if (isset($options['prefix'])) {
330
            $this->setPrefix($options['prefix']);
331
        }
332
    }
333
334
    /**
335
     * Inicializace CURL
336
     */
337
    public function curlInit()
338
    {
339
        $this->curl = \curl_init(); // create curl resource
340
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
341
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
342
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
343
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
344
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
345
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
346
        curl_setopt($this->curl, CURLOPT_USERPWD,
347
            $this->user.':'.$this->password); // set username and password
348
    }
349
350
    /**
351
     * Zinicializuje objekt dle daných dat
352
     * 
353
     * @param mixed $init
354
     */
355
    public function processInit($init)
356
    {
357
        if (is_integer($init)) {
358
            $this->loadFromFlexiBee($init);
359
        } elseif (is_array($init)) {
360
            $this->takeData($init);
361
        } elseif (strstr($init, 'code:')) {
362
            $this->loadFromFlexiBee($init);
363
        }
364
    }
365
366
    /**
367
     * Set URL prefix
368
     *
369
     * @param string $prefix
370
     */
371
    public function setPrefix($prefix)
372
    {
373
        switch ($prefix) {
374
            case 'a': //Access
375
            case 'c': //Company
376
            case 'u': //User
377
            case 'g': //License Groups
378
            case 'admin':
379
            case 'status':
380
            case 'login-logout':
381
                $this->prefix = '/'.$prefix.'/';
382
                break;
383
            case null:
384
            case '':
385
            case '/':
386
                $this->prefix = '';
387
                break;
388
            default:
389
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
390
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
391
        }
392
    }
393
394
    /**
395
     * Nastaví Evidenci pro Komunikaci.
396
     * Set evidence for communication
397
     *
398
     * @param string $evidence evidence pathName to use
399
     * @return boolean evidence switching status
400
     */
401
    public function setEvidence($evidence)
402
    {
403
        $result = null;
0 ignored issues
show
Unused Code introduced by
$result 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...
404
        switch ($this->prefix) {
405
            case '/c/':
406
                if (array_key_exists($evidence, EvidenceList::$name)) {
407
                    $this->evidence = $evidence;
408
                    $result         = true;
409
                } else {
410
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
411
                        $evidence));
412
                }
413
                break;
414
            default:
415
                $this->evidence = $evidence;
416
                $result         = true;
417
                break;
418
        }
419
        return $result;
420
    }
421
422
    /**
423
     * Vrací právě používanou evidenci pro komunikaci
424
     * Obtain current used evidence
425
     *
426
     * @return string
427
     */
428
    public function getEvidence()
429
    {
430
        return $this->evidence;
431
    }
432
433
    /**
434
     * Set used company.
435
     * Nastaví Firmu.
436
     *
437
     * @param string $company
438
     */
439
    public function setCompany($company)
440
    {
441
        $this->company = $company;
442
    }
443
444
    /**
445
     * Obtain company now used
446
     * Vrací právě používanou firmu
447
     *
448
     * @return string
449
     */
450
    public function getCompany()
451
    {
452
        return $this->company;
453
    }
454
455
    /**
456
     * Vrací název evidence použité v odpovědích z FlexiBee
457
     *
458
     * @return string
459
     */
460
    public function getResponseEvidence()
461
    {
462
        switch ($this->evidence) {
463
            case 'c':
464
                $evidence = 'companies';
465
                break;
466
            default:
467
                $evidence = $this->getEvidence();
468
                break;
469
        }
470
        return $evidence;
471
    }
472
473
    /**
474
     * Převede rekurzivně Objekt na pole.
475
     *
476
     * @param object|array $object
477
     *
478
     * @return array
479
     */
480
    public static function object2array($object)
481
    {
482
        $result = null;
483
        if (is_object($object)) {
484
            $objectData = get_object_vars($object);
485
            if (is_array($objectData) && count($objectData)) {
486
                $result = array_map('self::object2array', $objectData);
487
            }
488 View Code Duplication
        } else {
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...
489
            if (is_array($object)) {
490
                foreach ($object as $item => $value) {
491
                    $result[$item] = self::object2array($value);
492
                }
493
            } else {
494
                $result = $object;
495
            }
496
        }
497
498
        return $result;
499
    }
500
501
    /**
502
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
503
     *
504
     * @param object|array $object
505
     *
506
     * @return array
507
     */
508
    public static function objectToID($object)
509
    {
510
        $result = null;
511
        if (is_object($object)) {
512
            $result = $object->__toString();
513 View Code Duplication
        } else {
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...
514
            if (is_array($object)) {
515
                foreach ($object as $item => $value) {
516
                    $result[$item] = self::objectToID($value);
517
                }
518
            } else { //String
519
                $result = $object;
520
            }
521
        }
522
523
        return $result;
524
    }
525
526
    /**
527
     * Return basic URL for used Evidence
528
     *
529
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
530
     * @param string $urlSuffix
531
     */
532
    public function getEvidenceURL($urlSuffix = null)
533
    {
534
        if (is_null($urlSuffix)) {
535
            $urlSuffix = $this->getEvidence();
536
        } elseif ($urlSuffix[0] == ';') {
537
            $urlSuffix = $this->getEvidence().$urlSuffix;
538
        }
539
        return $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
540
    }
541
542
    /**
543
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
544
     *
545
     * @param string $urlSuffix část URL za identifikátorem firmy.
546
     * @param string $method    HTTP/REST metoda
547
     * @param string $format    Requested format
548
     * @return array|boolean Výsledek operace
549
     */
550
    public function performRequest($urlSuffix = null, $method = 'GET',
551
                                   $format = null)
552
    {
553
        $this->rowCount = null;
554
        $url            = $this->getEvidenceURL($urlSuffix);
555
556
        $responseCode = $this->doCurlRequest($url, $method, $format);
0 ignored issues
show
Documentation introduced by
$method is of type string, but the function expects a object<FlexiPeeHP\strinf>.

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...
557
558
        if (is_null($format)) {
559
            $format = $this->format;
560
        }
561
562
        switch ($responseCode) {
563
            case 200:
564
            case 201:
565
                // Parse response
566
                $responseDecoded = [];
567
568
                switch ($format) {
569
                    case 'json':
570
                        $responseDecoded = json_decode($this->lastCurlResponse,
571
                            true, 10);
572
                        if (($method == 'PUT') && isset($responseDecoded[$this->nameSpace][$this->resultField][0]['id'])) {
573
                            $this->lastInsertedID = $responseDecoded[$this->nameSpace][$this->resultField][0]['id'];
574
                            $this->setMyKey($this->lastInsertedID);
575
                        } else {
576
                            $this->lastInsertedID = null;
577
                            if (isset($responseDecoded[$this->nameSpace]['@rowCount'])) {
578
                                $this->rowCount = (int) $responseDecoded[$this->nameSpace]['@rowCount'];
579
                            }
580
                        }
581
                        $decodeError = json_last_error_msg();
582
                        if ($decodeError != 'No error') {
583
                            $this->addStatusMessage($decodeError, 'error');
584
                        }
585
                        break;
586
                    case 'xml':
587
                        if (strlen($this->lastCurlResponse)) {
588
                            $responseDecoded = self::xml2array($this->lastCurlResponse);
589
                        } else {
590
                            $responseDecoded = null;
591
                        }
592
                        break;
593
                }
594
595
596
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
597
598
                break;
599
600
            default: //Some goes wrong
601
                $this->lastCurlError = curl_error($this->curl);
602
                switch ($format) {
603
                    case 'json':
604
                        $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
605
                            function ($match) {
606
                            return mb_convert_encoding(pack('H*', $match[1]),
607
                                'UTF-8', 'UCS-2BE');
608
                        }, $this->lastCurlResponse);
609
                        $response = (json_encode(json_decode($response, true, 10),
610
                                JSON_PRETTY_PRINT));
611
                        break;
612
                    case 'xml':
613
                        if (strlen($this->lastCurlResponse)) {
614
                            $response = self::xml2array($this->lastCurlResponse);
615
                        }
616
                        break;
617
                }
618
619
                if (is_array($response)) {
620
                    $result = urldecode(http_build_query($response));
0 ignored issues
show
Bug introduced by
The variable $response 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...
621
                } elseif (strlen($response) && ($response != 'null')) {
622
                    $result = urldecode(http_build_query(self::object2array(current(json_decode($response)))));
623
                } else {
624
                    $result = null;
625
                }
626
627
                if ($response == 'null') {
628
                    if ($this->lastResponseCode == 200) {
629
                        $response = true;
630
                    } else {
631
                        $response = null;
632
                    }
633
                } else {
634
                    if (is_string($response)) {
635
                        $response = self::object2array(current(json_decode($response)));
636
                    }
637
                }
638
639
                if (is_array($response) && ($this->lastResponseCode == 400)) {
640
                    $this->logResult($response, $url);
641
                } else {
642
                    $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
643
                            curl_getinfo($this->curl, CURLINFO_HTTP_CODE),
644
                            $result, $this->lastCurlError), 'error');
645
                    $this->addStatusMessage($url, 'info');
646
                    if (count($this->postFields)) {
647
                        if (is_array($result)) {
648
                            $this->addStatusMessage(urldecode(http_build_query($this->postFields)),
649
                                'debug');
650
                        } else {
651
                            $this->addStatusMessage(urldecode(http_build_query($this->getData())),
652
                                'debug');
653
                        }
654
                    }
655
                }
656
657
                break;
658
        }
659
660
        if ($this->debug === true) {
661
            $this->saveDebugFiles();
662
        }
663
664
        return $response;
665
    }
666
667
    /**
668
     * Vykonej HTTP požadavek
669
     *
670
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
671
     * @param string $url    URL požadavku
672
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
673
     * @param string $format požadovaný formát komunikace
674
     * @return int HTTP Response CODE
675
     */
676
    public function doCurlRequest($url, $method, $format = null)
677
    {
678
        if (is_null($format)) {
679
            $format = $this->format;
680
        }
681
        curl_setopt($this->curl, CURLOPT_URL, $url);
682
// Nastavení samotné operace
683
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
684
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
685
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
686
687
        $httpHeaders = $this->defaultHttpHeaders;
688
        switch ($format) {
689
            case 'json':
690
                $httpHeaders['Accept']       = 'application/json';
691
                $httpHeaders['Content-Type'] = 'application/json';
692
693
                break;
694
            case 'xml':
695
                $httpHeaders['Accept']       = 'application/xml';
696
                $httpHeaders['Content-Type'] = 'application/xml';
697
                break;
698
        }
699
700
        $httpHeadersFinal = [];
701
        foreach ($httpHeaders as $key => $value) {
702
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
703
                $value.= ' v'.self::$libVersion;
704
            }
705
            $httpHeadersFinal[] = $key.': '.$value;
706
        }
707
708
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
709
710
// Proveď samotnou operaci
711
        $this->lastCurlResponse = curl_exec($this->curl);
712
713
        $this->info = curl_getinfo($this->curl);
714
715
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
716
        return $this->lastResponseCode;
717
    }
718
719
    /**
720
     * Nastaví druh prováděné akce.
721
     *
722
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
723
     * @param string $action
724
     * @return boolean
725
     */
726
    public function setAction($action)
727
    {
728
        $result = false;
729
        if (is_null($this->actionsAvailable)) {
730
            $this->action = $action;
731
            $result       = true;
732
        } else {
733
            if (array_search($action, $this->actionsAvailable)) {
734
                $this->action = $action;
735
                $result       = true;
736
            }
737
        }
738
        return $result;
739
    }
740
741
    /**
742
     * Convert XML to array.
743
     *
744
     * @param string $xml
745
     *
746
     * @return array
747
     */
748
    public static function xml2array($xml)
749
    {
750
        $arr = [];
751
752
        if (is_string($xml)) {
753
            $xml = simplexml_load_string($xml);
754
        }
755
756
        foreach ($xml->children() as $r) {
757
            if (count($r->children()) == 0) {
758
                $arr[$r->getName()] = strval($r);
759
            } else {
760
                $arr[$r->getName()][] = self::xml2array($r);
761
            }
762
        }
763
764
        return $arr;
765
    }
766
767
    /**
768
     * Odpojení od FlexiBee.
769
     */
770
    public function disconnect()
771
    {
772
        if (is_resource($this->curl)) {
773
            curl_close($this->curl);
774
        }
775
        $this->curl = null;
776
    }
777
778
    public function __destruct()
779
    {
780
        $this->disconnect();
781
    }
782
783
    /**
784
     * Načte řádek dat z FlexiBee.
785
     *
786
     * @param int $recordID id požadovaného záznamu
787
     *
788
     * @return array
789
     */
790
    public function getFlexiRow($recordID)
791
    {
792
        $record   = null;
793
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
794
        if (isset($response[$this->evidence])) {
795
            $record = $response[$this->evidence][0];
796
        }
797
798
        return $record;
799
    }
800
801
    /**
802
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
803
     *
804
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
805
     * @param array $conditions pole podmínek   - rendrují se do ()
806
     * @param array $urlParams  pole parametrů  - rendrují za ?
807
     */
808
    public function extractUrlParams(&$conditions, &$urlParams)
809
    {
810
        foreach ($this->urlParams as $urlParam) {
811
            if (isset($conditions[$urlParam])) {
812
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
813
            }
814
        }
815
    }
816
817
    /**
818
     * Načte data z FlexiBee.
819
     *
820
     * @param string $suffix     dotaz
821
     * @param string|array $conditions Volitelný filtrovací výraz
822
     */
823
    public function getFlexiData($suffix = null, $conditions = null)
824
    {
825
        $urlParams = $this->defaultUrlParams;
826
        if (!is_null($conditions)) {
827
            if (is_array($conditions)) {
828
                $this->extractUrlParams($conditions, $urlParams);
829
                $conditions = $this->flexiUrl($conditions);
830
            }
831
832
            if (strlen($conditions) && ($conditions[0] != '/')) {
833
                $conditions = '/'.rawurlencode('('.($conditions).')');
834
            }
835
        } else {
836
            $conditions = '';
837
        }
838
        if (strlen($suffix)) {
839
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
840
                'GET');
841
        } else {
842
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
843
                'GET');
844
        }
845
        if (isset($transactions[$this->evidence])) {
846
            $result = $transactions[$this->evidence];
847
        } else {
848
            $result = $transactions;
849
        }
850
851
        return $result;
852
    }
853
854
    /**
855
     * Načte záznam z FlexiBee.
856
     *
857
     * @param int $id ID záznamu
858
     *
859
     * @return int počet načtených položek
860
     */
861 View Code Duplication
    public function loadFromFlexiBee($id = 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...
862
    {
863
        $data = [];
864
        if (is_null($id)) {
865
            $id = $this->getMyKey();
866
        }
867
868
        $flexidata = $this->getFlexiData(null, '/'.$id);
869
        if (count($flexidata) == 1) {
870
            $data = current($flexidata);
871
        }
872
        return $this->takeData($data);
873
    }
874
875
    /**
876
     * Převede data do Json formátu pro FlexiBee.
877
     *
878
     * @param array $data
879
     *
880
     * @return string
881
     */
882
    public function jsonizeData($data)
883
    {
884
        $jsonize = [
885
            $this->nameSpace => [
886
                '@version' => $this->protoVersion,
887
                $this->evidence => $this->objectToID($data),
888
            ],
889
        ];
890
891
        if (!is_null($this->action)) {
892
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
893
            $this->action                                         = null;
894
        }
895
896
        return json_encode($jsonize);
897
    }
898
899
    /**
900
     * Test if given record ID exists in FlexiBee.
901
     *
902
     * @param string|int $identifer
903
     */
904
    public function idExists($identifer = null)
905
    {
906
        if (is_null($identifer)) {
907
            $identifer = $this->getMyKey();
908
        }
909
        $flexiData = $this->getFlexiData(
910
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
911
912
        return $flexiData;
913
    }
914
915
    /**
916
     * Test if given record exists in FlexiBee.
917
     *
918
     * @param array $data
919
     * @return boolean Record presence status
920
     */
921
    public function recordExists($data = null)
922
    {
923
        $found = null;
0 ignored issues
show
Unused Code introduced by
$found 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...
924
        if (is_null($data)) {
925
            $data = $this->getData();
926
        }
927
928
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
929
            self::flexiUrl($data));
0 ignored issues
show
Documentation introduced by
self::flexiUrl($data) is of type string, but the function expects a array|null.

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...
930
931
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
932
            || !count($res[0])) {
933
            $found = false;
934
        } else {
935
            $found = true;
936
        }
937
        return $found;
938
    }
939
940
    /**
941
     * Vrací z FlexiBee sloupečky podle podmínek.
942
     *
943
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
944
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
945
     *                                     sloupečku
946
     * @return array
947
     */
948 View Code Duplication
    public function getAllFromFlexibee($conditions = null, $indexBy = 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...
949
    {
950
        if (is_int($conditions)) {
951
            $conditions = [$this->getmyKeyColumn() => $conditions];
952
        }
953
954
        $flexiData = $this->getFlexiData('', $conditions);
955
956
        if (!is_null($indexBy)) {
957
            $flexiData = $this->reindexArrayBy($flexiData);
958
        }
959
960
        return $flexiData;
961
    }
962
963
    /**
964
     * Vrací z FlexiBee sloupečky podle podmínek.
965
     *
966
     * @param string[] $columnsList seznam položek
967
     * @param array    $conditions  pole podmínek nebo ID záznamu
968
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
969
     *
970
     * @return array
971
     */
972
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
973
                                           $indexBy = null)
974
    {
975
        $detail = 'full';
976
977
        if (is_int($conditions)) {
978
            $conditions = [$this->getmyKeyColumn() => $conditions];
979
        }
980
981
        if ($columnsList != '*') {
982
            if (is_array($columnsList)) {
983
                if (!array_key_exists($indexBy, $columnsList)) {
984
                    $columnsList[] = $indexBy;
985
                }
986
                $columns = implode(',', array_unique($columnsList));
987
            } else {
988
                $columns = $columnsList;
989
            }
990
            $detail = 'custom:'.$columns;
991
        }
992
993
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
994
995
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
996
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
997
        }
998
999
        return $flexiData;
1000
    }
1001
1002
    /**
1003
     * Vrací kód záznamu.
1004
     *
1005
     * @param mixed $data
1006
     *
1007
     * @return string
1008
     */
1009
    public function getKod($data = null, $unique = true)
1010
    {
1011
        $kod = null;
1012
1013
        if (is_null($data)) {
1014
            $data = $this->getData();
1015
        }
1016
1017
        if (is_string($data)) {
1018
            $data = [$this->nameColumn => $data];
1019
        }
1020
1021
        if (isset($data['kod'])) {
1022
            $kod = $data['kod'];
1023
        } else {
1024
            if (isset($data[$this->nameColumn])) {
1025
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1026
                    \Ease\Sand::rip($data[$this->nameColumn]));
1027
            } else {
1028
                if (isset($data[$this->myKeyColumn])) {
1029
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1030
                }
1031
            }
1032
        }
1033
1034
        if (!strlen($kod)) {
1035
            $kod = 'NOTSET';
1036
        }
1037
1038
        if (strlen($kod) > 18) {
1039
            $kodfinal = strtoupper(substr($kod, 0, 18));
1040
        } else {
1041
            $kodfinal = strtoupper($kod);
1042
        }
1043
1044
        if ($unique) {
1045
            $counter = 0;
1046
            if (count($this->codes)) {
1047
                foreach ($this->codes as $codesearch => $keystring) {
1048
                    if (strstr($codesearch, $kodfinal)) {
1049
                        ++$counter;
1050
                    }
1051
                }
1052
            }
1053
            if ($counter) {
1054
                $kodfinal = $kodfinal.$counter;
1055
            }
1056
1057
            $this->codes[$kodfinal] = $kod;
1058
        }
1059
1060
        return $kodfinal;
1061
    }
1062
1063
    /**
1064
     * Write Operation Result.
1065
     *
1066
     * @param array  $resultData
1067
     * @param string $url        URL
1068
     * @return boolean Log save success
1069
     */
1070
    public function logResult($resultData = null, $url = null)
1071
    {
1072
        $logResult = false;
1073
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1074
            if (isset($resultData['message'])) {
1075
                $this->addStatusMessage($resultData['message'], 'warning');
1076
            }
1077
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1078
                'warning');
1079
            unset($url);
1080
        }
1081
        if (is_null($resultData)) {
1082
            $resultData = $this->lastResult;
1083
        }
1084
        if (isset($url)) {
1085
            $this->logger->addStatusMessage(urldecode($url));
1086
        }
1087
1088
        if (isset($resultData['results'])) {
1089
            $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...
1090
            if ($resultData['success'] == 'false') {
1091
                $status = 'error';
1092
            } else {
1093
                $status = 'success';
1094
            }
1095
            foreach ($resultData['results'] as $result) {
1096
                if (isset($result['request-id'])) {
1097
                    $rid = $result['request-id'];
1098
                } else {
1099
                    $rid = '';
1100
                }
1101
                if (isset($result['errors'])) {
1102
                    foreach ($result['errors'] as $error) {
1103
                        $message = $error['message'];
1104
                        if (isset($error['for'])) {
1105
                            $message .= ' for: '.$error['for'];
1106
                        }
1107
                        if (isset($error['value'])) {
1108
                            $message .= ' value:'.$error['value'];
1109
                        }
1110
                        if (isset($error['code'])) {
1111
                            $message .= ' code:'.$error['code'];
1112
                        }
1113
                        $this->addStatusMessage($rid.': '.$message, $status);
1114
                    }
1115
                }
1116
            }
1117
        }
1118
1119
        if (is_object($this->logger)) {
1120
            $logResult = $this->logger->flush(get_class($this));
1121
        }
1122
        return $logResult;
1123
    }
1124
1125
    /**
1126
     * Save RAW Curl Request & Response to files in Temp directory
1127
     */
1128
    public function saveDebugFiles()
1129
    {
1130
        $tmpdir = sys_get_temp_dir();
1131
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1132
            $this->postFields);
1133
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1134
            $this->lastCurlResponse);
1135
    }
1136
1137
    /**
1138
     * Připraví data pro odeslání do FlexiBee
1139
     * 
1140
     * @param string $data
1141
     */
1142
    public function setPostFields($data)
1143
    {
1144
        $this->postFields = $data;
0 ignored issues
show
Documentation Bug introduced by
It seems like $data of type string is incompatible with the declared type array of property $postFields.

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...
1145
    }
1146
1147
    /**
1148
     * Generuje fragment url pro filtrování.
1149
     *
1150
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1151
     *
1152
     * @param array  $data
1153
     * @param string $joiner default and/or
1154
     * @param string $defop  default operator
1155
     *
1156
     * @return string
1157
     */
1158
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1159
    {
1160
        $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...
1161
        $parts    = [];
1162
1163
        foreach ($data as $column => $value) {
1164
            if (is_integer($data[$column]) || is_float($data[$column])) {
1165
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1166
            } elseif (is_bool($data[$column])) {
1167
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1168
            } elseif (is_null($data[$column])) {
1169
                $parts[$column] = $column." is null";
1170
            } else {
1171
                switch ($value) {
1172
                    case '!null':
1173
                        $parts[$column] = $column." is not null";
1174
                        break;
1175
                    case 'is empty':
1176
                    case 'is not empty':
1177
                        $parts[$column] = $column.' '.$value;
1178
                        break;
1179
                    default:
1180
                        $parts[$column] = $column." $defop '".$data[$column]."'";
1181
                        break;
1182
                }
1183
        }
1184
        }
1185
1186
        $flexiUrl = implode(' '.$joiner.' ', $parts);
1187
1188
        return $flexiUrl;
1189
    }
1190
1191
    /**
1192
     * Vrací identifikátor objektu code: nebo id:
1193
     *
1194
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1195
     * @return string indentifikátor záznamu reprezentovaného objektem
1196
     */
1197
    public function __toString()
1198
    {
1199
        $myCode = $this->getDataValue('kod');
1200
        if ($myCode) {
1201
            $id = 'code:'.$myCode;
1202
        } else {
1203
            $id = $this->getDataValue('id');
1204
            if (is_null($id)) {
1205
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1206
                    'warning');
1207
            }
1208
        }
1209
        return $id;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $id; (object|integer|double|string|array|boolean|null) is incompatible with the return type of the parent method Ease\Sand::__toString of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1210
    }
1211
1212
    /**
1213
     * Gives you FlexiPeeHP class name for Given Evidence
1214
     *
1215
     * @param string $evidence
1216
     * @return string Class name
1217
     */
1218
    static public function evidenceToClassName($evidence)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
1219
    {
1220
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1221
    }
1222
1223
    /**
1224
     * Vrací hodnotu daného externího ID
1225
     *
1226
     * @param string $want Which ? If empty,you obtain the first one.
1227
     * @return string
1228
     */
1229
    public function getExternalID($want = null)
1230
    {
1231
        $extid = null;
1232
        $ids   = $this->getDataValue('external-ids');
1233
        if (is_null($want)) {
1234
            if (count($ids)) {
1235
                $extid = current($ids);
1236
            }
1237
        } else {
1238
            if (!is_null($ids)) {
1239
                foreach ($ids as $id) {
0 ignored issues
show
Bug introduced by
The expression $ids of type object|integer|double|string|array|boolean 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...
1240
                    if (strstr($id, 'ext:'.$want)) {
1241
                        $extid = str_replace('ext:'.$want.':', '', $id);
1242
                    }
1243
                }
1244
            }
1245
        }
1246
        return $extid;
1247
    }
1248
1249
    /**
1250
     * Obtain actual GlobalVersion
1251
     * Vrací aktuální globální verzi změn
1252
     *
1253
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1254
     * @return type
1255
     */
1256
    public function getGlobalVersion()
1257
    {
1258
        $globalVersion = null;
1259
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1260
            $this->getFlexiData(null,
1261
                ['add-global-version' => 'true', 'limit' => 1]);
1262
        }
1263
1264
        if (isset($this->lastResult['@globalVersion'])) {
1265
            $globalVersion = intval($this->lastResult['@globalVersion']);
1266
        }
1267
1268
        return $globalVersion;
1269
    }
1270
1271
    /**
1272
     * Return the same response format for one and multiplete results
1273
     * 
1274
     * @param array $responseRaw
1275
     * @return array
1276
     */
1277
    public function unifyResponseFormat($responseRaw)
1278
    {
1279
        $response = null;
1280
        $evidence = $this->getResponseEvidence();
1281
        if (is_array($responseRaw)) {
1282
            // Get response body root automatically
1283
            if (array_key_exists($this->nameSpace, $responseRaw)) { //Unifi response format
1284
                $responseBody = $responseRaw[$this->nameSpace];
1285
                if (array_key_exists($evidence, $responseBody)) {
1286
                    $evidenceContent = $responseBody[$evidence];
1287
                    if (array_key_exists(0, $evidenceContent)) {
1288
                        $response[$evidence] = $evidenceContent; //Multiplete Results
1289
                    } else {
1290
                        $response[$evidence][0] = $evidenceContent; //One result
1291
                    }
1292
                } else {
1293
                    $response = $responseBody;
1294
                }
1295
            } else {
1296
                $response = $responseRaw;
1297
            }
1298
        }
1299
        return $response;
1300
    }
1301
1302
    /**
1303
     * Obtain structure for current (or given) evidence
1304
     *
1305
     * @param string $evidence
1306
     * @return array Evidence structure
1307
     */
1308 View Code Duplication
    public function getColumnsInfo($evidence = 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...
1309
    {
1310
        $columnsInfo = null;
1311
        if (is_null($evidence)) {
1312
            $evidence = $this->getEvidence();
1313
        }
1314
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1315
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1316
            $columnsInfo = Properties::$$propsName;
1317
        }
1318
        return $columnsInfo;
1319
    }
1320
1321
    /**
1322
     * Obtain actions for current (or given) evidence
1323
     *
1324
     * @param string $evidence
1325
     * @return array Evidence structure
1326
     */
1327 View Code Duplication
    public function getActionsInfo($evidence = 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...
1328
    {
1329
        $actionsInfo = null;
1330
        if (is_null($evidence)) {
1331
            $evidence = $this->getEvidence();
1332
        }
1333
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1334
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1335
            $actionsInfo = Actions::$$propsName;
1336
        }
1337
        return $actionsInfo;
1338
    }
1339
1340
    /**
1341
     * Obtain info for current (or given) evidence
1342
     *
1343
     * @param string $evidence
1344
     * @return array Evidence info
1345
     */
1346 View Code Duplication
    public function getEvidenceInfo($evidence = 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...
1347
    {
1348
        $evidencesInfo = null;
1349
        if (is_null($evidence)) {
1350
            $evidence = $this->getEvidence();
1351
        }
1352
        if (isset(EvidenceList::$evidences[$evidence])) {
1353
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1354
        }
1355
        return $evidencesInfo;
1356
    }
1357
1358
    /**
1359
     * Obtain name for current (or given) evidence path
1360
     *
1361
     * @param string $evidence Evidence Path
1362
     * @return array Evidence info
1363
     */
1364 View Code Duplication
    public function getEvidenceName($evidence = 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...
1365
    {
1366
        $evidenceName = null;
1367
        if (is_null($evidence)) {
1368
            $evidence = $this->getEvidence();
1369
        }
1370
        if (isset(EvidenceList::$name[$evidence])) {
1371
            $evidenceName = EvidenceList::$name[$evidence];
1372
        }
1373
        return $evidenceName;
1374
    }
1375
1376
    /**
1377
     * Perform given action (if availble) on current evidence/record
1378
     * @url https://demo.flexibee.eu/devdoc/actions
1379
     * 
1380
     * @param string $action one of evidence actions
1381
     * @param string $method ext|int External method call operation in URL.
1382
     *                               Internal add the @action element to request body
1383
     */
1384
    public function performAction($action, $method = 'ext')
1385
    {
1386
        $result = null;
0 ignored issues
show
Unused Code introduced by
$result 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...
1387
        if (is_null($this->actionsAvailable)) {
1388
            $this->actionsAvailble = $this->getActionsInfo();
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1389
        }
1390
1391
        if (is_array($this->actionsAvailble) && array_key_exists($action,
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1392
                $this->actionsAvailble)) {
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1393
            switch ($this->actionsAvailble[$action]['actionMakesSense']) {
0 ignored issues
show
Bug introduced by
The property actionsAvailble does not seem to exist. Did you mean action?

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...
1394
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1395
                case 'ONLY_WITH_INSTANCE': //Add instance
1396
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1397
                    break;
1398
1399
                default:
1400
                    $urlSuffix = '/'.$action;
1401
                    break;
1402
            }
1403
1404
            switch ($method) {
1405
                case 'int':
1406
                    $this->setAction($action);
1407
                    $result = $this->performRequest(null, 'POST');
1408
                    break;
1409
1410
                default:
1411
                    $result = $this->performRequest($urlSuffix, 'GET');
1412
                    break;
1413
            }
1414
        } else {
1415
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1416
                $action, $this->getEvidence()));
1417
        }
1418
1419
        return $result;
1420
    }
1421
1422
}
1423