Test Failed
Push — master ( 9bab16...fc0349 )
by Vítězslav
02:57
created

FlexiBeeRO   D

Complexity

Total Complexity 259

Size/Duplication

Total Lines 1699
Duplicated Lines 3.77 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 64
loc 1699
rs 4
c 0
b 0
f 0
wmc 259
lcom 1
cbo 5

61 Methods

Rating   Name   Duplication   Size   Complexity  
A getColumnsInfo() 12 12 3
A getActionsInfo() 12 12 3
A getRelationsInfo() 0 12 3
A getEvidenceInfo() 11 11 3
A getEvidenceName() 11 11 3
A __construct() 0 11 2
F setUp() 0 43 17
A curlInit() 0 12 1
B processInit() 0 13 5
C setPrefix() 0 21 11
B setFormat() 0 16 5
A setEvidence() 0 20 3
A getEvidence() 0 4 1
A setCompany() 0 4 1
A getCompany() 0 4 1
A getResponseEvidence() 0 15 3
B object2array() 9 20 6
A objectToID() 9 17 4
A getEvidenceURL() 0 9 3
A updateApiURL() 0 9 2
A performRequest() 0 16 3
B rawResponseToArray() 0 26 6
D parseResponse() 0 36 10
A parseError() 0 9 2
C doCurlRequest() 0 48 9
A setAction() 0 10 2
A xml2array() 0 18 4
A disconnect() 0 7 2
A __destruct() 0 4 1
A getFlexiRow() 0 10 2
A extractUrlParams() 0 8 3
C getFlexiData() 0 40 11
B loadFromFlexiBee() 0 15 5
A jsonizeData() 0 16 2
A idExists() 0 10 2
B recordExists() 0 18 6
A getAllFromFlexibee() 0 14 3
D getColumnsFromFlexibee() 0 36 10
D getKod() 0 53 13
C logResult() 0 49 15
A saveDebugFiles() 0 8 1
A setPostFields() 0 4 1
D flexiUrl() 0 27 10
B getRecordID() 0 14 5
A __toString() 0 4 1
A evidenceToClassName() 0 4 1
B getExternalID() 0 19 7
A getGlobalVersion() 0 14 4
A getResponseFormat() 0 9 2
B unifyResponseFormat() 0 25 6
B performAction() 0 35 6
A saveResponseToFile() 0 7 2
A getVazby() 0 10 2
C getFlexiBeeURL() 0 13 9
A setMyKey() 0 6 1
A ignore404() 0 7 2
A sendByMail() 0 8 1
A sendUnsent() 0 5 1
A flexiDateToDateTime() 0 4 1
A downloadInFormat() 0 12 4
A error500Reporter() 0 7 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FlexiBeeRO often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FlexiBeeRO, and based on these observations, apply Extract Interface, too.

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 a uloží v sobě jeho data
953
     * Read FlexiBee record and store it inside od object
954
     *
955
     * @param int|array $id ID or conditions
956
     *
957
     * @return int počet načtených položek
958
     */
959
    public function loadFromFlexiBee($id = null)
960
    {
961
        $data = [];
962
        if (is_null($id)) {
963
            $id = $this->getMyKey();
964
        }
965
966
        $flexidata = $this->getFlexiData(null, is_array($id) ? $id : '/'.$id);
967
968
        $this->apiURL = $this->curlInfo['url'];
969
        if (is_array($flexidata) && (count($flexidata) == 1)) {
970
            $data = current($flexidata);
971
        }
972
        return $this->takeData($data);
973
    }
974
975
    /**
976
     * Převede data do Json formátu pro FlexiBee.
977
     * Convert data to FlexiBee like Json format
978
     *
979
     * @param array $data
980
     *
981
     * @return string
982
     */
983
    public function jsonizeData($data)
984
    {
985
        $jsonize = [
986
            $this->nameSpace => [
987
                '@version' => $this->protoVersion,
988
                $this->evidence => $this->objectToID($data),
989
            ],
990
        ];
991
992
        if (!is_null($this->action)) {
993
            $jsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
994
            $this->action                                         = null;
995
        }
996
997
        return json_encode($jsonize);
998
    }
999
1000
    /**
1001
     * Test if given record ID exists in FlexiBee.
1002
     *
1003
     * @param string|int $identifer
1004
     */
1005
    public function idExists($identifer = null)
1006
    {
1007
        if (is_null($identifer)) {
1008
            $identifer = $this->getMyKey();
1009
        }
1010
        $flexiData = $this->getFlexiData(
1011
            'detail=custom:'.$this->getmyKeyColumn(), $identifer);
1012
1013
        return $flexiData;
1014
    }
1015
1016
    /**
1017
     * Test if given record exists in FlexiBee.
1018
     *
1019
     * @param array $data
1020
     * @return boolean Record presence status
1021
     */
1022
    public function recordExists($data = null)
1023
    {
1024
1025
        if (is_null($data)) {
1026
            $data = $this->getData();
1027
        }
1028
1029
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1030
            self::flexiUrl($data));
0 ignored issues
show
Documentation introduced by
self::flexiUrl($data) is of type string, but the function expects a array|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

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