Completed
Push — master ( 1f3d87...76a3d1 )
by Vítězslav
08:19
created

FlexiBeeRO::performAction()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 26
nc 7
nop 2
dl 0
loc 37
rs 8.439
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.4.2';
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
            case 'evidence-list':
467
                $evidence = 'evidences';
468
                break;
469
            default:
470
                $evidence = $this->getEvidence();
471
                break;
472
        }
473
        return $evidence;
474
    }
475
476
    /**
477
     * Převede rekurzivně Objekt na pole.
478
     *
479
     * @param object|array $object
480
     *
481
     * @return array
482
     */
483
    public static function object2array($object)
484
    {
485
        $result = null;
486
        if (is_object($object)) {
487
            $objectData = get_object_vars($object);
488
            if (is_array($objectData) && count($objectData)) {
489
                $result = array_map('self::object2array', $objectData);
490
            }
491 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...
492
            if (is_array($object)) {
493
                foreach ($object as $item => $value) {
494
                    $result[$item] = self::object2array($value);
495
                }
496
            } else {
497
                $result = $object;
498
            }
499
        }
500
501
        return $result;
502
    }
503
504
    /**
505
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
506
     *
507
     * @param object|array $object
508
     *
509
     * @return array
510
     */
511
    public static function objectToID($object)
512
    {
513
        $result = null;
514
        if (is_object($object)) {
515
            $result = $object->__toString();
516 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...
517
            if (is_array($object)) {
518
                foreach ($object as $item => $value) {
519
                    $result[$item] = self::objectToID($value);
520
                }
521
            } else { //String
522
                $result = $object;
523
            }
524
        }
525
526
        return $result;
527
    }
528
529
    /**
530
     * Return basic URL for used Evidence
531
     *
532
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
533
     * @param string $urlSuffix
534
     */
535
    public function getEvidenceURL($urlSuffix = null)
536
    {
537
        if (is_null($urlSuffix)) {
538
            $urlSuffix = $this->getEvidence();
539
        } elseif ($urlSuffix[0] == ';') {
540
            $urlSuffix = $this->getEvidence().$urlSuffix;
541
        }
542
        return $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
543
    }
544
545
    /**
546
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
547
     *
548
     * @param string $urlSuffix část URL za identifikátorem firmy.
549
     * @param string $method    HTTP/REST metoda
550
     * @param string $format    Requested format
551
     * @return array|boolean Výsledek operace
552
     */
553
    public function performRequest($urlSuffix = null, $method = 'GET',
554
                                   $format = null)
