Test Failed
Push — master ( 83f818...9d7760 )
by Vítězslav
10:30
created

FlexiBeeRO::getFlexiData()   C

Complexity

Conditions 11
Paths 45

Size

Total Lines 40
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 28
nc 45
nop 2
dl 0
loc 40
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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