Test Failed
Push — master ( 601165...03506f )
by Vítězslav
02:37
created

FlexiBeeRO::flexiUrl()   C

Complexity

Conditions 11
Paths 10

Size

Total Lines 32
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 25
nc 10
nop 3
dl 0
loc 32
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://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
235
     * @var string filter query
236
     */
237
    public $filter;
238
239
    /**
240
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
241
     * @var string
242
     */
243
    protected $action;
244
245
    /**
246
     * Pole akcí které podporuje ta která evidence
247
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
248
     * @var array
249
     */
250
    public $actionsAvailable = null;
251
252
    /**
253
     * Parmetry pro URL
254
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
255
     * @var array
256
     */
257
    public $urlParams = [
258
        'idUcetniObdobi',
259
        'dry-run',
260
        'fail-on-warning',
261
        'report-name',
262
        'report-lang',
263
        'report-sign',
264
        'detail', //See: https://www.flexibee.eu/api/dokumentace/ref/detail-levels
265
        'mode',
266
        'limit',
267
        'start',
268
        'order',
269
        'sort',
270
        'add-row-count',
271
        'relations',
272
        'includes',
273
        'use-ext-id',
274
        'use-internal-id',
275
        'stitky-as-ids',
276
        'only-ext-ids',
277
        'no-ext-ids',
278
        'no-ids',
279
        'code-as-id',
280
        'no-http-errors',
281
        'export-settings',
282
        'as-gui',
283
        'code-in-response',
284
        'add-global-version',
285
        'encoding',
286
        'delimeter',
287
        'format',
288
        'auth',
289
        'skupina-stitku',
290
        'dir',
291
        'relations',
292
        'relations',
293
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
294
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
295
        'inDesktopApp' // Note: Undocumented function (html only)
296
    ];
297
298
    /**
299
     * Save 404 results to log ?
300
     * @var boolean
301
     */
302
    protected $ignoreNotFound = false;
303
304
    /**
305
     * Array of errors caused by last request
306
     * @var array
307
     */
308
    private $errors = [];
309
310
    /**
311
     * Class for read only interaction with FlexiBee.
312
     *
313
     * @param mixed $init default record id or initial data
314
     * @param array $options Connection settings override
315
     */
316
    public function __construct($init = null, $options = [])
317
    {
318
        $this->init = $init;
319
320
        parent::__construct();
321
        $this->setUp($options);
322
        $this->curlInit();
323
        if (!empty($init)) {
324
            $this->processInit($init);
325
        }
326
    }
327
328
    /**
329
     * SetUp Object to be ready for connect
330
     *
331
     * @param array $options Object Options (company,url,user,password,evidence,
332
     *                                       prefix,defaultUrlParams,debug)
333
     */
334
    public function setUp($options = [])
335
    {
336
        if (isset($options['company'])) {
337
            $this->company = $options['company'];
338
        } else {
339
            if (is_null($this->company) && defined('FLEXIBEE_COMPANY')) {
340
                $this->company = constant('FLEXIBEE_COMPANY');
341
            }
342
        }
343
        if (isset($options['url'])) {
344
            $this->url = $options['url'];
345
        } else {
346
            if (is_null($this->url) && defined('FLEXIBEE_URL')) {
347
                $this->url = constant('FLEXIBEE_URL');
348
            }
349
        }
350
        if (isset($options['user'])) {
351
            $this->user = $options['user'];
352
        } else {
353
            if (is_null($this->user) && defined('FLEXIBEE_LOGIN')) {
354
                $this->user = constant('FLEXIBEE_LOGIN');
355
            }
356
        }
357
        if (isset($options['password'])) {
358
            $this->password = $options['password'];
359
        } else {
360
            if (is_null($this->password) && defined('FLEXIBEE_PASSWORD')) {
361
                $this->password = constant('FLEXIBEE_PASSWORD');
362
            }
363
        }
364
        if (isset($options['evidence'])) {
365
            $this->setEvidence($options['evidence']);
366
        }
367
        if (isset($options['defaultUrlParams'])) {
368
            $this->defaultUrlParams = $options['defaultUrlParams'];
369
        }
370
        if (isset($options['prefix'])) {
371
            $this->setPrefix($options['prefix']);
372
        }
373
        if (isset($options['debug'])) {
374
            $this->debug = $options['debug'];
375
        }
376
    }
377
378
    /**
379
     * Inicializace CURL
380
     */
381
    public function curlInit()
382
    {
383
        $this->curl = \curl_init(); // create curl resource
384
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
385
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
386
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
387
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
388
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
389
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
390
        curl_setopt($this->curl, CURLOPT_USERPWD,
391
            $this->user.':'.$this->password); // set username and password
392
    }
393
394
    /**
395
     * Zinicializuje objekt dle daných dat. Možné hodnoty:
396
     *
397
     *  * 234                              - interní číslo záznamu k načtení
398
     *  * code:LOPATA                      - kód záznamu
399
     *  * BAGR                             - kód záznamu ka načtení
400
     *  * ['id'=>24,'nazev'=>'hoblík']     - pole hodnot k předvyplnění
401
     *  * 743.json?relations=adresa,vazby  - část url s parametry k načtení
402
     *
403
     * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění
404
     */
405
    public function processInit($init)
406
    {
407
        if (is_integer($init)) {
408
            $this->loadFromFlexiBee($init);
409
        } elseif (is_array($init)) {
410
            $this->takeData($init);
411
        } elseif (preg_match('/\.(json|xml|csv)/', $init)) {
412
            $this->takeData($this->getFlexiData((($init[0] != '/') ? $this->getEvidenceURL().'/'
413
                            : '').$init));
414
        } else {
415
            $this->loadFromFlexiBee('code:'.str_replace('code:', '', $init));
416
        }
417
    }