555
    {
556
        $this->rowCount = null;
557
        $url            = $this->getEvidenceURL($urlSuffix);
558
559
        $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...
560
561
        if (is_null($format)) {
562
            $format = $this->format;
563
        }
564
565
        switch ($responseCode) {
566
            case 200:
567
            case 201:
568
                // Parse response
569
                $responseDecoded = [];
0 ignored issues
show
Unused Code introduced by
$responseDecoded 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...
570
571
                switch ($format) {
572
                    case 'json':
573
                        $responseDecoded = json_decode($this->lastCurlResponse,
574
                            true, 10);
575
                        if (($method == 'PUT') && isset($responseDecoded[$this->nameSpace][$this->resultField][0]['id'])) {
576
                            $this->lastInsertedID = $responseDecoded[$this->nameSpace][$this->resultField][0]['id'];
577
                            $this->setMyKey($this->lastInsertedID);
578
                        } else {
579
                            $this->lastInsertedID = null;
580
                            if (isset($responseDecoded[$this->nameSpace]['@rowCount'])) {
581
                                $this->rowCount = (int) $responseDecoded[$this->nameSpace]['@rowCount'];
582
                            }
583
                        }
584
                        $decodeError = json_last_error_msg();
585
                        if ($decodeError != 'No error') {
586
                            $this->addStatusMessage($decodeError, 'error');
587
                        }
588
                        break;
589
                    case 'xml':
590
                        if (strlen($this->lastCurlResponse)) {
591
                            $responseDecoded = self::xml2array($this->lastCurlResponse);
592
                        } else {
593
                            $responseDecoded = null;
594
                        }
595
                        break;
596
                    case 'txt':
597
                    default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
598
                        $responseDecoded = $this->lastCurlResponse;
599
                        break;
600
                }
601
602
603
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
604
605
                break;
606
607
            default: //Some goes wrong
608
                $this->lastCurlError = curl_error($this->curl);
609
                switch ($format) {
610
                    case 'json':
611
                        $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
612
                            function ($match) {
613
                            return mb_convert_encoding(pack('H*', $match[1]),
614
                                'UTF-8', 'UCS-2BE');
615
                        }, $this->lastCurlResponse);
616
                        $response = (json_encode(json_decode($response, true, 10),
617
                                JSON_PRETTY_PRINT));
618
                        break;
619
                    case 'xml':
620
                        if (strlen($this->lastCurlResponse)) {
621
                            $response = self::xml2array($this->lastCurlResponse);
622
                        }
623
                        break;
624
                    case 'txt':
625
                    default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
626
                        $response = $this->lastCurlResponse;
627
                        break;
628
                }
629
630
                if (is_array($response)) {
631
                    $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...
632
                } elseif (strlen($response) && ($response != 'null')) {
633
                    $result = urldecode(http_build_query(self::object2array(current(json_decode($response)))));
634
                } else {
635
                    $result = null;
636
                }
637
638
                if ($response == 'null') {
639
                    if ($this->lastResponseCode == 200) {
640
                        $response = true;
641
                    } else {
642
                        $response = null;
643
                    }
644
                } else {
645
                    if (is_string($response)) {
646
                        $response = self::object2array(current(json_decode($response)));
647
                    }
648
                }
649
650
                if (is_array($response) && ($this->lastResponseCode == 400)) {
651
                    $this->logResult($response, $url);
652
                } else {
653
                    $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
654
                            curl_getinfo($this->curl, CURLINFO_HTTP_CODE),
655
                            $result, $this->lastCurlError), 'error');
656
                    $this->addStatusMessage($url, 'info');
657
                    if (count($this->postFields)) {
658
                        if (is_array($result)) {
659
                            $this->addStatusMessage(urldecode(http_build_query($this->postFields)),
660
                                'debug');
661
                        } else {
662
                            $this->addStatusMessage(urldecode(http_build_query($this->getData())),
663
                                'debug');
664
                        }
665
                    }
666
                }
667
668
                break;
669
        }
670
671
        if ($this->debug === true) {
672
            $this->saveDebugFiles();
673
        }
674
675
        return $response;
676
    }
677
678
    /**
679
     * Vykonej HTTP požadavek
680
     *
681
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
682
     * @param string $url    URL požadavku
683
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
684
     * @param string $format požadovaný formát komunikace
685
     * @return int HTTP Response CODE
686
     */
687
    public function doCurlRequest($url, $method, $format = null)
688
    {
689
        if (is_null($format)) {
690
            $format = $this->format;
691
        }
692
        curl_setopt($this->curl, CURLOPT_URL, $url);
693
// Nastavení samotné operace
694
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
695
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
696
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
697
698
        $httpHeaders = $this->defaultHttpHeaders;
699
        switch ($format) {
700
            case 'json':
701
                $httpHeaders['Accept']       = 'application/json';
702
                $httpHeaders['Content-Type'] = 'application/json';
703
704
                break;
705
            case 'xml':
706
                $httpHeaders['Accept']       = 'application/xml';
707
                $httpHeaders['Content-Type'] = 'application/xml';
708
                break;
709
        }
710
711
        $httpHeadersFinal = [];
712
        foreach ($httpHeaders as $key => $value) {
713
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
714
                $value.= ' v'.self::$libVersion;
715
            }
716
            $httpHeadersFinal[] = $key.': '.$value;
717
        }
718
719
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
720
721
// Proveď samotnou operaci
722
        $this->lastCurlResponse = curl_exec($this->curl);
723
724
        $this->info = curl_getinfo($this->curl);
725
726
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
727
        return $this->lastResponseCode;
728
    }
729
730
    /**
731
     * Nastaví druh prováděné akce.
732
     *
733
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
734
     * @param string $action
735
     * @return boolean
736
     */
