Test Failed
Push — master ( 0e444f...d3234c )
by Vítězslav
02:49
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
    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 = 'evidence';
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 (!empty($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->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['@rowCount'])) {
693
                        $this->rowCount = (int) $responseDecoded['@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
                if (is_array($responseDecoded)) {
710
                    $this->parseError($responseDecoded);
711
                }
712
                $this->logResult($responseDecoded,$this->curlInfo['url']);
713
                break;
714
        }
715
        return $response;
716
    }
717
718
719
    /**
720
     * Parse error message response
721
     *
722
     * @param array $responseDecoded
723
     * @return int number of errors processed
724
     */
725
    public function parseError(array $responseDecoded)
726
    {
727
        if (array_key_exists('results', $responseDecoded)) {
728
            $this->errors = $responseDecoded['results'][0]['errors'];
729
        } else {
730
            $this->errors = [['message' => $responseDecoded['message']]];
731
        }
732
        return count($this->errors);
733
    }
734
735
    /**
736
     * Vykonej HTTP požadavek
737
     *
738
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
739
     * @param string $url    URL požadavku
740
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
741
     * @param string $format požadovaný formát komunikace
742
     * @return int HTTP Response CODE
743
     */
744
    public function doCurlRequest($url, $method, $format = null)
745
    {
746
        if (is_null($format)) {
747
            $format = $this->format;
748
        }
749
        curl_setopt($this->curl, CURLOPT_URL, $url);
750
// Nastavení samotné operace
751
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
752
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
753
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
754
755
        $httpHeaders = $this->defaultHttpHeaders;
756
757
        $formats = $this->reindexArrayBy(Formats::$formats, 'suffix');
758
759
        if (!isset($httpHeaders['Accept'])) {
760
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
761
        }
762
        if (!isset($httpHeaders['Content-Type'])) {
763
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
764
        }
765
        $httpHeadersFinal = [];
766
        foreach ($httpHeaders as $key => $value) {
767
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
768
                $value .= ' v'.self::$libVersion;
769
            }
770
            $httpHeadersFinal[] = $key.': '.$value;
771
        }
772
773
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
774
775
// Proveď samotnou operaci
776
        $this->lastCurlResponse = curl_exec($this->curl);
777
        $this->curlInfo         = curl_getinfo($this->curl);
778
        $this->responseFormat   = Formats::contentTypeToSuffix($this->curlInfo['content_type']);
779
        $this->lastResponseCode = $this->curlInfo['http_code'];
780
        $this->lastCurlError    = curl_error($this->curl);
781
        if (strlen($this->lastCurlError)) {
782
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
783
                    $this->lastResponseCode, $this->lastCurlError), 'error');
784
        }
785
786
        if ($this->debug === true) {
787
            $this->saveDebugFiles();
788
        }
789
790
        return $this->lastResponseCode;
791
    }
792
793
    /**
794
     * Nastaví druh prováděné akce.
795
     *
796
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
797
     * @param string $action
798
     * @return boolean
799
     */
800
    public function setAction($action)
801
    {
802
        $result           = false;
803
        $actionsAvailable = $this->getActionsInfo();
804
        if (array_key_exists($action, $actionsAvailable)) {
805
            $this->action = $action;
806
            $result       = true;
807
        }
808
        return $result;
809
    }
810
811
    /**
812
     * Convert XML to array.
813
     *
814
     * @param string $xml
815
     *
816
     * @return array
817
     */
818
    public static function xml2array($xml)
819
    {
820
        $arr = [];
821
822
        if (is_string($xml)) {
823
            $xml = simplexml_load_string($xml);
824
        }
825
826
        foreach ($xml->children() as $r) {
827
            if (count($r->children()) == 0) {
828
                $arr[$r->getName()] = strval($r);
829
            } else {
830
                $arr[$r->getName()][] = self::xml2array($r);
831
            }
832
        }
833
834
        return $arr;
835
    }
836
837
    /**
838
     * Odpojení od FlexiBee.
839
     */
840
    public function disconnect()
841
    {
842
        if (is_resource($this->curl)) {
843
            curl_close($this->curl);
844
        }
845
        $this->curl = null;
846
    }
