Test Failed
Push — master ( dcd74b...32136e )
by Vítězslav
03:11
created

FlexiBeeRO::getRecordID()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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