737
    public function setAction($action)
738
    {
739
        $result           = false;
740
        $actionsAvailable = $this->getActionsInfo();
741
        if (array_key_exists($action, $actionsAvailable)) {
742
            $actionInfo   = $actionsAvailable[$action];
0 ignored issues
show
Unused Code introduced by
$actionInfo 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...
743
            $this->action = $action;
744
            $result       = true;
745
        }
746
        return $result;
747
    }
748
749
    /**
750
     * Convert XML to array.
751
     *
752
     * @param string $xml
753
     *
754
     * @return array
755
     */
756
    public static function xml2array($xml)
757
    {
758
        $arr = [];
759
760
        if (is_string($xml)) {
761
            $xml = simplexml_load_string($xml);
762
        }
763
764
        foreach ($xml->children() as $r) {
765
            if (count($r->children()) == 0) {
766
                $arr[$r->getName()] = strval($r);
767
            } else {
768
                $arr[$r->getName()][] = self::xml2array($r);
769
            }
770
        }
771
772
        return $arr;
773
    }
774
775
    /**
776
     * Odpojení od FlexiBee.
777
     */
778
    public function disconnect()
779
    {
780
        if (is_resource($this->curl)) {
781
            curl_close($this->curl);
782
        }
783
        $this->curl = null;
784
    }
785
786
    public function __destruct()
787
    {
788
        $this->disconnect();
789
    }
790
791
    /**
792
     * Načte řádek dat z FlexiBee.
793
     *
794
     * @param int $recordID id požadovaného záznamu
795
     *
796
     * @return array
797
     */
798
    public function getFlexiRow($recordID)
799
    {
800
        $record   = null;
801
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
802
        if (isset($response[$this->evidence])) {
803
            $record = $response[$this->evidence][0];
804
        }
805
806
        return $record;
807
    }
808
809
    /**
810
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
811
     *
812
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
813
     * @param array $conditions pole podmínek   - rendrují se do ()
814
     * @param array $urlParams  pole parametrů  - rendrují za ?
815
     */
816
    public function extractUrlParams(&$conditions, &$urlParams)
817
    {
818
        foreach ($this->urlParams as $urlParam) {
819
            if (isset($conditions[$urlParam])) {
820
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
821
            }
822
        }
823
    }
824
825
    /**
826
     * Načte data z FlexiBee.
827
     *
828
     * @param string $suffix     dotaz
829
     * @param string|array $conditions Volitelný filtrovací výraz
830
     */
831
    public function getFlexiData($suffix = null, $conditions = null)
832
    {
833
        $urlParams = $this->defaultUrlParams;
834
        if (!is_null($conditions)) {
835
            if (is_array($conditions)) {
836
                $this->extractUrlParams($conditions, $urlParams);
837
                $conditions = $this->flexiUrl($conditions);
838
            }
839
840
            if (strlen($conditions) && ($conditions[0] != '/')) {
841
                $conditions = '/'.rawurlencode('('.($conditions).')');
842
            }
843
        } else {
844
            $conditions = '';
845
        }
846
        if (strlen($suffix)) {
847
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
848
                'GET');
849
        } else {
850
            $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
851
                'GET');
852
        }
853
        if (isset($transactions[$this->evidence])) {
854
            $result = $transactions[$this->evidence];
855
        } else {
856
            $result = $transactions;
857
        }
858
859
        return $result;
860
    }
861
862
    /**
863
     * Načte záznam z FlexiBee.
864
     *
865
     * @param int $id ID záznamu
866
     *
867
     * @return int počet načtených položek
868
     */
869 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...
870
    {
871
        $data = [];
872
        if (is_null($id)) {
873
            $id = $this->getMyKey();
874
        }
875
876
        $flexidata = $this->getFlexiData(null, '/'.$id);
877
        if (count($flexidata) == 1) {
878
            $data = current($flexidata);
879
        }
880
        return $this->takeData($data);
881
    }
882
883
    /**
884
     * Převede data do Json formátu pro FlexiBee.
885
     *
886
     * @param array $data
887
     *
888
     * @return string
889
     */
