Test Failed
Push — master ( bb67b0...f67d68 )
by Vítězslav
07:21
created

FlexiBeeRO::getFlexiBeeURL()   C

Complexity

Conditions 9
Paths 256

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 11
nc 256
nop 0
dl 0
loc 13
rs 6.4615
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-2017 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
     * Availble Formats.
27
     *
28
     * @see https://www.flexibee.eu/api/dokumentace/ref/format-types/
29
     * @var array formats known to flexibee
30
     */
31
    static public $formats = [
32
        'HTML' => ['desc' => 'HTML stránka pro zobrazení informací na webové stránce.',
33
            'suffix' => 'html', 'content-type' => 'text/html', 'import' => false],
34
        'XML' => ['desc' => 'Strojově čitelná struktura ve formátu XML.', 'suffix' => 'xml',
35
            'content-type' => 'application/xml', 'import' => true],
36
        'JSON' => ['desc' => 'Strojově čitelná struktura ve formátu JSON. ', 'suffix' => 'json',
37
            'content-type' => 'application/json', 'import' => true],
38
        'CSV' => ['desc' => 'Tabulkový výstup do formátu CSV (Column Separated Values).',
39
            'suffix' => 'csv', 'content-type' => 'text/csv', 'import' => true],
40
        'DBF' => ['desc' => 'Databázový výstup ve formátu DBF (dBase).', 'suffix' => 'dbf',
41
            'content-type' => 'application/dbf', 'import' => true],
42
        'XLS' => ['desc' => 'Tabulkový výstup ve formátu Excel.', 'suffix' => 'xls',
43
            'content-type' => 'application/ms-excel', 'import' => true],
44
        'ISDOC' => ['desc' => 'e-faktura ISDOC.', 'suffix' => 'isdoc', 'content-type' => 'application/x-isdoc',
45
            'import' => false],
46
        'ISDOCx' => ['desc' => 'e-faktura ISDOC s PDF přílohou', 'suffix' => 'isdocx',
47
            'content-type' => 'application/x-isdocx',
48
            'import' => false],
49
        'EDI' => ['desc' => 'Elektronická výměna data (EDI) ve formátu INHOUSE.',
50
            'suffix' => 'edi', 'content-type' => 'application/x-edi-inhouse', 'import' => 'objednavka-prijata'],
51
        'PDF' => ['desc' => 'Generování tiskového reportu. Jedná se o stejnou funkci která je dostupná v aplikaci. Export do PDF',
52
            'suffix' => 'pdf', 'content-type' => 'application/pdf', 'import' => false],
53
        'vCard' => ['desc' => 'Výstup adresáře do formátu elektronické vizitky vCard.',
54
            'suffix' => 'vcf', 'content-type' => 'text/vcard', 'import' => false],
55
        'iCalendar' => ['desc' => '"Výstup do kalendáře ve formátu iCalendar. Lze takto exportovat události, ale také třeba splatnosti u přijatých či vydaných faktur.',
56
            'suffix' => 'ical', 'content-type' => 'text/calendar', 'import' => false]
57
    ];
58
59
    /**
60
     * Základní namespace pro komunikaci s FlexiBee.
61
     * Basic namespace for communication with FlexiBee
62
     *
63
     * @var string Jmený prostor datového bloku odpovědi
64
     */
65
    public $nameSpace = 'winstrom';
66
67
    /**
68
     * URL of object data in FlexiBee
69
     * @var string url
70
     */
71
    public $apiURL = null;
72
73
    /**
74
     * Datový blok v poli odpovědi.
75
     * Data block in response field.
76
     *
77
     * @var string
78
     */
79
    public $resultField = 'results';
80
81
    /**
82
     * Verze protokolu použitého pro komunikaci.
83
     * Communication protocol version used.
84
     *
85
     * @var string Verze použitého API
86
     */
87
    public $protoVersion = '1.0';
88
89
    /**
90
     * Evidence užitá objektem.
91
     * Evidence used by object
92
     *
93
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
94
     * @var string
95
     */
96
    public $evidence = null;
97
98
    /**
99
     * Výchozí formát pro komunikaci.
100
     * Default communication format.
101
     *
102
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
103
     *
104
     * @var string json|xml|...
105
     */
106
    public $format = 'json';
107
108
    /**
109
     * Curl Handle.
110
     *
111
     * @var resource
112
     */
113
    public $curl = null;
114
115
    /**
116
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
117
     * @var string
118
     */
119
    public $company = null;
120
121
    /**
122
     * Server[:port]
123
     * @var string
124
     */
125
    public $url = null;
126
127
    /**
128
     * REST API Username
129
     * @var string
130
     */
131
    public $user = null;
132
133
    /**
134
     * REST API Password
135
     * @var string
136
     */
137
    public $password = null;
138
139
    /**
140
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
141
     */
142
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
143
144
    /**
145
     * Default additional request url parameters after question mark
146
     * 
147
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
148
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
149
     * @var array
150
     */
151
    public $defaultUrlParams = ['limit' => 0];
152
153
    /**
154
     * Identifikační řetězec.
155
     *
156
     * @var string
157
     */
158
    public $init = null;
159
160
    /**
161
     * Sloupeček s názvem.
162
     *
163
     * @var string
164
     */
165
    public $nameColumn = 'nazev';
166
167
    /**
168
     * Sloupeček obsahující datum vložení záznamu do shopu.
169
     *
170
     * @var string
171
     */
172
    public $myCreateColumn = 'false';
173
174
    /**
175
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
176
     *
177
     * @var string
178
     */
179
    public $myLastModifiedColumn = 'lastUpdate';
180
181
    /**
182
     * Klíčový idendifikátor záznamu.
183
     *
184
     * @var string
185
     */