418
419
    /**
420
     * Set URL prefix
421
     *
422
     * @param string $prefix
423
     */
424
    public function setPrefix($prefix)
425
    {
426
        switch ($prefix) {
427
            case 'a': //Access
428
            case 'c': //Company
429
            case 'u': //User
430
            case 'g': //License Groups
431
            case 'admin':
432
            case 'status':
433
            case 'login-logout':
434
                $this->prefix = '/'.$prefix.'/';
435
                break;
436
            case null:
437
            case '':
438
            case '/':
439
                $this->prefix = '';
440
                break;
441
            default:
442
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
443
        }
444
    }
445
446
    /**
447
     * Set communication format.
448
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
449
     *
450
     * @param string $format
451
     * @return boolen format is availble
452
     */
453
    public function setFormat($format)
454
    {
455
        $result = true;
456
        if (($this->debug === true) && isset(Formats::$$this->evidence)) {
457
            $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...
458
            if (array_key_exists($format, array_flip(Formats::$$this->evidence))
459
                === false) {
460
                $result = false;
461
            }
462
        }
463
        if ($result === true) {
464
            $this->format = $format;
465
            $this->updateApiURL();
466
        }
467
        return $result;
468
    }
469
470
    /**
471
     * Nastaví Evidenci pro Komunikaci.
472
     * Set evidence for communication
473
     *
474
     * @param string $evidence evidence pathName to use
475
     * @return boolean evidence switching status
476
     */
477
    public function setEvidence($evidence)
478
    {
479
        switch ($this->prefix) {
480
            case '/c/':
481
                if (array_key_exists($evidence, EvidenceList::$name)) {
482
                    $this->evidence = $evidence;
483
                    $result         = true;
484
                } else {
485
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
486
                        $evidence));
487
                }
488
                break;
489
            default:
490
                $this->evidence = $evidence;
491
                $result         = true;
492
                break;
493
        }
494
        $this->updateApiURL();
495
        return $result;
496
    }
497
498
    /**
499
     * Vrací právě používanou evidenci pro komunikaci
500
     * Obtain current used evidence
501
     *
502
     * @return string
503
     */
504
    public function getEvidence()
505
    {
506
        return $this->evidence;
507
    }
508
509
    /**
510
     * Set used company.
511
     * Nastaví Firmu.
512
     *
513
     * @param string $company
514
     */
515
    public function setCompany($company)
516
    {
517
        $this->company = $company;
518
    }
519
520
    /**
521
     * Obtain company now used
522
     * Vrací právě používanou firmu
523
     *
524
     * @return string
525
     */
526
    public function getCompany()
527
    {
528
        return $this->company;
529
    }
530
531
    /**
532
     * Vrací název evidence použité v odpovědích z FlexiBee
533
     *
534
     * @return string
535
     */
536
    public function getResponseEvidence()
537
    {
538
        switch ($this->evidence) {
539
            case 'c':
540
                $evidence = 'company';
541
                break;
542
            case 'evidence-list':
543
                $evidence = 'evidence';
544
                break;
545
            default:
546
                $evidence = $this->getEvidence();
547
                break;
548
        }
549
        return $evidence;
550
    }
551
552
    /**
553
     * Převede rekurzivně Objekt na pole.
554
     *
555
     * @param object|array $object
556
     *
557
     * @return array
558
     */
559
    public static function object2array($object)
560
    {
561
        $result = null;
562
        if (is_object($object)) {
563
            $objectData = get_object_vars($object);
564
            if (is_array($objectData) && count($objectData)) {
565
                $result = array_map('self::object2array', $objectData);
566
            }
567 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...
568
            if (is_array($object)) {
569
                foreach ($object as $item => $value) {
570
                    $result[$item] = self::object2array($value);
571
                }
572
            } else {
573
                $result = $object;
574
            }
575
        }
576
577
        return $result;
578
    }
579
580
    /**
581
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
582
     *
583
     * @param object|array $object
584
     *
585
     * @return array
586
     */
587
    public static function objectToID($object)
588
    {
589
        $result = null;
590
        if (is_object($object)) {
591
            $result = $object->__toString();
592 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...
593
            if (is_array($object)) {
594
                foreach ($object as $item => $value) {
595
                    $result[$item] = self::objectToID($value);
596
                }
597
            } else { //String
598
                $result = $object;
599
            }
600
        }
601
602
        return $result;
603
    }
604
605
    /**
606
     * Return basic URL for used Evidence
607
     *
608
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
609
     * @param string $urlSuffix
610
     */
611
    public function getEvidenceURL($urlSuffix = null)
612
    {
613
        if (is_null($urlSuffix)) {
614
            $urlSuffix = $this->getEvidence();
615
        } elseif ($urlSuffix[0] == ';') {
616
            $urlSuffix = $this->getEvidence().$urlSuffix;
617
        }
618
        return $this->url.$this->prefix.$this->company.'/'.$urlSuffix;
619
    }
620
621
    /**
622
     * Update $this->apiURL
623
     */
624
    public function updateApiURL()
625
    {
626
        $this->apiURL = $this->getEvidenceURL();
627
        $id           = $this->__toString();
628
        if (!empty($id)) {
629
            $this->apiURL .= '/'.urlencode($id);
630
        }
631
        $this->apiURL .= '.'.$this->format;
632
    }