890
    public function jsonizeData($data)
891
    {
892
        $jsonize = [
893
            $this->nameSpace => [
894
                '@version' => $this->protoVersion,
895
                $this->evidence => $this->objectToID($data),
896
            ],
897
        ];
898
899
        if (!is_null($this->action)) {
900
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
901
            $this->action                                         = null;
902
        }
903
904
        return json_encode($jsonize);
905
    }
906
907
    /**
908
     * Test if given record ID exists in FlexiBee.
909
     *
910
     * @param string|int $identifer
911
     */
912
    public function idExists($identifer = null)
913
    {
914
        if (is_null($identifer)) {
915
            $identifer = $this->getMyKey();
916
        }
917
        $flexiData = $this->getFlexiData(
918
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
919
920
        return $flexiData;
921
    }
922
923
    /**
924
     * Test if given record exists in FlexiBee.
925
     *
926
     * @param array $data
927
     * @return boolean Record presence status
928
     */
929
    public function recordExists($data = null)
930
    {
931
932
        if (is_null($data)) {
933
            $data = $this->getData();
934
        }
935
936
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
937
            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...
938
939
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
940
            || !count($res[0])) {
941
            $found = false;
942
        } else {
943
            $found = true;
944
        }
945
        return $found;
946
    }
947
948
    /**
949
     * Vrací z FlexiBee sloupečky podle podmínek.
950
     *
951
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
952
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
953
     *                                     sloupečku
954
     * @return array
955
     */
956 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...
957
    {
958
        if (is_int($conditions)) {
959
            $conditions = [$this->getmyKeyColumn() => $conditions];
960
        }
961
962
        $flexiData = $this->getFlexiData('', $conditions);
963
964
        if (!is_null($indexBy)) {
965
            $flexiData = $this->reindexArrayBy($flexiData);
966
        }
967
968
        return $flexiData;
969
    }
970
971
    /**
972
     * Vrací z FlexiBee sloupečky podle podmínek.
973
     *
974
     * @param string[] $columnsList seznam položek
975
     * @param array    $conditions  pole podmínek nebo ID záznamu
976
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
977
     *
978
     * @return array
979
     */
980
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
981
                                           $indexBy = null)
982
    {
983
        $detail = 'full';
984
985
        if (is_int($conditions)) {
986
            $conditions = [$this->getmyKeyColumn() => $conditions];
987
        }
988
989
        if ($columnsList != '*') {
990
            if (is_array($columnsList)) {
991
                if (!is_null($indexBy) && !array_key_exists($indexBy,
992
                        $columnsList)) {
993
                    $columnsList[] = $indexBy;
994
                }
995
                $columns = implode(',', array_unique($columnsList));
996
            } else {
997
                $columns = $columnsList;
998
            }
999
            $detail = 'custom:'.$columns;
1000
        }
1001
1002
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
1003
1004
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1005
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1006
        }
1007
1008
        return $flexiData;
1009
    }
1010
1011
    /**
1012
     * Vrací kód záznamu.
1013
     *
1014
     * @param mixed $data
1015
     *
1016
     * @return string
1017
     */
1018
    public function getKod($data = null, $unique = true)
1019
    {
1020
        $kod = null;
1021
1022
        if (is_null($data)) {
1023
            $data = $this->getData();
1024
        }
1025
1026
        if (is_string($data)) {
1027
            $data = [$this->nameColumn => $data];
1028
        }
1029
1030
        if (isset($data['kod'])) {
1031
            $kod = $data['kod'];
1032
        } else {
1033
            if (isset($data[$this->nameColumn])) {
1034
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1035
                    \Ease\Sand::rip($data[$this->nameColumn]));
1036
            } else {
1037
                if (isset($data[$this->myKeyColumn])) {
1038
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1039
                }
1040
            }
1041
        }
1042
1043
        if (!strlen($kod)) {
1044
            $kod = 'NOTSET';
1045
        }
1046
1047
        if (strlen($kod) > 18) {
1048
            $kodfinal = strtoupper(substr($kod, 0, 18));
1049
        } else {
1050
            $kodfinal = strtoupper($kod);
1051
        }
