Test Failed
Push — master ( cae1c4...219209 )
by Vítězslav
04:19
created

FlexiBeeRO::setMyKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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