186
    public $fbKeyColumn = 'id';
187
188
    /**
189
     * Informace o posledním HTTP requestu.
190
     *
191
     * @var *
192
     */
193
    public $info;
194
195
    /**
196
     * Informace o poslední HTTP chybě.
197
     *
198
     * @var string
199
     */
200
    public $lastCurlError = null;
201
202
    /**
203
     * Used codes storage.
204
     *
205
     * @var array
206
     */
207
    public $codes = null;
208
209
    /**
210
     * Last Inserted ID.
211
     *
212
     * @var int
213
     */
214
    public $lastInsertedID = null;
215
216
    /**
217
     * Default Line Prefix.
218
     *
219
     * @var string
220
     */
221
    public $prefix = '/c/';
222
223
    /**
224
     * Raw Content of last curl response
225
     * 
226
     * @var string
227
     */
228
    public $lastCurlResponse;
229
230
    /**
231
     * HTTP Response code of last request
232
     *
233
     * @var int
234
     */
235
    public $lastResponseCode = null;
236
237
    /**
238
     * Body data  for next curl POST operation
239
     *
240
     * @var string
241
     */
242
    protected $postFields = null;
243
244
    /**
245
     * Last operation result data or message(s)
246
     *
247
     * @var array
248
     */
249
    public $lastResult = null;
250
251
    /**
252
     * Nuber from  @rowCount
253
     * @var int
254
     */
255
    public $rowCount = null;
256
257
    /**
258
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
259
     * @var string
260
     */
261
    protected $action;
262
263
    /**
264
     * Pole akcí které podporuje ta která evidence
265
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
266
     * @var array
267
     */
268
    public $actionsAvailable = null;
269
270
    /**
271
     * Parmetry pro URL
272
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
273
     * @var array
274
     */
275
    public $urlParams = [
276
        'idUcetniObdobi',
277
        'dry-run',
278
        'fail-on-warning',
279
        'report-name',
280
        'report-lang',
281
        'report-sign',
282
        'detail', //See: https://www.flexibee.eu/api/dokumentace/ref/detail-levels
283
        'mode',
284
        'limit',
285
        'start',
286
        'order',
287
        'sort',
288
        'add-row-count',
289
        'relations',
290
        'includes',
291
        'use-ext-id',
292
        'use-internal-id',
293
        'stitky-as-ids',
294
        'only-ext-ids',
295
        'no-ext-ids',
296
        'no-ids',
297
        'code-as-id',
298
        'no-http-errors',
299
        'export-settings',
300
        'as-gui',
301
        'code-in-response',
302
        'add-global-version',
303
        'encoding',
304
        'delimeter',
305
        'format',
306
        'auth',
307
        'skupina-stitku',
308
        'dir',
309
        'relations',
310
        'relations',
311
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
312
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
313
        'inDesktopApp' // Note: Undocumented function (html only)
314
    ];
315
316
    /**
317
     * Class for read only interaction with FlexiBee.
318
     *
319
     * @param mixed $init default record id or initial data
320
     * @param array $options Connection settings override
321
     */
322
    public function __construct($init = null, $options = [])
323
    {
324
        $this->init = $init;
325
326
        parent::__construct();
327
        $this->setUp($options);
328
        $this->curlInit();
329
        if (!is_null($init)) {
330
            $this->processInit($init);
331
        }
332
    }
333
334
    /**
335
     * SetUp Object to be ready for connect
336
     *
337
     * @param array $options Object Options (company,url,user,password,evidence,
338
     *                                       prefix,debug)
339
     */
340
    public function setUp($options = [])
341
    {
342
        if (isset($options['company'])) {
343
            $this->company = $options['company'];
344
        } else {
345
            if (is_null($this->company) && defined('FLEXIBEE_COMPANY')) {
346
                $this->company = constant('FLEXIBEE_COMPANY');
347
            }
348
        }
349
        if (isset($options['url'])) {
350
            $this->url = $options['url'];
351
        } else {
352
            if (is_null($this->url) && defined('FLEXIBEE_URL')) {
353
                $this->url = constant('FLEXIBEE_URL');
354
            }
355
        }
356
        if (isset($options['user'])) {
357
            $this->user = $options['user'];
358
        } else {
359
            if (is_null($this->user) && defined('FLEXIBEE_LOGIN')) {
360
                $this->user = constant('FLEXIBEE_LOGIN');
361
            }
362
        }
363
        if (isset($options['password'])) {
364
            $this->password = $options['password'];
365
        } else {
366
            if (is_null($this->password) && defined('FLEXIBEE_PASSWORD')) {
367
                $this->password = constant('FLEXIBEE_PASSWORD');
368
            }
369
        }
370
        if (isset($options['evidence'])) {
371
            $this->setEvidence($options['evidence']);
372
        }
373
        if (isset($options['prefix'])) {
374
            $this->setPrefix($options['prefix']);
375
        }
376
        if (isset($options['debug'])) {
377
            $this->debug = $options['debug'];
378
        }
379
    }
380
381
    /**
382
     * Inicializace CURL
383
     */
384
    public function curlInit()
385
    {
386
        $this->curl = \curl_init(); // create curl resource
387
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
388
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
389
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
390
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
391
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
392
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
393
        curl_setopt($this->curl, CURLOPT_USERPWD,
394
            $this->user.':'.$this->password); // set username and password
395
    }
396
397
    /**
398
     * Zinicializuje objekt dle daných dat
399
     * 
400
     * @param mixed $init
401
     */
402
    public function processInit($init)