633
634
    /**
635
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
636
     *
637
     * @param string $urlSuffix část URL za identifikátorem firmy.
638
     * @param string $method    HTTP/REST metoda
639
     * @param string $format    Requested format
640
     * @return array|boolean Výsledek operace
641
     */
642
    public function performRequest($urlSuffix = null, $method = 'GET',
643
                                   $format = null)
644
    {
645
        $this->rowCount = null;
646
647
        if (preg_match('/^http/', $urlSuffix)) {
648
            $url = $urlSuffix;
649
        } else {
650
            $url = $this->getEvidenceURL($urlSuffix);
651
        }
652
653
        $responseCode = $this->doCurlRequest($url, $method, $format);
654
655
        return strlen($this->lastCurlResponse) ? $this->parseResponse($this->rawResponseToArray($this->lastCurlResponse,
656
                    $this->responseFormat), $responseCode) : null;
657
    }
658
659
    /**
660
     * Parse Raw FlexiBee response in several formats
661
     *
662
     * @param string $responseRaw raw response body
663
     * @param string $format      Raw Response format json|xml|etc
664
     *
665
     * @return array
666
     */
667
    public function rawResponseToArray($responseRaw, $format)
668
    {
669
        switch ($format) {
670
            case 'json':
671
                $responseDecoded = json_decode($responseRaw, true, 10);
672
                $decodeError     = json_last_error_msg();
673
                if ($decodeError == 'No error') {
674
                    if (array_key_exists($this->nameSpace, $responseDecoded)) {
675
                        $responseDecoded = $responseDecoded[$this->nameSpace];
676
                    }
677
                } else {
678
                    $this->addStatusMessage('JSON Decoder: '.$decodeError,
679
                        'error');
680
                    $this->addStatusMessage($responseRaw, 'debug');
681
                }
682
                break;
683
            case 'xml':
684
                $responseDecoded = self::xml2array($this->lastCurlResponse);
685
                break;
686
            case 'txt':
687
            default:
688
                $responseDecoded = $this->lastCurlResponse;
689
                break;
690
        }
691
        return $responseDecoded;
692
    }
693
694
    /**
695
     * Parse Response array
696
     * 
697
     * @param array $responseDecoded
698
     * @param int $responseCode Request Response Code
699
     *
700
     * @return array main data part of response
701
     */
702
    public function parseResponse($responseDecoded, $responseCode)
703
    {
704
        $response = null;
705
        switch ($responseCode) {
706
            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...
707
                if (isset($responseDecoded[$this->resultField][0]['id'])) {
708
                    $this->lastInsertedID = $responseDecoded[$this->resultField][0]['id'];
709
                    $this->setMyKey($this->lastInsertedID);
710
                    $this->apiURL         = $this->getEvidenceURL().'/'.$this->lastInsertedID;
711
                } else {
712
                    $this->lastInsertedID = null;
713
                    if (isset($responseDecoded['@rowCount'])) {
714
                        $this->rowCount = (int) $responseDecoded['@rowCount'];
715
                    }
716
                }
717
            case 200:
718
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
719
                break;
720
721
            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...
722
                $this->error500Reporter($responseDecoded);
723
            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...
724
                if ($this->ignoreNotFound === true) {
725
                    break;
726
                }
727
            case 400:
728
            default: //Something goes wrong
729
                $this->addStatusMessage($this->curlInfo['url'], 'warning');
730
                if (is_array($responseDecoded)) {
731
                    $this->parseError($responseDecoded);
732
                }
733
                $this->logResult($responseDecoded, $this->curlInfo['url']);
734
                break;
735
        }
736
        return $response;
737
    }
738
739
    /**
740
     * Parse error message response
741
     *
742
     * @param array $responseDecoded
743
     * @return int number of errors processed
744
     */
745
    public function parseError(array $responseDecoded)
746
    {
747
        if (array_key_exists('results', $responseDecoded)) {
748
            $this->errors = $responseDecoded['results'][0]['errors'];
749
        } else {
750
            $this->errors = [['message' => $responseDecoded['message']]];
751
        }
752
        return count($this->errors);
753
    }
754
755
    /**
756
     * Vykonej HTTP požadavek
757
     *
758
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
759
     * @param string $url    URL požadavku
760
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
761
     * @param string $format požadovaný formát komunikace
762
     * @return int HTTP Response CODE
763
     */
764
    public function doCurlRequest($url, $method, $format = null)
765
    {
766
        if (is_null($format)) {
767
            $format = $this->format;
768
        }
769
        curl_setopt($this->curl, CURLOPT_URL, $url);
770
// Nastavení samotné operace
771
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
772
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
773
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
774
775
        $httpHeaders = $this->defaultHttpHeaders;
776
777
        $formats = Formats::bySuffix();
778
779
        if (!isset($httpHeaders['Accept'])) {
780
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
781
        }
782
        if (!isset($httpHeaders['Content-Type'])) {
783
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
784
        }
785
        $httpHeadersFinal = [];
786
        foreach ($httpHeaders as $key => $value) {
787
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
788
                $value .= ' v'.self::$libVersion;
789
            }
790
            $httpHeadersFinal[] = $key.': '.$value;
791
        }
792
793
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
794
795
// Proveď samotnou operaci
796
        $this->lastCurlResponse = curl_exec($this->curl);
797
        $this->curlInfo         = curl_getinfo($this->curl);
798
        $this->responseFormat   = Formats::contentTypeToSuffix($this->curlInfo['content_type']);
799
        $this->lastResponseCode = $this->curlInfo['http_code'];
800
        $this->lastCurlError    = curl_error($this->curl);
