Test Failed
Push — master ( fb85d2...ce342b )
by Vítězslav
02:45
created

FlexiBeeRO::parseResponse()   D

Complexity

Conditions 9
Paths 10

Size

Total Lines 34
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

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

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1688
    {
1689
        //Send Raw Request: Method/URL/Headers/Body
1690
        //With tail of FlexiBee log 
1691
        //To FlexiBee developers team
1692
        //By mail
1693
    }
1694
1695
}
1696