847
848
    /**
849
     * Disconnect CURL befere pass away
850
     */
851
    public function __destruct()
852
    {
853
        $this->disconnect();
854
    }
855
856
    /**
857
     * Načte řádek dat z FlexiBee.
858
     *
859
     * @param int $recordID id požadovaného záznamu
860
     *
861
     * @return array
862
     */
863
    public function getFlexiRow($recordID)
864
    {
865
        $record   = null;
866
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
867
        if (isset($response[$this->evidence])) {
868
            $record = $response[$this->evidence][0];
869
        }
870
871
        return $record;
872
    }
873
874
    /**
875
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
876
     *
877
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
878
     * @param array $conditions pole podmínek   - rendrují se do ()
879
     * @param array $urlParams  pole parametrů  - rendrují za ?
880
     */
881
    public function extractUrlParams(&$conditions, &$urlParams)
882
    {
883
        foreach ($this->urlParams as $urlParam) {
884
            if (isset($conditions[$urlParam])) {
885
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
886
            }
887
        }
888
    }
889
890
    /**
891
     * Načte data z FlexiBee.
892
     *
893
     * @param string $suffix     dotaz
894
     * @param string|array $conditions Volitelný filtrovací výraz
895
     */
896
    public function getFlexiData($suffix = null, $conditions = null)
897
    {
898
        $urlParams = $this->defaultUrlParams;
899
        if (!is_null($conditions)) {
900
            if (is_array($conditions)) {
901
                $this->extractUrlParams($conditions, $urlParams);
902
                $conditions = $this->flexiUrl($conditions);
903
            }
904
905
            if (strlen($conditions) && ($conditions[0] != '/')) {
906
                $conditions = '/'.rawurlencode('('.($conditions).')');
907
            }
908
        } else {
909
            $conditions = '';
910
        }
911
912
        if (preg_match('/^http/', $suffix)) {
913
            $transactions = $this->performRequest($suffix, 'GET');
914
        } else {
915
            if (strlen($suffix)) {
916
                $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
917
                    'GET');
918
            } else {
919
                $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
920
                    'GET');
921
            }
922
        }
923
        $responseEvidence = $this->getResponseEvidence();
924
        if (is_array($transactions) && array_key_exists($responseEvidence,
925
                $transactions)) {
926
            $result = $transactions[$responseEvidence];
927
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
928
                $result = null; // Response is empty Array
929
            }
930
        } else {
931
            $result = $transactions;
932
        }
933
934
        return $result;
935
    }
936
937
    /**
938
     * Načte záznam z FlexiBee.
939
     *
940
     * @param int $id ID záznamu
941
     *
942
     * @return int počet načtených položek
943
     */
944
    public function loadFromFlexiBee($id = null)
945
    {
946
        $data = [];
947
        if (is_null($id)) {
948
            $id = $this->getMyKey();
949
        }
950
951
        $flexidata    = $this->getFlexiData(null, '/'.$id);
952
        $this->apiURL = $this->curlInfo['url'];
953
        if (is_array($flexidata) && (count($flexidata) == 1)) {
954
            $data = current($flexidata);
955
        }
956
        return $this->takeData($data);
957
    }
958
959
    /**
960
     * Převede data do Json formátu pro FlexiBee.
961
     * Convert data to FlexiBee like Json format
962
     *
963
     * @param array $data
964
     *
965
     * @return string
966
     */
967
    public function jsonizeData($data)
968
    {
969
        $jsonize = [
970
            $this->nameSpace => [
971
                '@version' => $this->protoVersion,
972
                $this->evidence => $this->objectToID($data),
973
            ],
974
        ];
975
976
        if (!is_null($this->action)) {
977
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
978
            $this->action                                         = null;
979
        }
980
981
        return json_encode($jsonize);
982
    }
983
984
    /**
985
     * Test if given record ID exists in FlexiBee.
986
     *
987
     * @param string|int $identifer
988
     */
989
    public function idExists($identifer = null)
