Completed
Push — master ( 90fa53...002064 )
by Vítězslav
16:43
created

FlexiBeeRO::updateApiURL()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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