403
    {
404
        if (is_integer($init)) {
405
            $this->loadFromFlexiBee($init);
406
        } elseif (is_array($init)) {
407
            $this->takeData($init);
408
        } elseif (strstr($init, 'code:')) {
409
            $this->loadFromFlexiBee($init);
410
        }
411
    }
412
413
    /**
414
     * Set URL prefix
415
     *
416
     * @param string $prefix
417
     */
418
    public function setPrefix($prefix)
419
    {
420
        switch ($prefix) {
421
            case 'a': //Access
422
            case 'c': //Company
423
            case 'u': //User
424
            case 'g': //License Groups
425
            case 'admin':
426
            case 'status':
427
            case 'login-logout':
428
                $this->prefix = '/'.$prefix.'/';
429
                break;
430
            case null:
431
            case '':
432
            case '/':
433
                $this->prefix = '';
434
                break;
435
            default:
436
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
437
                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...
438
        }
439
    }
440
441
    /**
442
     * Set communication format.
443
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
444
     *
445
     * @param string $format
446
     */
447
    public function setFormat($format)
448
    {
449
        $this->format = $format;
450
    }
451
452
    /**
453
     * Nastaví Evidenci pro Komunikaci.
454
     * Set evidence for communication
455
     *
456
     * @param string $evidence evidence pathName to use
457
     * @return boolean evidence switching status
458
     */
459
    public function setEvidence($evidence)
460
    {
461
        $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...
462
        switch ($this->prefix) {
463
            case '/c/':
464
                if (array_key_exists($evidence, EvidenceList::$name)) {
465
                    $this->evidence = $evidence;
466
                    $result         = true;
467
                } else {
468
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
469
                        $evidence));
470
                }
471
                break;
472
            default:
473
                $this->evidence = $evidence;
474
                $result         = true;
475
                break;
476
        }
477
        $this->updateApiURL();
478
        return $result;
479
    }
480
481
    /**
482
     * Vrací právě používanou evidenci pro komunikaci
483
     * Obtain current used evidence
484
     *
485
     * @return string
486
     */
487
    public function getEvidence()
488
    {
489
        return $this->evidence;
490
    }
491
492
    /**
493
     * Set used company.
494
     * Nastaví Firmu.
495
     *
496
     * @param string $company
497
     */
498
    public function setCompany($company)
499
    {
500
        $this->company = $company;
501
    }
502
503
    /**
504
     * Obtain company now used
505
     * Vrací právě používanou firmu
506
     *
507
     * @return string
508
     */
509
    public function getCompany()
510
    {
511
        return $this->company;
512
    }
513
514
    /**
515
     * Vrací název evidence použité v odpovědích z FlexiBee
516
     *
517
     * @return string
518
     */
519
    public function getResponseEvidence()
520
    {
521
        switch ($this->evidence) {
522
            case 'c':
523
                $evidence = 'company';
524
                break;
525
            case 'evidence-list':
526
                $evidence = 'evidences';
527
                break;
528
            default:
529
                $evidence = $this->getEvidence();
530
                break;
531
        }
532
        return $evidence;
533
    }
534
535
    /**
536
     * Převede rekurzivně Objekt na pole.
537
     *
538
     * @param object|array $object
539
     *
540
     * @return array
541
     */
542
    public static function object2array($object)
543
    {
544
        $result = null;
545
        if (is_object($object)) {
546
            $objectData = get_object_vars($object);
547
            if (is_array($objectData) && count($objectData)) {
548
                $result = array_map('self::object2array', $objectData);
549
            }
550 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...
551
            if (is_array($object)) {
552
                foreach ($object as $item => $value) {
553
                    $result[$item] = self::object2array($value);
554
                }
555
            } else {
556
                $result = $object;
557
            }
558
        }
559
560
        return $result;
561
    }
562
563
    /**
564
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
565
     *
566
     * @param object|array $object
567
     *
568
     * @return array
569
     */
570
    public static function objectToID($object)
571
    {
572
        $result = null;
573
        if (is_object($object)) {
574
            $result = $object->__toString();
575 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...
576
            if (is_array($object)) {
577
                foreach ($object as $item => $value) {
578
                    $result[$item] = self::objectToID($value);
579
                }
580
            } else { //String
581
                $result = $object;
582
            }
583
        }
584
585
        return $result;
586
    }
587
588
    /**
589
     * Return basic URL for used Evidence
590
     *
591
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
592
     * @param string $urlSuffix
593
     */
594
    public function getEvidenceURL($urlSuffix = null)
595
    {
596
        if (is_null($urlSuffix)) {
597
            $urlSuffix = $this->getEvidence();
598
        } elseif ($urlSuffix[0] == ';') {
599
            $urlSuffix = $this->getEvidence().$urlSuffix;
600
        }
601
        return $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
602
    }
603
604
    /**
605
     * Update $this->apiURL
606
     */
607
    public function updateApiURL()
608
    {
609
        $this->apiURL = $this->getEvidenceURL();
610
        $id           = $this->__toString();
611
        if (!is_null($id)) {
612
            $this->apiURL .= '/'.urlencode($id);
613
        }
614
    }
615
616
    /**
617
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
618
     *
619
     * @param string $urlSuffix část URL za identifikátorem firmy.
620
     * @param string $method    HTTP/REST metoda
621
     * @param string $format    Requested format
622
     * @return array|boolean Výsledek operace
623
     */
624
    public function performRequest($urlSuffix = null, $method = 'GET',
625
                                   $format = null)