990
    {
991
        if (is_null($identifer)) {
992
            $identifer = $this->getMyKey();
993
        }
994
        $flexiData = $this->getFlexiData(
995
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
996
997
        return $flexiData;
998
    }
999
1000
    /**
1001
     * Test if given record exists in FlexiBee.
1002
     *
1003
     * @param array $data
1004
     * @return boolean Record presence status
1005
     */
1006
    public function recordExists($data = null)
1007
    {
1008
1009
        if (is_null($data)) {
1010
            $data = $this->getData();
1011
        }
1012
1013
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1014
            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...
1015
1016
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1017
            || !count($res[0])) {
1018
            $found = false;
1019
        } else {
1020
            $found = true;
1021
        }
1022
        return $found;
1023
    }
1024
1025
    /**
1026
     * Vrací z FlexiBee sloupečky podle podmínek.
1027
     *
1028
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1029
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1030
     *                                     sloupečku
1031
     * @return array
1032
     */
1033
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1034
    {
1035
        if (is_int($conditions)) {
1036
            $conditions = [$this->getmyKeyColumn() => $conditions];
1037
        }
1038
1039
        $flexiData = $this->getFlexiData('', $conditions);
1040
1041
        if (!is_null($indexBy)) {
1042
            $flexiData = $this->reindexArrayBy($flexiData);
1043
        }
1044
1045
        return $flexiData;
1046
    }
1047
1048
    /**
1049
     * Vrací z FlexiBee sloupečky podle podmínek.
1050
     *
1051
     * @param string[] $columnsList seznam položek
1052
     * @param array    $conditions  pole podmínek nebo ID záznamu
1053
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1054
     *
1055
     * @return array
1056
     */
1057
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
1058
                                           $indexBy = null)
1059
    {
1060
        $detail = 'full';
1061
        switch (gettype($columnsList)) {
1062
            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...
1063
                $conditions = [$this->getmyKeyColumn() => $conditions];
1064
            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...
1065
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1066
                        $columnsList)) {
1067
                    $columnsList[] = $indexBy;
1068
                }
1069
                $columns = implode(',', array_unique($columnsList));
1070
                $detail  = 'custom:'.$columns;
1071
            default:
1072
                switch ($columnsList) {
1073
                    case 'id':
1074
                        $detail = 'id';
1075
                        break;
1076
                    case 'summary':
1077
                        $detail = 'summary';
1078
                        break;
1079
                    default:
1080
                        break;
1081
                }
1082
                break;
1083
        }
1084
1085
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
1086
1087
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1088
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1089
        }
1090
1091
        return $flexiData;
1092
    }
1093
1094
    /**
1095
     * Vrací kód záznamu.
1096
     *
1097
     * @param mixed $data
1098
     *
1099
     * @return string
1100
     */
1101
    public function getKod($data = null, $unique = true)
1102
    {
1103
        $kod = null;
1104
1105
        if (is_null($data)) {
1106
            $data = $this->getData();
1107
        }
1108
1109
        if (is_string($data)) {
1110
            $data = [$this->nameColumn => $data];
1111
        }
1112
1113
        if (isset($data['kod'])) {
1114
            $kod = $data['kod'];
1115
        } else {
1116
            if (isset($data[$this->nameColumn])) {
1117
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1118
                    \Ease\Sand::rip($data[$this->nameColumn]));
1119
            } else {
1120
                if (isset($data[$this->myKeyColumn])) {
1121
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1122
                }
1123
            }
1124
        }
1125
1126
        if (!strlen($kod)) {
1127
            $kod = 'NOTSET';
1128
        }
1129
1130
        if (strlen($kod) > 18) {
1131
            $kodfinal = strtoupper(substr($kod, 0, 18));
1132
        } else {
1133
            $kodfinal = strtoupper($kod);
1134
        }
1135
1136
        if ($unique) {
1137
            $counter = 0;
1138
            if (count($this->codes)) {
1139
                foreach ($this->codes as $codesearch => $keystring) {
1140
                    if (strstr($codesearch, $kodfinal)) {
1141
                        ++$counter;
1142
                    }
1143
                }
1144
            }
1145
            if ($counter) {
1146
                $kodfinal = $kodfinal.$counter;
1147
            }
1148
1149
            $this->codes[$kodfinal] = $kod;
1150
        }