1052
1053
        if ($unique) {
1054
            $counter = 0;
1055
            if (count($this->codes)) {
1056
                foreach ($this->codes as $codesearch => $keystring) {
1057
                    if (strstr($codesearch, $kodfinal)) {
1058
                        ++$counter;
1059
                    }
1060
                }
1061
            }
1062
            if ($counter) {
1063
                $kodfinal = $kodfinal.$counter;
1064
            }
1065
1066
            $this->codes[$kodfinal] = $kod;
1067
        }
1068
1069
        return $kodfinal;
1070
    }
1071
1072
    /**
1073
     * Write Operation Result.
1074
     *
1075
     * @param array  $resultData
1076
     * @param string $url        URL
1077
     * @return boolean Log save success
1078
     */
1079
    public function logResult($resultData = null, $url = null)
1080
    {
1081
        $logResult = false;
1082
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1083
            if (isset($resultData['message'])) {
1084
                $this->addStatusMessage($resultData['message'], 'warning');
1085
            }
1086
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1087
                'warning');
1088
            unset($url);
1089
        }
1090
        if (is_null($resultData)) {
1091
            $resultData = $this->lastResult;
1092
        }
1093
        if (isset($url)) {
1094
            $this->logger->addStatusMessage(urldecode($url));
1095
        }
1096
1097
        if (isset($resultData['results'])) {
1098
            $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...
1099
            if ($resultData['success'] == 'false') {
1100
                $status = 'error';
1101
            } else {
1102
                $status = 'success';
1103
            }
1104
            foreach ($resultData['results'] as $result) {
1105
                if (isset($result['request-id'])) {
1106
                    $rid = $result['request-id'];
1107
                } else {
1108
                    $rid = '';
1109
                }
1110
                if (isset($result['errors'])) {
1111
                    foreach ($result['errors'] as $error) {
1112
                        $message = $error['message'];
1113
                        if (isset($error['for'])) {
1114
                            $message .= ' for: '.$error['for'];
1115
                        }
1116
                        if (isset($error['value'])) {
1117
                            $message .= ' value:'.$error['value'];
1118
                        }
1119
                        if (isset($error['code'])) {
1120
                            $message .= ' code:'.$error['code'];
1121
                        }
1122
                        $this->addStatusMessage($rid.': '.$message, $status);
1123
                    }
1124
                }
1125
            }
1126
        }
1127
1128
        if (is_object($this->logger)) {
1129
            $logResult = $this->logger->flush(get_class($this));
1130
        }
1131
        return $logResult;
1132
    }
1133
1134
    /**
1135
     * Save RAW Curl Request & Response to files in Temp directory
1136
     */
1137
    public function saveDebugFiles()
1138
    {
1139
        $tmpdir = sys_get_temp_dir();
1140
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1141
            $this->postFields);
1142
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1143
            $this->lastCurlResponse);
1144
    }
1145
1146
    /**
1147
     * Připraví data pro odeslání do FlexiBee
1148
     * 
1149
     * @param string $data
1150
     */
1151
    public function setPostFields($data)
1152
    {
1153
        $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...
1154
    }
1155
1156
    /**
1157
     * Generuje fragment url pro filtrování.
1158
     *
1159
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1160
     *
1161
     * @param array  $data
1162
     * @param string $joiner default and/or
1163
     * @param string $defop  default operator
1164
     *
1165
     * @return string
1166
     */
1167
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1168
    {
1169
        $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...
1170
        $parts    = [];
1171
1172
        foreach ($data as $column => $value) {
1173
            if (is_integer($data[$column]) || is_float($data[$column])) {
1174
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1175
            } elseif (is_bool($data[$column])) {
1176
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1177
            } elseif (is_null($data[$column])) {
1178
                $parts[$column] = $column." is null";
1179
            } else {
1180
                switch ($value) {
1181
                    case '!null':
1182
                        $parts[$column] = $column." is not null";
1183
                        break;
1184
                    case 'is empty':
1185
                    case 'is not empty':
1186
                        $parts[$column] = $column.' '.$value;
1187
                        break;
1188
                    default:
1189
                        $parts[$column] = $column." $defop '".$data[$column]."'";
1190
                        break;
1191
                }
1192
            }
1193
        }
1194
1195
        $flexiUrl = implode(' '.$joiner.' ', $parts);
1196
1197
        return $flexiUrl;
1198
    }