801
        if (strlen($this->lastCurlError)) {
802
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
803
                    $this->lastResponseCode, $this->lastCurlError), 'error');
804
        }
805
806
        if ($this->debug === true) {
807
            $this->saveDebugFiles();
808
        }
809
810
        return $this->lastResponseCode;
811
    }
812
813
    /**
814
     * Nastaví druh prováděné akce.
815
     *
816
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
817
     * @param string $action
818
     * @return boolean
819
     */
820
    public function setAction($action)
821
    {
822
        $result           = false;
823
        $actionsAvailable = $this->getActionsInfo();
824
        if (array_key_exists($action, $actionsAvailable)) {
825
            $this->action = $action;
826
            $result       = true;
827
        }
828
        return $result;
829
    }
830
831
    /**
832
     * Convert XML to array.
833
     *
834
     * @param string $xml
835
     *
836
     * @return array
837
     */
838
    public static function xml2array($xml)
839
    {
840
        $arr = [];
841
842
        if (is_string($xml)) {
843
            $xml = simplexml_load_string($xml);
844
        }
845
846
        foreach ($xml->children() as $r) {
847
            if (count($r->children()) == 0) {
848
                $arr[$r->getName()] = strval($r);
849
            } else {
850
                $arr[$r->getName()][] = self::xml2array($r);
851
            }
852
        }
853
854
        return $arr;
855
    }
856
857
    /**
858
     * Odpojení od FlexiBee.
859
     */
860
    public function disconnect()
861
    {
862
        if (is_resource($this->curl)) {
863
            curl_close($this->curl);
864
        }
865
        $this->curl = null;
866
    }
867
868
    /**
869
     * Disconnect CURL befere pass away
870
     */
871
    public function __destruct()
872
    {
873
        $this->disconnect();
874
    }
875
876
    /**
877
     * Načte řádek dat z FlexiBee.
878
     *
879
     * @param int $recordID id požadovaného záznamu
880
     *
881
     * @return array
882
     */
883
    public function getFlexiRow($recordID)
884
    {
885
        $record   = null;
886
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
887
        if (isset($response[$this->evidence])) {
888
            $record = $response[$this->evidence][0];
889
        }
890
891
        return $record;
892
    }
893
894
    /**
895
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
896
     *
897
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
898
     * @param array $conditions pole podmínek   - rendrují se do ()
899
     * @param array $urlParams  pole parametrů  - rendrují za ?
900
     */
901
    public function extractUrlParams(&$conditions, &$urlParams)
902
    {
903
        foreach ($this->urlParams as $urlParam) {
904
            if (isset($conditions[$urlParam])) {
905
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
906
            }
907
        }
908
    }
909
910
    /**
911
     * Načte data z FlexiBee.
912
     *
913
     * @param string $suffix     dotaz
914
     * @param string|array $conditions Volitelný filtrovací výraz
915
     */
916
    public function getFlexiData($suffix = null, $conditions = null)
917
    {
918
        $urlParams = $this->defaultUrlParams;
919
        if (!is_null($conditions)) {
920
            if (is_array($conditions)) {
921
                $this->extractUrlParams($conditions, $urlParams);
922
                $conditions = $this->flexiUrl($conditions);
923
            }
924
925
            if (strlen($conditions) && ($conditions[0] != '/')) {
926
                $conditions = '/'.rawurlencode('('.($conditions).')');
927
            }
928
        } else {
929
            $conditions = '';
930
        }
931
932
        if (preg_match('/^http/', $suffix)) {
933
            $transactions = $this->performRequest($suffix, 'GET');
934
        } else {
935
            if (strlen($suffix)) {
936
                $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.$suffix.'&'.http_build_query($urlParams),
937
                    'GET');
938
            } else {
939
                $transactions = $this->performRequest($this->evidence.$conditions.'.'.$this->format.'?'.http_build_query($urlParams),
940
                    'GET');
941
            }
942
        }
943
        $responseEvidence = $this->getResponseEvidence();
944
        if (is_array($transactions) && array_key_exists($responseEvidence,
945
                $transactions)) {
946
            $result = $transactions[$responseEvidence];
947
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
948
                $result = null; // Response is empty Array
949
            }
950
        } else {
951
            $result = $transactions;
952
        }
953
954
        return $result;
955
    }
956
957
    /**
958
     * Načte záznam z FlexiBee a uloží v sobě jeho data
959
     * Read FlexiBee record and store it inside od object
960
     *
961
     * @param int|array $id ID or conditions
962
     *
963
     * @return int počet načtených položek
964
     */
965
    public function loadFromFlexiBee($id = null)
966
    {
967
        $data = [];
968
        if (is_null($id)) {
969
            $id = $this->getMyKey();
970
        }
971
972
        $flexidata = $this->getFlexiData(null, is_array($id) ? $id : '/'.$id);
973
974
        $this->apiURL = $this->curlInfo['url'];
975
        if (is_array($flexidata) && (count($flexidata) == 1)) {
976
            $data = current($flexidata);
977
        }
978
        return $this->takeData($data);
979
    }
980
981
    /**
982
     * Převede data do Json formátu pro FlexiBee.
983
     * Convert data to FlexiBee like Json format
984
     *
985
     * @param array $data
986
     *
987
     * @return string
988
     */
989
    public function jsonizeData($data)