1151
1152
        return $kodfinal;
1153
    }
1154
1155
    /**
1156
     * Write Operation Result.
1157
     *
1158
     * @param array  $resultData
1159
     * @param string $url        URL
1160
     * @return boolean Log save success
1161
     */
1162
    public function logResult($resultData = null, $url = null)
1163
    {
1164
        $logResult = false;
1165
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1166
            if (isset($resultData['message'])) {
1167
                $this->addStatusMessage($resultData['message'], 'warning');
1168
            }
1169
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1170
                'warning');
1171
            unset($url);
1172
        }
1173
        if (is_null($resultData)) {
1174
            $resultData = $this->lastResult;
1175
        }
1176
        if (isset($url)) {
1177
            $this->logger->addStatusMessage(urldecode($url));
1178
        }
1179
1180
        if (isset($resultData['results'])) {
1181
            if ($resultData['success'] == 'false') {
1182
                $status = 'error';
1183
            } else {
1184
                $status = 'success';
1185
            }
1186
            foreach ($resultData['results'] as $result) {
1187
                if (isset($result['request-id'])) {
1188
                    $rid = $result['request-id'];
1189
                } else {
1190
                    $rid = '';
1191
                }
1192
                if (isset($result['errors'])) {
1193
                    foreach ($result['errors'] as $error) {
1194
                        $message = $error['message'];
1195
                        if (isset($error['for'])) {
1196
                            $message .= ' for: '.$error['for'];
1197
                        }
1198
                        if (isset($error['value'])) {
1199
                            $message .= ' value:'.$error['value'];
1200
                        }
1201
                        if (isset($error['code'])) {
1202
                            $message .= ' code:'.$error['code'];
1203
                        }
1204
                        $this->addStatusMessage($rid.': '.$message, $status);
1205
                    }
1206
                }
1207
            }
1208
        }
1209
        return $logResult;
1210
    }
1211
1212
    /**
1213
     * Save RAW Curl Request & Response to files in Temp directory
1214
     */
1215
    public function saveDebugFiles()
1216
    {
1217
        $tmpdir = sys_get_temp_dir();
1218
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1219
            $this->postFields);
1220
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1221
            $this->lastCurlResponse);
1222
    }
1223
1224
    /**
1225
     * Připraví data pro odeslání do FlexiBee
1226
     *
1227
     * @param string $data
1228
     */
1229
    public function setPostFields($data)
1230
    {
1231
        $this->postFields = $data;
1232
    }
1233
1234
    /**
1235
     * Generuje fragment url pro filtrování.
1236
     *
1237
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1238
     *
1239
     * @param array  $data
1240
     * @param string $joiner default and/or
1241
     * @param string $defop  default operator
1242
     *
1243
     * @return string
1244
     */
1245
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1246
    {
1247
        $parts = [];
1248
        foreach ($data as $column => $value) {
1249
            if (is_integer($data[$column]) || is_float($data[$column])) {
1250
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1251
            } elseif (is_bool($data[$column])) {
1252
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1253
            } elseif (is_null($data[$column])) {
1254
                $parts[$column] = $column." is null";
1255
            } else {
1256
                switch ($value) {
1257
                    case '!null':
1258
                        $parts[$column] = $column." is not null";
1259
                        break;
1260
                    case 'is empty':
1261
                    case 'is not empty':
1262
                        $parts[$column] = $column.' '.$value;
1263
                        break;
1264
                    default:
1265
                        $parts[$column] = $column." $defop '".$data[$column]."'";
1266
                        break;
1267
                }
1268
            }
1269
        }
1270
        return implode(' '.$joiner.' ', $parts);
1271
    }
1272
1273
    /**
1274
     * Obtain record/object identificator code: or id:
1275
     * Vrací identifikátor objektu code: nebo id:
1276
     *
1277
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1278
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1279
     */
1280
    public function getRecordID()