626
    {
627
        $response       = null;
628
        $result         = null;
629
        $this->rowCount = null;
630
631
        if (preg_match('/^http/', $urlSuffix)) {
632
            $url = $urlSuffix;
633
        } else {
634
            $url = $this->getEvidenceURL($urlSuffix);
635
        }
636
637
        $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...
638
639
        if (is_null($format)) {
640
            $format = $this->format;
641
        }
642
643
        switch ($responseCode) {
644
            case 200:
645
            case 201:
646
                // Parse response
647
                $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...
648
649
                switch ($format) {
650
                    case 'json':
651
                        $responseDecoded = json_decode($this->lastCurlResponse,
652
                            true, 10);
653
                        if (($method == 'PUT') && isset($responseDecoded[$this->nameSpace][$this->resultField][0]['id'])) {
654
                            $this->lastInsertedID = $responseDecoded[$this->nameSpace][$this->resultField][0]['id'];
655
                            $this->setMyKey($this->lastInsertedID);
656
                        } else {
657
                            $this->lastInsertedID = null;
658
                            if (isset($responseDecoded[$this->nameSpace]['@rowCount'])) {
659
                                $this->rowCount = (int) $responseDecoded[$this->nameSpace]['@rowCount'];
660
                            }
661
                        }
662
                        $decodeError = json_last_error_msg();
663
                        if ($decodeError != 'No error') {
664
                            $this->addStatusMessage($decodeError, 'error');
665
                        }
666
                        break;
667
                    case 'xml':
668
                        if (strlen($this->lastCurlResponse)) {
669
                            $responseDecoded = self::xml2array($this->lastCurlResponse);
670
                        } else {
671
                            $responseDecoded = null;
672
                        }
673
                        break;
674
                    case 'txt':
675
                    default:
676
                        $responseDecoded = $this->lastCurlResponse;
677
                        break;
678
                }
679
680
681
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
682
683
                break;
684
685
            default: //Some goes wrong
686
                $this->lastCurlError = curl_error($this->curl);
687
                switch ($format) {
688
                    case 'json':
689
                        $response = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
690
                            function ($match) {
691
                            return mb_convert_encoding(pack('H*', $match[1]),
692
                                'UTF-8', 'UCS-2BE');
693
                        }, $this->lastCurlResponse);
694
                        $response = (json_encode(json_decode($response, true, 10),
695
                                JSON_PRETTY_PRINT));
696
                        break;
697
                    case 'xml':
698
                        if (strlen($this->lastCurlResponse)) {
699
                            $response = self::xml2array($this->lastCurlResponse);
700
                        }
701
                        break;
702
                    case 'txt':
703
                    default:
704
                        $response = $this->lastCurlResponse;
705
                        break;
706
                }
707
708
                if (is_array($response)) {
709
                    $result = urldecode(http_build_query($response));
710
                } elseif (strlen($response) && ($response != 'null')) {
711
                    $decoded = json_decode($response);
712
                    if (is_array($decoded)) {
713
                        $result = urldecode(http_build_query(self::object2array(current($decoded))));
714
                    }
715
                } else {
716
                    $result = null;
717
                }
718
719
                if ($response == 'null') {
720
                    if ($this->lastResponseCode == 200) {
721
                        $response = true;
722
                    } else {
723
                        $response = null;
724
                    }
725
                } else {
726
                    if (is_string($response)) {
727
                        $decoded = json_decode($response);
728
                        if (is_array($decoded)) {
729
                            $response = self::object2array(current($decoded));
730
                        }
731
                    }
732
                }
733
734
                if (is_array($response) && ($this->lastResponseCode == 400)) {
735
                    $this->logResult($response, $url);
736
                } else {
737
                    $this->addStatusMessage(sprintf('Error (HTTP %d): <pre>%s</pre> %s',
738
                            curl_getinfo($this->curl, CURLINFO_HTTP_CODE),
739
                            $result, $this->lastCurlError), 'error');
740
                    $this->addStatusMessage($url, 'info');
741
                    if (count($this->postFields)) {
742
                        if (is_array($result)) {
743
                            $this->addStatusMessage(urldecode(http_build_query($this->postFields)),
744
                                'debug');
745
                        } else {
746
                            $this->addStatusMessage(urldecode(http_build_query($this->getData())),
747
                                'debug');
748
                        }
749
                    }
750
                }
751
752
                break;
753
        }
754
755
        if ($this->debug === true) {
756
            $this->saveDebugFiles();
757
        }
758
759
        return $response;
760
    }
761
762
    /**
763
     * Vykonej HTTP požadavek
764
     *
765
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
766
     * @param string $url    URL požadavku
767
     * @param strinf $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
768
     * @param string $format požadovaný formát komunikace
769
     * @return int HTTP Response CODE
770
     */
771
    public function doCurlRequest($url, $method, $format = null)
772
    {
773
        if (is_null($format)) {
774
            $format = $this->format;
775
        }
776
        curl_setopt($this->curl, CURLOPT_URL, $url);
777
// Nastavení samotné operace
778
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
779
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
780
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
781
782
        $httpHeaders = $this->defaultHttpHeaders;
783
784
        $formats = $this->reindexArrayBy(self::$formats, 'suffix');
785
786
        if (!isset($httpHeaders['Accept'])) {
787
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
788
        }
789
        if (!isset($httpHeaders['Content-Type'])) {
790
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
791
        }
792
        $httpHeadersFinal = [];
793
        foreach ($httpHeaders as $key => $value) {
794
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
795
                $value .= ' v'.self::$libVersion;
796
            }
797
            $httpHeadersFinal[] = $key.': '.$value;
798
        }
799
800
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
801
802
// Proveď samotnou operaci
803
        $this->lastCurlResponse = curl_exec($this->curl);
804
805
        $this->info = curl_getinfo($this->curl);
806
807
        $this->lastResponseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
808
        return $this->lastResponseCode;
809
    }
810
811
    /**
812
     * Nastaví druh prováděné akce.
813
     *
814
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
815
     * @param string $action
816
     * @return boolean
817
     */