990
    {
991
        $jsonize = [
992
            $this->nameSpace => [
993
                '@version' => $this->protoVersion,
994
                $this->evidence => $this->objectToID($data),
995
            ],
996
        ];
997
998 View Code Duplication
        if (!is_null($this->action)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
999
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
1000
            $this->action                                         = null;
1001
        }
1002
1003 View Code Duplication
        if (!is_null($this->filter)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1004
            $jsonize[$this->nameSpace][$this->evidence.'@filter'] = $this->filter;
1005
        }
1006
1007
        return json_encode($jsonize);
1008
    }
1009
1010
    /**
1011
     * Test if given record ID exists in FlexiBee.
1012
     *
1013
     * @param string|int $identifer
1014
     */
1015
    public function idExists($identifer = null)
1016
    {
1017
        if (is_null($identifer)) {
1018
            $identifer = $this->getMyKey();
1019
        }
1020
        $flexiData = $this->getFlexiData(
1021
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
1022
1023
        return $flexiData;
1024
    }
1025
1026
    /**
1027
     * Test if given record exists in FlexiBee.
1028
     *
1029
     * @param array $data
1030
     * @return boolean Record presence status
1031
     */
1032
    public function recordExists($data = null)
1033
    {
1034
1035
        if (is_null($data)) {
1036
            $data = $this->getData();
1037
        }
1038
1039
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1040
            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...
1041
1042
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1043
            || !count($res[0])) {
1044
            $found = false;
1045
        } else {
1046
            $found = true;
1047
        }
1048
        return $found;
1049
    }
1050
1051
    /**
1052
     * Vrací z FlexiBee sloupečky podle podmínek.
1053
     *
1054
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1055
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1056
     *                                     sloupečku
1057
     * @return array
1058
     */
1059
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1060
    {
1061
        if (is_int($conditions)) {
1062
            $conditions = [$this->getmyKeyColumn() => $conditions];
1063
        }
1064
1065
        $flexiData = $this->getFlexiData('', $conditions);
1066
1067
        if (!is_null($indexBy)) {
1068
            $flexiData = $this->reindexArrayBy($flexiData);
1069
        }
1070
1071
        return $flexiData;
1072
    }
1073
1074
    /**
1075
     * Vrací z FlexiBee sloupečky podle podmínek.
1076
     *
1077
     * @param string[] $columnsList seznam položek
1078
     * @param array    $conditions  pole podmínek nebo ID záznamu
1079
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1080
     *
1081
     * @return array
1082
     */
1083
    public function getColumnsFromFlexibee($columnsList, $conditions = null,
1084
                                           $indexBy = null)
1085
    {
1086
        $detail = 'full';
1087
        switch (gettype($columnsList)) {
1088
            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...
1089
                $conditions = [$this->getmyKeyColumn() => $conditions];
1090
            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...
1091
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1092
                        $columnsList)) {
1093
                    $columnsList[] = $indexBy;
1094
                }
1095
                $columns = implode(',', array_unique($columnsList));
1096
                $detail  = 'custom:'.$columns;
1097
            default:
1098
                switch ($columnsList) {
1099
                    case 'id':
1100
                        $detail = 'id';
1101
                        break;
1102
                    case 'summary':
1103
                        $detail = 'summary';
1104
                        break;
1105
                    default:
1106
                        break;
1107
                }
1108
                break;
1109
        }
1110
1111
        $flexiData = $this->getFlexiData('detail='.$detail, $conditions);
1112
1113
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1114
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1115
        }
1116
1117
        return $flexiData;
1118
    }
1119
1120
    /**
1121
     * Vrací kód záznamu.
1122
     *
1123
     * @param mixed $data
1124
     *
1125
     * @return string
1126
     */
1127
    public function getKod($data = null, $unique = true)
1128
    {
1129
        $kod = null;
1130
1131
        if (is_null($data)) {
1132
            $data = $this->getData();
1133
        }
1134
1135
        if (is_string($data)) {
1136
            $data = [$this->nameColumn => $data];
1137
        }
1138
1139
        if (isset($data['kod'])) {
1140
            $kod = $data['kod'];
1141
        } else {
1142
            if (isset($data[$this->nameColumn])) {
1143
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1144
                    \Ease\Sand::rip($data[$this->nameColumn]));
1145
            } else {
1146
                if (isset($data[$this->myKeyColumn])) {
1147
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1148
                }
1149
            }
1150
        }
1151
1152
        if (!strlen($kod)) {
1153
            $kod = 'NOTSET';
1154
        }
1155
1156
        if (strlen($kod) > 18) {
1157
            $kodfinal = strtoupper(substr($kod, 0, 18));
1158
        } else {
1159
            $kodfinal = strtoupper($kod);
1160
        }
1161
1162
        if ($unique) {
1163
            $counter = 0;
1164
            if (count($this->codes)) {
1165
                foreach ($this->codes as $codesearch => $keystring) {
1166
                    if (strstr($codesearch, $kodfinal)) {
1167
                        ++$counter;
1168
                    }
1169
                }
1170
            }
1171
            if ($counter) {
1172
                $kodfinal = $kodfinal.$counter;
1173
            }
1174
1175
            $this->codes[$kodfinal] = $kod;
1176
        }
1177
1178
        return $kodfinal;
1179
    }
1180
1181
    /**
1182
     * Write Operation Result.
1183
     *
1184
     * @param array  $resultData
1185
     * @param string $url        URL
1186
     * @return boolean Log save success
1187
     */
1188
    public function logResult($resultData = null, $url = null)
1189
    {
1190
        $logResult = false;
1191
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1192
            if (isset($resultData['message'])) {
1193
                $this->addStatusMessage($resultData['message'], 'warning');
1194
            }
1195
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1196
                'warning');
1197
            unset($url);
1198
        }
1199
        if (is_null($resultData)) {
1200
            $resultData = $this->lastResult;
1201
        }