1281
    {
1282
        $myCode = $this->getDataValue('kod');
1283
        if ($myCode) {
1284
            $id = 'code:'.$myCode;
1285
        } else {
1286
            $id = $this->getDataValue('id');
1287
            if (($this->debug === true) && is_null($id)) {
1288
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1289
                    'warning');
1290
            }
1291
        }
1292
        return is_numeric($id) ? intval($id) : strval($id);
1293
    }
1294
1295
    /**
1296
     * Obtain record/object identificator code: or id:
1297
     * Vrací identifikátor objektu code: nebo id:
1298
     *
1299
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1300
     * @return string indentifikátor záznamu reprezentovaného objektem
1301
     */
1302
    public function __toString()
1303
    {
1304
        return strval($this->getRecordID());
1305
    }
1306
1307
    /**
1308
     * Gives you FlexiPeeHP class name for Given Evidence
1309
     *
1310
     * @param string $evidence
1311
     * @return string Class name
1312
     */
1313
    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...
1314
    {
1315
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1316
    }
1317
1318
    /**
1319
     * Vrací hodnotu daného externího ID
1320
     *
1321
     * @param string $want Which ? If empty,you obtain the first one.
1322
     * @return string
1323
     */
1324
    public function getExternalID($want = null)
1325
    {
1326
        $extid = null;
1327
        $ids   = $this->getDataValue('external-ids');
1328
        if (is_null($want)) {
1329
            if (count($ids)) {
1330
                $extid = current($ids);
1331
            }
1332
        } else {
1333
            if (!is_null($ids) && is_array($ids)) {
1334
                foreach ($ids as $id) {
1335
                    if (strstr($id, 'ext:'.$want)) {
1336
                        $extid = str_replace('ext:'.$want.':', '', $id);
1337
                    }
1338
                }
1339
            }
1340
        }
1341
        return $extid;
1342
    }
1343
1344
    /**
1345
     * Obtain actual GlobalVersion
1346
     * Vrací aktuální globální verzi změn
1347
     *
1348
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1349
     * @return type
1350
     */
1351
    public function getGlobalVersion()
1352
    {
1353
        $globalVersion = null;
1354
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1355
            $this->getFlexiData(null,
1356
                ['add-global-version' => 'true', 'limit' => 1]);
1357
        }
1358
1359
        if (isset($this->lastResult['@globalVersion'])) {
1360
            $globalVersion = intval($this->lastResult['@globalVersion']);
1361
        }
1362
1363
        return $globalVersion;
1364
    }
1365
1366
    /**
1367
     * Obtain content type of last response
1368
     *
1369
     * @return string
1370
     */
1371
    public function getResponseFormat()
1372
    {
1373
        if (isset($this->curlInfo['content_type'])) {
1374
            $responseFormat = $this->curlInfo['content_type'];
1375
        } else {
1376
            $responseFormat = null;
1377
        }
1378
        return $responseFormat;
1379
    }
1380
1381
    /**
1382
     * Return the same response format for one and multiplete results
1383
     *
1384
     * @param array $responseBody
1385
     * @return array
1386
     */
1387
    public function unifyResponseFormat($responseBody)
1388
    {
1389
        if (!is_array($responseBody) || array_key_exists('message',
1390
                $responseBody)) { //Unifi response format
1391
            $response = $responseBody;
1392
        } else {
1393
            $evidence = $this->getResponseEvidence();
1394
            if (array_key_exists($evidence, $responseBody)) {
1395
                $response        = [];
1396
                $evidenceContent = $responseBody[$evidence];
1397
                if (array_key_exists(0, $evidenceContent)) {
1398
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1399
                } else {
1400
                    $response[$evidence][0] = $evidenceContent; //One result
1401
                }
1402
            } else {
1403
                if (isset($responseBody['priloha'])) {
1404
                    $response = $responseBody['priloha'];
1405
                } else {
1406
                    $response = $responseBody;
1407
                }
1408
            }
1409
        }
1410
        return $response;
1411
    }
1412
1413
    /**
1414
     * Obtain structure for current (or given) evidence
1415
     *
1416
     * @param string $evidence
1417
     * @return array Evidence structure
1418
     */