818
    public function setAction($action)
819
    {
820
        $result           = false;
821
        $actionsAvailable = $this->getActionsInfo();
822
        if (array_key_exists($action, $actionsAvailable)) {
823
            $this->action = $action;
824
            $result       = true;
825
        }
826
        return $result;
827
    }
828
829
    /**
830
     * Convert XML to array.
831
     *
832
     * @param string $xml
833
     *
834
     * @return array
835
     */
836
    public static function xml2array($xml)
837
    {
838
        $arr = [];
839
840
        if (is_string($xml)) {
841
            $xml = simplexml_load_string($xml);
842
        }
843
844
        foreach ($xml->children() as $r) {
845
            if (count($r->children()) == 0) {
846
                $arr[$r->getName()] = strval($r);
847
            } else {
848
                $arr[$r->getName()][] = self::xml2array($r);
849
            }
850
        }
851
852
        return $arr;
853
    }
854
855
    /**
856
     * Odpojení od FlexiBee.
857
     */
858
    public function disconnect()
859
    {
860
        if (is_resource($this->curl)) {
861
            curl_close($this->curl);
862
        }
863
        $this->curl = null;
864
    }
865
866
    /**
867
     * Disconnect CURL befere pass away
868
     */
869
    public function __destruct()
870
    {
871
        $this->disconnect();
872
    }
873
874
    /**
875
     * Načte řádek dat z FlexiBee.
876
     *
877
     * @param int $recordID id požadovaného záznamu
878
     *
879
     * @return array
880
     */
881
    public function getFlexiRow($recordID)
882
    {
883
        $record   = null;
884
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
885
        if (isset($response[$this->evidence])) {
886
            $record = $response[$this->evidence][0];
887
        }
888
889
        return $record;
890
    }
891
892
    /**
893
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
894
     *
895
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
896
     * @param array $conditions pole podmínek   - rendrují se do ()
897
     * @param array $urlParams  pole parametrů  - rendrují za ?
898
     */
899
    public function extractUrlParams(&$conditions, &$urlParams)
900
    {
901
        foreach ($this->urlParams as $urlParam) {
902
            if (isset($conditions[$urlParam])) {
903
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
904
            }
905
        }
906
    }
907
908
    /**
909
     * Načte data z FlexiBee.
910
     *
911
     * @param string $suffix     dotaz
912
     * @param string|array $conditions Volitelný filtrovací výraz
913
     */
914
    public function getFlexiData($suffix = null, $conditions = null)
915
    {
916
        $urlParams = $this->defaultUrlParams;
917
        if (!is_null($conditions)) {
918
            if (is_array($conditions)) {
919
                $this->extractUrlParams($conditions, $urlParams);
920
                $conditions = $this->flexiUrl($conditions);
921
            }
922
923
            if (strlen($conditions) && ($conditions[0] != '/')) {
924
                $conditions = '/'.rawurlencode('('.($conditions).')');
925
            }
926
        } else {
927
            $conditions = '';
928
        }
929
930
        if (preg_match('/^http/', $suffix)) {
931
            $transactions = $this->performRequest($suffix, 'GET');
932
        } else {
933
            if (strlen($suffix)) {
934
                $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
935
                    'GET');
936
            } else {
937
                $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
938
                    'GET');
939
            }
940
        }
941
        if (isset($transactions[$this->evidence])) {
942
            $result = $transactions[$this->evidence];
943
        } else {
944
            $result = $transactions;
945
        }
946
947
        return $result;
948
    }
949
950
    /**
951
     * Načte záznam z FlexiBee.
952
     *
953
     * @param int $id ID záznamu
954
     *
955
     * @return int počet načtených položek
956
     */
957
    public function loadFromFlexiBee($id = null)
958
    {
959
        $data = [];
960
        if (is_null($id)) {
961
            $id = $this->getMyKey();
962
        }
963
964
        $flexidata    = $this->getFlexiData(null, '/'.$id);
965
        $this->apiURL = $this->info['url'];
966
        if (is_array($flexidata) && (count($flexidata) == 1)) {
967
            $data = current($flexidata);
968
        }
969
        return $this->takeData($data);
970
    }
971
972
    /**
973
     * Převede data do Json formátu pro FlexiBee.
974
     * Convert data to FlexiBee like Json format
975
     *
976
     * @param array $data
977
     *
978
     * @return string
979
     */
980
    public function jsonizeData($data)
981
    {
982
        $jsonize = [
983
            $this->nameSpace => [
984
                '@version' => $this->protoVersion,
985
                $this->evidence => $this->objectToID($data),
986
            ],
987
        ];
988
989
        if (!is_null($this->action)) {
990
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
991
            $this->action                                         = null;
992
        }
993
994
        return json_encode($jsonize);
995
    }
996
997
    /**
998
     * Test if given record ID exists in FlexiBee.
999
     *
1000
     * @param string|int $identifer
1001
     */
1002
    public function idExists($identifer = null)
1003
    {
1004
        if (is_null($identifer)) {
1005
            $identifer = $this->getMyKey();
1006
        }
1007
        $flexiData = $this->getFlexiData(
1008
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
1009
1010
        return $flexiData;
1011
    }
1012
1013
    /**
1014
     * Test if given record exists in FlexiBee.
1015
     *
1016
     * @param array $data
1017
     * @return boolean Record presence status
1018
     */
1019
    public function recordExists($data = null)
1020
    {
1021
1022
        if (is_null($data)) {
1023
            $data = $this->getData();
1024
        }
1025
1026
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1027
            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...
1028
1029
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1030
            || !count($res[0])) {
1031
            $found = false;
1032
        } else {
1033
            $found = true;
1034
        }
1035
        return $found;
1036
    }