1202
        if (isset($url)) {
1203
            $this->logger->addStatusMessage(urldecode($url));
1204
        }
1205
1206
        if (isset($resultData['results'])) {
1207
            if ($resultData['success'] == 'false') {
1208
                $status = 'error';
1209
            } else {
1210
                $status = 'success';
1211
            }
1212
            foreach ($resultData['results'] as $result) {
1213
                if (isset($result['request-id'])) {
1214
                    $rid = $result['request-id'];
1215
                } else {
1216
                    $rid = '';
1217
                }
1218
                if (isset($result['errors'])) {
1219
                    foreach ($result['errors'] as $error) {
1220
                        $message = $error['message'];
1221
                        if (isset($error['for'])) {
1222
                            $message .= ' for: '.$error['for'];
1223
                        }
1224
                        if (isset($error['value'])) {
1225
                            $message .= ' value:'.$error['value'];
1226
                        }
1227
                        if (isset($error['code'])) {
1228
                            $message .= ' code:'.$error['code'];
1229
                        }
1230
                        $this->addStatusMessage($rid.': '.$message, $status);
1231
                    }
1232
                }
1233
            }
1234
        }
1235
        return $logResult;
1236
    }
1237
1238
    /**
1239
     * Save RAW Curl Request & Response to files in Temp directory
1240
     */
1241
    public function saveDebugFiles()
1242
    {
1243
        $tmpdir = sys_get_temp_dir();
1244
        file_put_contents($tmpdir.'/request-'.$this->evidence.'-'.microtime().'.'.$this->format,
1245
            $this->postFields);
1246
        file_put_contents($tmpdir.'/response-'.$this->evidence.'-'.microtime().'.'.$this->format,
1247
            $this->lastCurlResponse);
1248
    }
1249
1250
    /**
1251
     * Připraví data pro odeslání do FlexiBee
1252
     *
1253
     * @param string $data
1254
     */
1255
    public function setPostFields($data)
1256
    {
1257
        $this->postFields = $data;
1258
    }
1259
1260
    /**
1261
     * Generuje fragment url pro filtrování.
1262
     *
1263
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1264
     *
1265
     * @param array  $data
1266
     * @param string $joiner default and/or
1267
     * @param string $defop  default operator
1268
     *
1269
     * @return string
1270
     */
1271
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1272
    {
1273
        $parts = [];
1274
1275
        foreach ($data as $column => $value) {
1276
            if (is_integer($data[$column]) || is_float($data[$column])) {
1277
                $parts[$column] = $column.' eq \''.$data[$column].'\'';
1278
            } elseif (is_bool($data[$column])) {
1279
                $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1280
            } elseif (is_null($data[$column])) {
1281
                $parts[$column] = $column." is null";
1282
            } else {
1283
                switch ($value) {
1284
                    case '!null':
1285
                        $parts[$column] = $column." is not null";
1286
                        break;
1287
                    case 'is empty':
1288
                    case 'is not empty':
1289
                        $parts[$column] = $column.' '.$value;
1290
                        break;
1291
                    default:
1292
                        if ($column == 'stitky') {
1293
                            $parts[$column] = $column."='code:".$data[$column]."'";
1294
                        } else {
1295
                            $parts[$column] = $column." $defop '".$data[$column]."'";
1296
                        }
1297
                        break;
1298
                }
1299
            }
1300
        }
1301
        return implode(' '.$joiner.' ', $parts);
1302
    }
1303
1304
    /**
1305
     * Obtain record/object identificator code: or id:
1306
     * Vrací identifikátor objektu code: nebo id:
1307
     *
1308
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1309
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1310
     */
1311
    public function getRecordID()
1312
    {
1313
        $myCode = $this->getDataValue('kod');
1314
        if ($myCode) {
1315
            $id = 'code:'.$myCode;
1316
        } else {
1317
            $id = $this->getDataValue('id');
1318
            if (($this->debug === true) && is_null($id)) {
1319
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1320
                    'warning');
1321
            }
1322
        }
1323
        return is_numeric($id) ? intval($id) : strval($id);
1324
    }
1325
1326
    /**
1327
     * Obtain record/object identificator code: or id:
1328
     * Vrací identifikátor objektu code: nebo id:
1329
     *
1330
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1331
     * @return string indentifikátor záznamu reprezentovaného objektem
1332
     */
1333
    public function __toString()
1334
    {
1335
        return strval($this->getRecordID());
1336
    }
1337
1338
    /**
1339
     * Gives you FlexiPeeHP class name for Given Evidence
1340
     *
1341
     * @param string $evidence
1342
     * @return string Class name
1343
     */
1344
    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...
1345
    {
1346
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1347
    }
1348
1349
    /**
1350
     * Vrací hodnotu daného externího ID
1351
     *
1352
     * @param string $want Which ? If empty,you obtain the first one.
1353
     * @return string
1354
     */
1355
    public function getExternalID($want = null)
1356
    {
1357
        $extid = null;
1358
        $ids   = $this->getDataValue('external-ids');
1359
        if (is_null($want)) {
1360
            if (count($ids)) {
1361
                $extid = current($ids);
1362
            }
1363
        } else {
1364
            if (!is_null($ids) && is_array($ids)) {
1365
                foreach ($ids as $id) {
1366
                    if (strstr($id, 'ext:'.$want)) {
1367
                        $extid = str_replace('ext:'.$want.':', '', $id);
1368
                    }
1369
                }
1370
            }
1371
        }
1372
        return $extid;
1373
    }