1419 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...
1420
    {
1421
        $columnsInfo = null;
1422
        if (is_null($evidence)) {
1423
            $evidence = $this->getEvidence();
1424
        }
1425
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1426
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1427
            $columnsInfo = Properties::$$propsName;
1428
        }
1429
        return $columnsInfo;
1430
    }
1431
1432
    /**
1433
     * Obtain actions for current (or given) evidence
1434
     *
1435
     * @param string $evidence
1436
     * @return array Evidence structure
1437
     */
1438 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...
1439
    {
1440
        $actionsInfo = null;
1441
        if (is_null($evidence)) {
1442
            $evidence = $this->getEvidence();
1443
        }
1444
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1445
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1446
            $actionsInfo = Actions::$$propsName;
1447
        }
1448
        return $actionsInfo;
1449
    }
1450
1451
    /**
1452
     * Obtain relations for current (or given) evidence
1453
     *
1454
     * @param string $evidence
1455
     * @return array Evidence structure
1456
     */
1457
    public function getRelationsInfo($evidence = null)
1458
    {
1459
        $relationsInfo = null;
1460
        if (is_null($evidence)) {
1461
            $evidence = $this->getEvidence();
1462
        }
1463
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1464
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1465
            $relationsInfo = Relations::$$propsName;
1466
        }
1467
        return $relationsInfo;
1468
    }
1469
1470
    /**
1471
     * Obtain info for current (or given) evidence
1472
     *
1473
     * @param string $evidence
1474
     * @return array Evidence info
1475
     */
1476 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...
1477
    {
1478
        $evidencesInfo = null;
1479
        if (is_null($evidence)) {
1480
            $evidence = $this->getEvidence();
1481
        }
1482
        if (isset(EvidenceList::$evidences[$evidence])) {
1483
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1484
        }
1485
        return $evidencesInfo;
1486
    }
1487
1488
    /**
1489
     * Obtain name for current (or given) evidence path
1490
     *
1491
     * @param string $evidence Evidence Path
1492
     * @return array Evidence info
1493
     */
1494 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...
1495
    {
1496
        $evidenceName = null;
1497
        if (is_null($evidence)) {
1498
            $evidence = $this->getEvidence();
1499
        }
1500
        if (isset(EvidenceList::$name[$evidence])) {
1501
            $evidenceName = EvidenceList::$name[$evidence];
1502
        }
1503
        return $evidenceName;
1504
    }
1505
1506
    /**
1507
     * Perform given action (if availble) on current evidence/record
1508
     * @url https://demo.flexibee.eu/devdoc/actions
1509
     *
1510
     * @param string $action one of evidence actions
1511
     * @param string $method ext|int External method call operation in URL.
1512
     *                               Internal add the @action element to request body
1513
     */
1514
    public function performAction($action, $method = 'ext')
1515
    {
1516
        $actionsAvailble = $this->getActionsInfo();
1517
1518
        if (is_array($actionsAvailble) && array_key_exists($action,
1519
                $actionsAvailble)) {
1520
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1521
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1522
                case 'ONLY_WITH_INSTANCE': //Add instance
1523
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1524
                    break;
1525
1526
                default:
1527
                    $urlSuffix = '/'.$action;
1528
                    break;
1529
            }
1530
1531
            switch ($method) {
1532
                case 'int':
1533
                    $this->setAction($action);
1534
                    $this->setPostFields($this->jsonizeData($this->getData()));
1535
                    $result = $this->performRequest(null, 'POST');
1536
                    break;
1537
1538
                default:
1539
                    $result = $this->performRequest($urlSuffix, 'GET');
1540
                    break;
1541
            }
1542
        } else {
1543
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1544
                $action, $this->getEvidence()));
1545
        }
1546
1547
        return $result;
1548
    }
1549
1550
    /**
1551
     * Save current object to file
1552
     *
1553
     * @param string $destfile path to file
1554
     */
1555
    public function saveResponseToFile($destfile)
1556
    {
1557
        if (strlen($this->lastCurlResponse)) {
1558
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1559
        }
1560
        file_put_contents($destfile, $this->lastCurlResponse);
1561
    }