1037
1038
    /**
1039
     * Vrací z FlexiBee sloupečky podle podmínek.
1040
     *
1041
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1042
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1043
     *                                     sloupečku
1044
     * @return array
1045
     */
1046
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1047
    {
1048
        if (is_int($conditions)) {
1049
            $conditions = [$this->getmyKeyColumn() => $conditions];
1050
        }
1051
1052
        $flexiData = $this->getFlexiData('', $conditions);
1053
1054
        if (!is_null($indexBy)) {
1055
            $flexiData = $this->reindexArrayBy($flexiData);
1056
        }
1057
1058
        return $flexiData;
1059
    }
1060
1061
    /**
1062
     * Vrací z FlexiBee sloupečky podle podmínek.
1063
     *
1064
     * @param string[] $columnsList seznam položek
1065
     * @param array    $conditions  pole podmínek nebo ID záznamu
1066
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1067
     *
1068
     * @return array
1069
     */
1070
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
1071
                                           $indexBy = null)
1072
    {
1073
        $detail = 'full';
1074
1075
        if (is_int($conditions)) {
1076
            $conditions = [$this->getmyKeyColumn() => $conditions];
1077
        }
1078
1079
        if ($columnsList != '*') {
1080
            if (is_array($columnsList)) {
1081
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1082
                        $columnsList)) {
1083
                    $columnsList[] = $indexBy;
1084
                }
1085
                $columns = implode(',', array_unique($columnsList));
1086
            } else {
1087
                $columns = $columnsList;
1088
            }
1089
            $detail = 'custom:'.$columns;
1090
        }
1091
1092
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
1093
1094
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1095
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1096
        }
1097
1098
        return $flexiData;
1099
    }
1100
1101
    /**
1102
     * Vrací kód záznamu.
1103
     *
1104
     * @param mixed $data
1105
     *
1106
     * @return string
1107
     */
1108
    public function getKod($data = null, $unique = true)
1109
    {
1110
        $kod = null;
1111
1112
        if (is_null($data)) {
1113
            $data = $this->getData();
1114
        }
1115
1116
        if (is_string($data)) {
1117
            $data = [$this->nameColumn => $data];
1118
        }
1119
1120
        if (isset($data['kod'])) {
1121
            $kod = $data['kod'];
1122
        } else {
1123
            if (isset($data[$this->nameColumn])) {
1124
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1125
                    \Ease\Sand::rip($data[$this->nameColumn]));
1126
            } else {
1127
                if (isset($data[$this->myKeyColumn])) {
1128
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1129
                }
1130
            }
1131
        }
1132
1133
        if (!strlen($kod)) {
1134
            $kod = 'NOTSET';
1135
        }
1136
1137
        if (strlen($kod) > 18) {
1138
            $kodfinal = strtoupper(substr($kod, 0, 18));
1139
        } else {
1140
            $kodfinal = strtoupper($kod);
1141
        }
1142
1143
        if ($unique) {
1144
            $counter = 0;
1145
            if (count($this->codes)) {
1146
                foreach ($this->codes as $codesearch => $keystring) {
1147
                    if (strstr($codesearch, $kodfinal)) {
1148
                        ++$counter;
1149
                    }
1150
                }
1151
            }
1152
            if ($counter) {
1153
                $kodfinal = $kodfinal.$counter;
1154
            }
1155
1156
            $this->codes[$kodfinal] = $kod;
1157
        }
1158
1159
        return $kodfinal;
1160
    }
1161
1162
    /**
1163
     * Write Operation Result.
1164
     *
1165
     * @param array  $resultData
1166
     * @param string $url        URL
1167
     * @return boolean Log save success
1168
     */
1169
    public function logResult($resultData = null, $url = null)
1170
    {
1171
        $logResult = false;
1172
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1173
            if (isset($resultData['message'])) {
1174
                $this->addStatusMessage($resultData['message'], 'warning');
1175
            }
1176
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1177
                'warning');
1178
            unset($url);
1179
        }
1180
        if (is_null($resultData)) {
1181
            $resultData = $this->lastResult;
1182
        }
1183
        if (isset($url)) {
1184
            $this->logger->addStatusMessage(urldecode($url));
1185
        }
1186
1187
        if (isset($resultData['results'])) {
1188
            $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...
1189
            if ($resultData['success'] == 'false') {
1190
                $status = 'error';
1191
            } else {
1192
                $status = 'success';
1193
            }
1194
            foreach ($resultData['results'] as $result) {
1195
                if (isset($result['request-id'])) {
1196
                    $rid = $result['request-id'];
1197
                } else {
1198
                    $rid = '';
1199
                }
1200
                if (isset($result['errors'])) {
1201
                    foreach ($result['errors'] as $error) {
1202
                        $message = $error['message'];
1203
                        if (isset($error['for'])) {
1204
                            $message .= ' for: '.$error['for'];
1205
                        }
1206
                        if (isset($error['value'])) {
1207
                            $message .= ' value:'.$error['value'];
1208
                        }
1209
                        if (isset($error['code'])) {
1210
                            $message .= ' code:'.$error['code'];
1211
                        }
1212
                        $this->addStatusMessage($rid.': '.$message, $status);
1213
                    }
1214
                }
1215
            }
1216
        }
1217
        return $logResult;
1218
    }
1219
1220
    /**
1221
     * Save RAW Curl Request & Response to files in Temp directory
1222
     */
1223
    public function saveDebugFiles()
1224
    {
1225
        $tmpdir = sys_get_temp_dir();
1226
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1227
            $this->postFields);
1228
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1229
            $this->lastCurlResponse);
1230
    }