1374
1375
    /**
1376
     * Obtain actual GlobalVersion
1377
     * Vrací aktuální globální verzi změn
1378
     *
1379
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1380
     * @return type
1381
     */
1382
    public function getGlobalVersion()
1383
    {
1384
        $globalVersion = null;
1385
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1386
            $this->getFlexiData(null,
1387
                ['add-global-version' => 'true', 'limit' => 1]);
1388
        }
1389
1390
        if (isset($this->lastResult['@globalVersion'])) {
1391
            $globalVersion = intval($this->lastResult['@globalVersion']);
1392
        }
1393
1394
        return $globalVersion;
1395
    }
1396
1397
    /**
1398
     * Obtain content type of last response
1399
     *
1400
     * @return string
1401
     */
1402
    public function getResponseFormat()
1403
    {
1404
        if (isset($this->curlInfo['content_type'])) {
1405
            $responseFormat = $this->curlInfo['content_type'];
1406
        } else {
1407
            $responseFormat = null;
1408
        }
1409
        return $responseFormat;
1410
    }
1411
1412
    /**
1413
     * Return the same response format for one and multiplete results
1414
     *
1415
     * @param array $responseBody
1416
     * @return array
1417
     */
1418
    public function unifyResponseFormat($responseBody)
1419
    {
1420
        if (!is_array($responseBody) || array_key_exists('message',
1421
                $responseBody)) { //Unifi response format
1422
            $response = $responseBody;
1423
        } else {
1424
            $evidence = $this->getResponseEvidence();
1425
            if (array_key_exists($evidence, $responseBody)) {
1426
                $response        = [];
1427
                $evidenceContent = $responseBody[$evidence];
1428
                if (array_key_exists(0, $evidenceContent)) {
1429
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1430
                } else {
1431
                    $response[$evidence][0] = $evidenceContent; //One result
1432
                }
1433
            } else {
1434
                if (isset($responseBody['priloha'])) {
1435
                    $response = $responseBody['priloha'];
1436
                } else {
1437
                    $response = $responseBody;
1438
                }
1439
            }
1440
        }
1441
        return $response;
1442
    }
1443
1444
    /**
1445
     * Obtain structure for current (or given) evidence
1446
     *
1447
     * @param string $evidence
1448
     * @return array Evidence structure
1449
     */
1450 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...
1451
    {
1452
        $columnsInfo = null;
1453
        if (is_null($evidence)) {
1454
            $evidence = $this->getEvidence();
1455
        }
1456
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1457
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1458
            $columnsInfo = Properties::$$propsName;
1459
        }
1460
        return $columnsInfo;
1461
    }
1462
1463
    /**
1464
     * Obtain actions for current (or given) evidence
1465
     *
1466
     * @param string $evidence
1467
     * @return array Evidence structure
1468
     */
1469 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...
1470
    {
1471
        $actionsInfo = null;
1472
        if (is_null($evidence)) {
1473
            $evidence = $this->getEvidence();
1474
        }
1475
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1476
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1477
            $actionsInfo = Actions::$$propsName;
1478
        }
1479
        return $actionsInfo;
1480
    }
1481
1482
    /**
1483
     * Obtain relations for current (or given) evidence
1484
     *
1485
     * @param string $evidence
1486
     * @return array Evidence structure
1487
     */
1488
    public function getRelationsInfo($evidence = null)
1489
    {
1490
        $relationsInfo = null;
1491
        if (is_null($evidence)) {
1492
            $evidence = $this->getEvidence();
1493
        }
1494
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1495
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1496
            $relationsInfo = Relations::$$propsName;
1497
        }
1498
        return $relationsInfo;
1499
    }
1500
1501
    /**
1502
     * Obtain info for current (or given) evidence
1503
     *
1504
     * @param string $evidence
1505
     * @return array Evidence info
1506
     */
1507 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...
1508
    {
1509
        $evidencesInfo = null;
1510
        if (is_null($evidence)) {
1511
            $evidence = $this->getEvidence();
1512
        }
1513
        if (isset(EvidenceList::$evidences[$evidence])) {
1514
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1515
        }
1516
        return $evidencesInfo;
1517
    }
1518
1519
    /**
1520
     * Obtain name for current (or given) evidence path
1521
     *
1522
     * @param string $evidence Evidence Path
1523
     * @return array Evidence info
1524
     */
1525 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...
1526
    {
1527
        $evidenceName = null;
1528
        if (is_null($evidence)) {
1529
            $evidence = $this->getEvidence();
1530
        }
1531
        if (isset(EvidenceList::$name[$evidence])) {
1532
            $evidenceName = EvidenceList::$name[$evidence];
1533
        }
1534
        return $evidenceName;
1535
    }
1536
1537
    /**
1538
     * Perform given action (if availble) on current evidence/record
1539
     * @url https://demo.flexibee.eu/devdoc/actions
1540
     *
1541
     * @param string $action one of evidence actions
1542
     * @param string $method ext|int External method call operation in URL.
1543
     *                               Internal add the @action element to request body
1544
     */
1545
    public function performAction($action, $method = 'ext')
1546
    {
1547
        $actionsAvailble = $this->getActionsInfo();
1548
1549
        if (is_array($actionsAvailble) && array_key_exists($action,
1550
                $actionsAvailble)) {
1551
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1552
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1553
                case 'ONLY_WITH_INSTANCE': //Add instance
1554
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1555
                    break;
1556
1557
                default:
1558
                    $urlSuffix = '/'.$action;
1559
                    break;
1560
            }
1561
1562
            switch ($method) {
1563
                case 'int':
1564
                    $this->setAction($action);
1565
                    $this->setPostFields($this->jsonizeData($this->getData()));
1566
                    $result = $this->performRequest(null, 'POST');
1567
                    break;
1568
1569
                default:
1570
                    $result = $this->performRequest($urlSuffix, 'GET');
1571
                    break;
1572
            }
1573
        } else {
1574
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1575
                $action, $this->getEvidence()));