1562
1563
    /**
1564
     * Obtain established relations listing
1565
     *
1566
     * @return array Null or Relations
1567
     */
1568
    public function getVazby()
1569
    {
1570
        $vazby = $this->getDataValue('vazby');
1571
        if (is_null($vazby)) {
1572
            $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...
1573
                ['relations' => 'vazby', 'id' => $this->getRecordID()]);
1574
            $vazby = $vazby[0]['vazby'];
1575
        }
1576
        return $vazby;
1577
    }
1578
1579
    /**
1580
     * Gives You URL for Current Record in FlexiBee web interface
1581
     *
1582
     * @return string url
1583
     */
1584
    public function getFlexiBeeURL()
1585
    {
1586
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1587
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1588
                : '';
1589
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1590
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1591
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1592
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1593
        $pass       = ($user || $pass) ? "$pass@" : '';
1594
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1595
        return $scheme.$user.$pass.$host.$port.$path;
1596
    }
1597
1598
    /**
1599
     * Set Record Key
1600
     *
1601
     * @param int|string $myKeyValue
1602
     * @return boolean
1603
     */
1604
    public function setMyKey($myKeyValue)
1605
    {
1606
        $res = parent::setMyKey($myKeyValue);
1607
        $this->updateApiURL();
1608
        return $res;
1609
    }
1610
1611
    /**
1612
     * Set or get ignore not found pages flag
1613
     *
1614
     * @param boolean $ignore set flag to
1615
     *
1616
     * @return boolean get flag state
1617
     */
1618
    public function ignore404($ignore = null)
1619
    {
1620
        if (!is_null($ignore)) {
1621
            $this->ignoreNotFound = $ignore;
1622
        }
1623
        return $this->ignoreNotFound;
1624
    }
1625
1626
    /**
1627
     * Send Document by mail
1628
     *
1629
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1630
     *
1631
     * @param string $to
1632
     * @param string $subject
1633
     * @param string $body Email Text
1634
     *
1635
     * @return int http response code
1636
     */
1637
    public function sendByMail($to, $subject, $body, $cc = null)
1638
    {
1639
        $this->setPostFields($body);
1640
        $result = $this->doCurlRequest($this->getEvidenceURL().'/'.
1641
            urlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1642
            , 'PUT', 'xml');
1643
        return $result == 200;
1644
    }
1645
1646
    /**
1647
     * Send all unsent Invoices by mail
1648
     *
1649
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1650
     * @return int http response code
1651
     */
1652
    public function sendUnsent()
1653
    {
1654
        return $this->doCurlRequest($this->getEvidenceURL().'/automaticky-odeslat-neodeslane',
1655
                'PUT', 'xml');
1656
    }
1657
1658
    /**
1659
     * FlexiBee date to PHP DateTime
1660
     *
1661
     * @param string $flexidate
1662
     * @return \DateTime
1663
     */
1664
    public static function flexiDateToDateTime($flexidate)
1665
    {
1666
        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 1666 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...
1667
    }
1668
1669
    /**
1670
     * Uloží dokument v daném formátu do složky v systému souborů
1671
     * Save document in given format to directory in filesystem
1672
     *
1673
     * @param string $format  pdf/csv/xml/json/ ...
1674
     * @param string $destDir where to put file (prefix)
1675
     * 
1676
     * @return string|null filename downloaded or none
1677
     */
1678
    public function downloadInFormat($format, $destDir = './')
1679
    {
1680
        $fileOnDisk = null;
1681
        if ($this->setFormat($format)) {
1682
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
1683
            if (($this->doCurlRequest($this->apiURL, 'GET') == 200) && (file_put_contents($downloadTo,
1684
                    $this->lastCurlResponse) !== false)) {
1685
                $fileOnDisk = $downloadTo;
1686
            }
1687
        }
1688
        return $fileOnDisk;
1689
    }
1690
1691
    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...
1692
    {
1693
        //Send Raw Request: Method/URL/Headers/Body
1694
        //With tail of FlexiBee log 
1695
        //To FlexiBee developers team
1696
        //By mail
1697
    }
1698
1699
}
1700