1231
1232
    /**
1233
     * Připraví data pro odeslání do FlexiBee
1234
     * 
1235
     * @param string $data
1236
     */
1237
    public function setPostFields($data)
1238
    {
1239
        $this->postFields = $data;
1240
    }
1241
1242
    /**
1243
     * Generuje fragment url pro filtrování.
1244
     *
1245
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1246
     *
1247
     * @param array  $data
1248
     * @param string $joiner default and/or
1249
     * @param string $defop  default operator
1250
     *
1251
     * @return string
1252
     */
1253
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1254
    {
1255
        $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...
1256
        $parts    = [];
1257
1258
        foreach ($data as $column => $value) {
1259
            if (is_integer($data[$column]) || is_float($data[$column])) {
1260
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1261
            } elseif (is_bool($data[$column])) {
1262
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1263
            } elseif (is_null($data[$column])) {
1264
                $parts[$column] = $column." is null";
1265
            } else {
1266
                switch ($value) {
1267
                    case '!null':
1268
                        $parts[$column] = $column." is not null";
1269
                        break;
1270
                    case 'is empty':
1271
                    case 'is not empty':
1272
                        $parts[$column] = $column.' '.$value;
1273
                        break;
1274
                    default:
1275
                        $parts[$column] = $column." $defop '".$data[$column]."'";
1276
                        break;
1277
                }
1278
            }
1279
        }
1280
1281
        $flexiUrl = implode(' '.$joiner.' ', $parts);
1282
1283
        return $flexiUrl;
1284
    }
1285
1286
    /**
1287
     * Obtain record/object identificator code: or id:
1288
     * Vrací identifikátor objektu code: nebo id:
1289
     *
1290
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1291
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1292
     */
1293
    public function getRecordID()
1294
    {
1295
        $myCode = $this->getDataValue('kod');
1296
        if ($myCode) {
1297
            $id = 'code:'.$myCode;
1298
        } else {
1299
            $id = $this->getDataValue('id');
1300
            if (($this->debug === true) && is_null($id)) {
1301
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1302
                    'warning');
1303
            }
1304
        }
1305
        return is_numeric($id) ? intval($id) : strval($id);
1306
    }
1307
1308
    /**
1309
     * Obtain record/object identificator code: or id:
1310
     * Vrací identifikátor objektu code: nebo id:
1311
     *
1312
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1313
     * @return string indentifikátor záznamu reprezentovaného objektem
1314
     */
1315
    public function __toString()
1316
    {
1317
        return strval($this->getRecordID());
1318
    }
1319
1320
    /**
1321
     * Gives you FlexiPeeHP class name for Given Evidence
1322
     *
1323
     * @param string $evidence
1324
     * @return string Class name
1325
     */
1326
    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...
1327
    {
1328
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1329
    }
1330
1331
    /**
1332
     * Vrací hodnotu daného externího ID
1333
     *
1334
     * @param string $want Which ? If empty,you obtain the first one.
1335
     * @return string
1336
     */
1337
    public function getExternalID($want = null)
1338
    {
1339
        $extid = null;
1340
        $ids   = $this->getDataValue('external-ids');
1341
        if (is_null($want)) {
1342
            if (count($ids)) {
1343
                $extid = current($ids);
1344
            }
1345
        } else {
1346
            if (!is_null($ids) && is_array($ids)) {
1347
                foreach ($ids as $id) {
1348
                    if (strstr($id, 'ext:'.$want)) {
1349
                        $extid = str_replace('ext:'.$want.':', '', $id);
1350
                    }
1351
                }
1352
            }
1353
        }
1354
        return $extid;
1355
    }
1356
1357
    /**
1358
     * Obtain actual GlobalVersion
1359
     * Vrací aktuální globální verzi změn
1360
     *
1361
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1362
     * @return type
1363
     */
1364
    public function getGlobalVersion()
1365
    {
1366
        $globalVersion = null;
1367
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1368
            $this->getFlexiData(null,
1369
                ['add-global-version' => 'true', 'limit' => 1]);
1370
        }
1371
1372
        if (isset($this->lastResult['@globalVersion'])) {
1373
            $globalVersion = intval($this->lastResult['@globalVersion']);
1374
        }
1375
1376
        return $globalVersion;
1377
    }
1378
1379
    /**
1380
     * Obtain content type of last response
1381
     *
1382
     * @return string
1383
     */
1384
    public function getResponseFormat()
1385
    {
1386
        if (isset($this->info['content_type'])) {
1387
            $responseFormat = $this->info['content_type'];
1388
        } else {
1389
            $responseFormat = null;
1390
        }
1391
        return $responseFormat;
1392
    }
1393
1394
    /**
1395
     * Return the same response format for one and multiplete results
1396
     * 
1397
     * @param array $responseRaw
1398
     * @return array
1399
     */
1400
    public function unifyResponseFormat($responseRaw)
1401
    {
1402
        $response = null;
1403
        $evidence = $this->getResponseEvidence();
1404
        if (is_array($responseRaw)) {
1405
            // Get response body root automatically
1406
            if (array_key_exists($this->nameSpace, $responseRaw)) { //Unifi response format
1407
                $responseBody = $responseRaw[$this->nameSpace];
1408
                if (array_key_exists($evidence, $responseBody)) {
1409
                    $evidenceContent = $responseBody[$evidence];
1410
                    if (array_key_exists(0, $evidenceContent)) {
1411
                        $response[$evidence] = $evidenceContent; //Multiplete Results
1412
                    } else {
1413
                        $response[$evidence][0] = $evidenceContent; //One result
1414
                    }
1415
                } else {
1416
                    if (isset($responseBody['priloha'])) {
1417
                        $response = $responseBody['priloha'];
1418
                    } else {
1419
                        $response = $responseBody;
1420
                    }
1421
                }
1422
            } else {
1423
                $response = $responseRaw;
1424
            }
1425
        }
1426
        return $response;
1427
    }