1199
1200
    /**
1201
     * Obtain record/object identificator code: or id:
1202
     * Vrací identifikátor objektu code: nebo id:
1203
     *
1204
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1205
     * @return string indentifikátor záznamu reprezentovaného objektem
1206
     */
1207
    public function __toString()
1208
    {
1209
        $myCode = $this->getDataValue('kod');
1210
        if ($myCode) {
1211
            $id = 'code:'.$myCode;
1212
        } else {
1213
            $id = $this->getDataValue('id');
1214
            if (($this->debug === true) && is_null($id)) {
1215
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1216
                    'warning');
1217
            }
1218
        }
1219
        return strval($id);
1220
    }
1221
1222
    /**
1223
     * Gives you FlexiPeeHP class name for Given Evidence
1224
     *
1225
     * @param string $evidence
1226
     * @return string Class name
1227
     */
1228
    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...
1229
    {
1230
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1231
    }
1232
1233
    /**
1234
     * Vrací hodnotu daného externího ID
1235
     *
1236
     * @param string $want Which ? If empty,you obtain the first one.
1237
     * @return string
1238
     */
1239
    public function getExternalID($want = null)
1240
    {
1241
        $extid = null;
1242
        $ids   = $this->getDataValue('external-ids');
1243
        if (is_null($want)) {
1244
            if (count($ids)) {
1245
                $extid = current($ids);
1246
            }
1247
        } else {
1248
            if (!is_null($ids)) {
1249
                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...
1250
                    if (strstr($id, 'ext:'.$want)) {
1251
                        $extid = str_replace('ext:'.$want.':', '', $id);
1252
                    }
1253
                }
1254
            }
1255
        }
1256
        return $extid;
1257
    }
1258
1259
    /**
1260
     * Obtain actual GlobalVersion
1261
     * Vrací aktuální globální verzi změn
1262
     *
1263
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1264
     * @return type
1265
     */
1266
    public function getGlobalVersion()
1267
    {
1268
        $globalVersion = null;
1269
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1270
            $this->getFlexiData(null,
1271
                ['add-global-version' => 'true', 'limit' => 1]);
1272
        }
1273
1274
        if (isset($this->lastResult['@globalVersion'])) {
1275
            $globalVersion = intval($this->lastResult['@globalVersion']);
1276
        }
1277
1278
        return $globalVersion;
1279
    }
1280
1281
    /**
1282
     * Obtain content type of last response
1283
     *
1284
     * @return string
1285
     */
1286
    public function getResponseFormat()
1287
    {
1288
        if (isset($this->info['content_type'])) {
1289
            $responseFormat = $this->info['content_type'];
1290
        } else {
1291
            $responseFormat = null;
1292
        }
1293
        return $responseFormat;
1294
    }
1295
1296
    /**
1297
     * Return the same response format for one and multiplete results
1298
     * 
1299
     * @param array $responseRaw
1300
     * @return array
1301
     */
1302
    public function unifyResponseFormat($responseRaw)
1303
    {
1304
        $response = null;
1305
        $evidence = $this->getResponseEvidence();
1306
        if (is_array($responseRaw)) {
1307
            // Get response body root automatically
1308
            if (array_key_exists($this->nameSpace, $responseRaw)) { //Unifi response format
1309
                $responseBody = $responseRaw[$this->nameSpace];
1310
                if (array_key_exists($evidence, $responseBody)) {
1311
                    $evidenceContent = $responseBody[$evidence];
1312
                    if (array_key_exists(0, $evidenceContent)) {
1313
                        $response[$evidence] = $evidenceContent; //Multiplete Results
1314
                    } else {
1315
                        $response[$evidence][0] = $evidenceContent; //One result
1316
                    }
1317
                } else {
1318
                    $response = $responseBody;
1319
                }
1320
            } else {
1321
                $response = $responseRaw;
1322
            }
1323
        }
1324
        return $response;
1325
    }
