Test Failed
Push — master ( db4226...0ac485 )
by Vítězslav
02:57
created

FlexiBeeRO::processInit()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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