1428
1429
    /**
1430
     * Obtain structure for current (or given) evidence
1431
     *
1432
     * @param string $evidence
1433
     * @return array Evidence structure
1434
     */
1435 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...
1436
    {
1437
        $columnsInfo = null;
1438
        if (is_null($evidence)) {
1439
            $evidence = $this->getEvidence();
1440
        }
1441
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1442
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1443
            $columnsInfo = Properties::$$propsName;
1444
        }
1445
        return $columnsInfo;
1446
    }
1447
1448
    /**
1449
     * Obtain actions for current (or given) evidence
1450
     *
1451
     * @param string $evidence
1452
     * @return array Evidence structure
1453
     */
1454 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...
1455
    {
1456
        $actionsInfo = null;
1457
        if (is_null($evidence)) {
1458
            $evidence = $this->getEvidence();
1459
        }
1460
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1461
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1462
            $actionsInfo = Actions::$$propsName;
1463
        }
1464
        return $actionsInfo;
1465
    }
1466
1467
    /**
1468
     * Obtain relations for current (or given) evidence
1469
     *
1470
     * @param string $evidence
1471
     * @return array Evidence structure
1472
     */
1473
    public function getRelationsInfo($evidence = null)
1474
    {
1475
        $relationsInfo = null;
1476
        if (is_null($evidence)) {
1477
            $evidence = $this->getEvidence();
1478
        }
1479
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1480
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1481
            $relationsInfo = Relations::$$propsName;
1482
        }
1483
        return $relationsInfo;
1484
    }
1485
1486
    /**
1487
     * Obtain info for current (or given) evidence
1488
     *
1489
     * @param string $evidence
1490
     * @return array Evidence info
1491
     */
1492 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...
1493
    {
1494
        $evidencesInfo = null;
1495
        if (is_null($evidence)) {
1496
            $evidence = $this->getEvidence();
1497
        }
1498
        if (isset(EvidenceList::$evidences[$evidence])) {
1499
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1500
        }
1501
        return $evidencesInfo;
1502
    }
1503
1504
    /**
1505
     * Obtain name for current (or given) evidence path
1506
     *
1507
     * @param string $evidence Evidence Path
1508
     * @return array Evidence info
1509
     */
1510 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...
1511
    {
1512
        $evidenceName = null;
1513
        if (is_null($evidence)) {
1514
            $evidence = $this->getEvidence();
1515
        }
1516
        if (isset(EvidenceList::$name[$evidence])) {
1517
            $evidenceName = EvidenceList::$name[$evidence];
1518
        }
1519
        return $evidenceName;
1520
    }
1521
1522
    /**
1523
     * Perform given action (if availble) on current evidence/record
1524
     * @url https://demo.flexibee.eu/devdoc/actions
1525
     * 
1526
     * @param string $action one of evidence actions
1527
     * @param string $method ext|int External method call operation in URL.
1528
     *                               Internal add the @action element to request body
1529
     */
1530
    public function performAction($action, $method = 'ext')
1531
    {
1532
        $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...
1533
1534
        $actionsAvailble = $this->getActionsInfo();
1535
1536
        if (is_array($actionsAvailble) && array_key_exists($action,
1537
                $actionsAvailble)) {
1538
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1539
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1540
                case 'ONLY_WITH_INSTANCE': //Add instance
1541
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1542
                    break;
1543
1544
                default:
1545
                    $urlSuffix = '/'.$action;
1546
                    break;
1547
            }
1548
1549
            switch ($method) {
1550
                case 'int':
1551
                    $this->setAction($action);
1552
                    $this->setPostFields($this->jsonizeData($this->getData()));
1553
                    $result = $this->performRequest(null, 'POST');
1554
                    break;
1555
1556
                default:
1557
                    $result = $this->performRequest($urlSuffix, 'GET');
1558
                    break;
1559
            }
1560
        } else {
1561
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1562
                $action, $this->getEvidence()));
1563
        }
1564
1565
        return $result;
1566
    }
1567
1568
    /**
1569
     * Save current object to file
1570
     *
1571
     * @param string $destfile path to file
1572
     */
1573
    public function saveResponseToFile($destfile)
1574
    {
1575
        if (strlen($this->lastCurlResponse)) {
1576
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
0 ignored issues
show
Documentation introduced by
'GET' 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...
1577
        }
1578
        file_put_contents($destfile, $this->lastCurlResponse);
1579
    }
1580
1581
    /**
1582
     * Obtain established relations listing
1583
     *
1584
     * @return array Null or Relations
1585
     */
1586
    public function getVazby()
1587
    {
1588
        $vazby = $this->getDataValue('vazby');
1589
        if (is_null($vazby)) {
1590
            $vazby = $this->getColumnsFromFlexibee('*',
0 ignored issues
show
Documentation introduced by
'*' is of type string, but the function expects a array<integer,string>.

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...
1591
                ['relations' => 'vazby', 'id' => $this->getRecordID()]);
1592
            $vazby = $vazby[0]['vazby'];
1593
        }
1594
        return $vazby;
1595
    }
1596
1597
    /**
1598
     * Gives You URL for Current Record in FlexiBee web interface
1599
     *
1600
     * @return string url
1601
     */
1602
    public function getFlexiBeeURL()
1603
    {
1604
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1605
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1606
                : '';
1607
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1608
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1609
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1610
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1611
        $pass       = ($user || $pass) ? "$pass@" : '';
1612
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1613
        return $scheme.$user.$pass.$host.$port.$path;
1614
    }
1615
}
1616