1326
1327
    /**
1328
     * Obtain structure for current (or given) evidence
1329
     *
1330
     * @param string $evidence
1331
     * @return array Evidence structure
1332
     */
1333 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...
1334
    {
1335
        $columnsInfo = null;
1336
        if (is_null($evidence)) {
1337
            $evidence = $this->getEvidence();
1338
        }
1339
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1340
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1341
            $columnsInfo = Properties::$$propsName;
1342
        }
1343
        return $columnsInfo;
1344
    }
1345
1346
    /**
1347
     * Obtain actions for current (or given) evidence
1348
     *
1349
     * @param string $evidence
1350
     * @return array Evidence structure
1351
     */
1352 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...
1353
    {
1354
        $actionsInfo = null;
1355
        if (is_null($evidence)) {
1356
            $evidence = $this->getEvidence();
1357
        }
1358
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1359
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1360
            $actionsInfo = Actions::$$propsName;
1361
        }
1362
        return $actionsInfo;
1363
    }
1364
1365
    /**
1366
     * Obtain relations for current (or given) evidence
1367
     *
1368
     * @param string $evidence
1369
     * @return array Evidence structure
1370
     */
1371
    public function getRelationsInfo($evidence = null)
1372
    {
1373
        $relationsInfo = null;
1374
        if (is_null($evidence)) {
1375
            $evidence = $this->getEvidence();
1376
        }
1377
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1378
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1379
            $relationsInfo = Relations::$$propsName;
1380
        }
1381
        return $relationsInfo;
1382
    }
1383
1384
    /**
1385
     * Obtain info for current (or given) evidence
1386
     *
1387
     * @param string $evidence
1388
     * @return array Evidence info
1389
     */
1390 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...
1391
    {
1392
        $evidencesInfo = null;
1393
        if (is_null($evidence)) {
1394
            $evidence = $this->getEvidence();
1395
        }
1396
        if (isset(EvidenceList::$evidences[$evidence])) {
1397
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1398
        }
1399
        return $evidencesInfo;
1400
    }
1401
1402
    /**
1403
     * Obtain name for current (or given) evidence path
1404
     *
1405
     * @param string $evidence Evidence Path
1406
     * @return array Evidence info
1407
     */
1408 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...
1409
    {
1410
        $evidenceName = null;
1411
        if (is_null($evidence)) {
1412
            $evidence = $this->getEvidence();
1413
        }
1414
        if (isset(EvidenceList::$name[$evidence])) {
1415
            $evidenceName = EvidenceList::$name[$evidence];
1416
        }
1417
        return $evidenceName;
1418
    }
1419
1420
    /**
1421
     * Perform given action (if availble) on current evidence/record
1422
     * @url https://demo.flexibee.eu/devdoc/actions
1423
     * 
1424
     * @param string $action one of evidence actions
1425
     * @param string $method ext|int External method call operation in URL.
1426
     *                               Internal add the @action element to request body
1427
     */
1428
    public function performAction($action, $method = 'ext')
1429
    {
1430
        $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...
1431
1432
        $actionsAvailble = $this->getActionsInfo();
1433
1434
        if (is_array($actionsAvailble) && array_key_exists($action,
1435
                $actionsAvailble)) {
1436
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1437
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1438
                case 'ONLY_WITH_INSTANCE': //Add instance
1439
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1440
                    break;
1441
1442
                default:
1443
                    $urlSuffix = '/'.$action;
1444
                    break;
1445
            }
1446
1447
            switch ($method) {
1448
                case 'int':
1449
                    $this->setAction($action);
1450
                    $this->setPostFields($this->jsonizeData($this->getData()));
1451
                    $result = $this->performRequest(null, 'POST');
1452
                    break;
1453
1454
                default:
1455
                    $result = $this->performRequest($urlSuffix, 'GET');
1456
                    break;
1457
            }
1458
        } else {
1459
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1460
                $action, $this->getEvidence()));
1461
        }
1462
1463
        return $result;
1464
    }
1465
}
1466