1576
        }
1577
1578
        return $result;
1579
    }
1580
1581
    /**
1582
     * Save current object to file
1583
     *
1584
     * @param string $destfile path to file
1585
     */
1586
    public function saveResponseToFile($destfile)
1587
    {
1588
        if (strlen($this->lastCurlResponse)) {
1589
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1590
        }
1591
        file_put_contents($destfile, $this->lastCurlResponse);
1592
    }
1593
1594
    /**
1595
     * Obtain established relations listing
1596
     *
1597
     * @return array Null or Relations
1598
     */
1599
    public function getVazby()
1600
    {
1601
        $vazby = $this->getDataValue('vazby');
1602
        if (is_null($vazby)) {
1603
            $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...
1604
                ['relations' => 'vazby', 'id' => $this->getRecordID()]);
1605
            $vazby = $vazby[0]['vazby'];
1606
        }
1607
        return $vazby;
1608
    }
1609
1610
    /**
1611
     * Gives You URL for Current Record in FlexiBee web interface
1612
     *
1613
     * @return string url
1614
     */
1615
    public function getFlexiBeeURL()
1616
    {
1617
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1618
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1619
                : '';
1620
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1621
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1622
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1623
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1624
        $pass       = ($user || $pass) ? "$pass@" : '';
1625
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1626
        return $scheme.$user.$pass.$host.$port.$path;
1627
    }
1628
1629
    /**
1630
     * Set Record Key
1631
     *
1632
     * @param int|string $myKeyValue
1633
     * @return boolean
1634
     */
1635
    public function setMyKey($myKeyValue)
1636
    {
1637
        $res = parent::setMyKey($myKeyValue);
1638
        $this->updateApiURL();
1639
        return $res;
1640
    }
1641
1642
    /**
1643
     * Set or get ignore not found pages flag
1644
     *
1645
     * @param boolean $ignore set flag to
1646
     *
1647
     * @return boolean get flag state
1648
     */
1649
    public function ignore404($ignore = null)
1650
    {
1651
        if (!is_null($ignore)) {
1652
            $this->ignoreNotFound = $ignore;
1653
        }
1654
        return $this->ignoreNotFound;
1655
    }
1656
1657
    /**
1658
     * Send Document by mail
1659
     *
1660
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1661
     *
1662
     * @param string $to
1663
     * @param string $subject
1664
     * @param string $body Email Text
1665
     *
1666
     * @return int http response code
1667
     */
1668
    public function sendByMail($to, $subject, $body, $cc = null)
1669
    {
1670
        $this->setPostFields($body);
1671
        $result = $this->doCurlRequest($this->getEvidenceURL().'/'.
1672
            urlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1673
            , 'PUT', 'xml');
1674
        return $result == 200;
1675
    }
1676
1677
    /**
1678
     * Send all unsent Invoices by mail
1679
     *
1680
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1681
     * @return int http response code
1682
     */
1683
    public function sendUnsent()
1684
    {
1685
        return $this->doCurlRequest($this->getEvidenceURL().'/automaticky-odeslat-neodeslane',
1686
                'PUT', 'xml');
1687
    }
1688
1689
    /**
1690
     * FlexiBee date to PHP DateTime
1691
     *
1692
     * @param string $flexidate
1693
     * @return \DateTime
1694
     */
1695
    public static function flexiDateToDateTime($flexidate)
1696
    {
1697
        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 1697 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...
1698
    }
1699
1700
    /**
1701
     * Získá dokument v daném formátu
1702
     * Obtain document in given format
1703
     *
1704
     * @param string $format  pdf/csv/xml/json/ ...
1705
     *
1706
     * @return string|null filename downloaded or none
1707
     */
1708
    public function getInFormat($format)
1709
    {
1710
        $response = null;
1711
        if ($this->setFormat($format)) {
1712
            if (($this->doCurlRequest(($format == 'html') ? $this->apiURL.'?inDesktopApp=true'
1713
                            : $this->apiURL, 'GET') == 200)) {
1714
                $response = $this->lastCurlResponse;
1715
            }
1716
        }
1717
        return $response;
1718
    }
1719
1720
    /**
1721
     * Uloží dokument v daném formátu do složky v systému souborů
1722
     * Save document in given format to directory in filesystem
1723
     *
1724
     * @param string $format  pdf/csv/xml/json/ ...
1725
     * @param string $destDir where to put file (prefix)
1726
     * 
1727
     * @return string|null filename downloaded or none
1728
     */
1729
    public function downloadInFormat($format, $destDir = './')
1730
    {
1731
        $fileOnDisk = null;
1732
        if ($this->setFormat($format)) {
1733
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
1734
            if (($this->doCurlRequest($this->apiURL, 'GET') == 200) && (file_put_contents($downloadTo,
1735
                    $this->lastCurlResponse) !== false)) {
1736
                $fileOnDisk = $downloadTo;
1737
            }
1738
        }
1739
        return $fileOnDisk;
1740
    }
1741
1742
    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...
1743
    {
1744
        //Send Raw Request: Method/URL/Headers/Body
1745
        //With tail of FlexiBee log 
1746
        //To FlexiBee developers team
1747
        //By mail
1748
    }
1749
}
1750