Test Failed
Push — master ( a01320...02a0f6 )
by Vítězslav
12:23
created

FlexiBeeRO::flexiDateToDateTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * FlexiPeeHP - Read Only Access to FlexiBee class.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015-2017 Spoje.Net
7
 */
8
9
namespace FlexiPeeHP;
10
11
/**
12
 * Základní třída pro čtení z FlexiBee
13
 *
14
 * @url https://demo.flexibee.eu/devdoc/
15
 */
16
class FlexiBeeRO extends \Ease\Brick
17
{
18
    /**
19
     * Version of FlexiPeeHP library
20
     *
21
     * @var string
22
     */
23
    public static $libVersion = '1.6.4.2';
24
25
    /**
26
     * Základní namespace pro komunikaci s FlexiBee.
27
     * Basic namespace for communication with FlexiBee
28
     *
29
     * @var string Jmený prostor datového bloku odpovědi
30
     */
31
    public $nameSpace = 'winstrom';
32
33
    /**
34
     * URL of object data in FlexiBee
35
     * @var string url
36
     */
37
    public $apiURL = null;
38
39
    /**
40
     * Datový blok v poli odpovědi.
41
     * Data block in response field.
42
     *
43
     * @var string
44
     */
45
    public $resultField = 'results';
46
47
    /**
48
     * Verze protokolu použitého pro komunikaci.
49
     * Communication protocol version used.
50
     *
51
     * @var string Verze použitého API
52
     */
53
    public $protoVersion = '1.0';
54
55
    /**
56
     * Evidence užitá objektem.
57
     * Evidence used by object
58
     *
59
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
60
     * @var string
61
     */
62
    public $evidence = null;
63
64
    /**
65
     * Výchozí formát pro komunikaci.
66
     * Default communication format.
67
     *
68
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
69
     *
70
     * @var string json|xml|...
71
     */
72
    public $format = 'json';
73
74
    /**
75
     * formát příchozí odpovědi
76
     * response format
77
     *
78
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
79
     *
80
     * @var string json|xml|...
81
     */
82
    public $responseFormat = 'json';
83
84
    /**
85
     * Curl Handle.
86
     *
87
     * @var resource
88
     */
89
    public $curl = null;
90
91
    /**
92
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
93
     * @var string
94
     */
95
    public $company = null;
96
97
    /**
98
     * Server[:port]
99
     * @var string
100
     */
101
    public $url = null;
102
103
    /**
104
     * REST API Username
105
     * @var string
106
     */
107
    public $user = null;
108
109
    /**
110
     * REST API Password
111
     * @var string
112
     */
113
    public $password = null;
114
115
    /**
116
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
117
     */
118
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
119
120
    /**
121
     * Default additional request url parameters after question mark
122
     *
123
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
124
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
125
     * @var array
126
     */
127
    public $defaultUrlParams = ['limit' => 0];
128
129
    /**
130
     * Identifikační řetězec.
131
     *
132
     * @var string
133
     */
134
    public $init = null;
135
136
    /**
137
     * Sloupeček s názvem.
138
     *
139
     * @var string
140
     */
141
    public $nameColumn = 'nazev';
142
143
    /**
144
     * Sloupeček obsahující datum vložení záznamu do shopu.
145
     *
146
     * @var string
147
     */
148
    public $myCreateColumn = 'false';
149
150
    /**
151
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
152
     *
153
     * @var string
154
     */
155
    public $myLastModifiedColumn = 'lastUpdate';
156
157
    /**
158
     * Klíčový idendifikátor záznamu.
159
     *
160
     * @var string
161
     */
162
    public $fbKeyColumn = 'id';
163
164
    /**
165
     * Informace o posledním HTTP requestu.
166
     *
167
     * @var *
168
     */
169
    public $curlInfo;
170
171
    /**
172
     * Informace o poslední HTTP chybě.
173
     *
174
     * @var string
175
     */
176
    public $lastCurlError = null;
177
178
    /**
179
     * Used codes storage.
180
     *
181
     * @var array
182
     */
183
    public $codes = null;
184
185
    /**
186
     * Last Inserted ID.
187
     *
188
     * @var int
189
     */
190
    public $lastInsertedID = null;
191
192
    /**
193
     * Default Line Prefix.
194
     *
195
     * @var string
196
     */
197
    public $prefix = '/c/';
198
199
    /**
200
     * Raw Content of last curl response
201
     *
202
     * @var string
203
     */
204
    public $lastCurlResponse;
205
206
    /**
207
     * HTTP Response code of last request
208
     *
209
     * @var int
210
     */
211
    public $lastResponseCode = null;
212
213
    /**
214
     * Body data  for next curl POST operation
215
     *
216
     * @var string
217
     */
218
    protected $postFields = null;
219
220
    /**
221
     * Last operation result data or message(s)
222
     *
223
     * @var array
224
     */
225
    public $lastResult = null;
226
227
    /**
228
     * Nuber from  @rowCount
229
     * @var int
230
     */
231
    public $rowCount = null;
232
233
    /**
234
     * @link https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
235
     * @var string filter query
236
     */
237
    public $filter;
238
239
    /**
240
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
241
     * @var string
242
     */
243
    protected $action;
244
245
    /**
246
     * Pole akcí které podporuje ta která evidence
247
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
248
     * @var array
249
     */
250
    public $actionsAvailable = null;
251
252
    /**
253
     * Parmetry pro URL
254
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
255
     * @var array
256
     */
257
    public $urlParams = [
258
        'idUcetniObdobi',
259
        'dry-run',
260
        'fail-on-warning',
261
        'report-name',
262
        'report-lang',
263
        'report-sign',
264
        'detail', //See: https://www.flexibee.eu/api/dokumentace/ref/detail-levels
265
        'mode',
266
        'limit',
267
        'start',
268
        'order',
269
        'sort',
270
        'add-row-count',
271
        'relations',
272
        'includes',
273
        'use-ext-id',
274
        'use-internal-id',
275
        'stitky-as-ids',
276
        'only-ext-ids',
277
        'no-ext-ids',
278
        'no-ids',
279
        'code-as-id',
280
        'no-http-errors',
281
        'export-settings',
282
        'as-gui',
283
        'code-in-response',
284
        'add-global-version',
285
        'encoding',
286
        'delimeter',
287
        'format',
288
        'auth',
289
        'skupina-stitku',
290
        'dir',
291
        'relations',
292
        'relations',
293
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
294
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
295
        'inDesktopApp' // Note: Undocumented function (html only)
296
    ];
297
298
    /**
299
     * Save 404 results to log ?
300
     * @var boolean
301
     */
302
    protected $ignoreNotFound = false;
303
304
    /**
305
     * Array of errors caused by last request
306
     * @var array
307
     */
308
    private $errors = [];
309
310
    /**
311
     * List of Error500 reports sent
312
     * @var array
313
     */
314
    private $reports = [];
315
316
    /**
317
     * Send Error500 Report to
318
     * @var string email address
319
     */
320
    public $reportRecipient = '[email protected]';
321
322
    /**
323
     * Class for read only interaction with FlexiBee.
324
     *
325
     * @param mixed $init default record id or initial data
326
     * @param array $options Connection settings override
327
     */
328 24
    public function __construct($init = null, $options = [])
329
    {
330 24
        $this->init = $init;
331
332 24
        parent::__construct();
333 24
        $this->setUp($options);
334 24
        $this->curlInit();
335 24
        if (!empty($init)) {
336 22
            $this->processInit($init);
337 22
        }
338 24
    }
339
340
    /**
341
     * SetUp Object to be ready for connect
342
     *
343
     * @param array $options Object Options (company,url,user,password,evidence,
344
     *                                       prefix,defaultUrlParams,debug)
345
     */
346 47
    public function setUp($options = [])
347
    {
348 47
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
349 47
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
350 47
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
351 47
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
352 47
        if (isset($options['evidence'])) {
353 45
            $this->setEvidence($options['evidence']);
354 45
        }
355 47
        $this->setupProperty($options, 'defaultUrlParams');
356 47
        if (isset($options['prefix'])) {
357 45
            $this->setPrefix($options['prefix']);
358 45
        }
359 47
        $this->setupProperty($options, 'debug');
360 47
        $this->updateApiURL();
361 47
    }
362
363
    /**
364
     * Set up one of properties
365
     *
366
     * @param array  $options  array of given properties
367
     * @param string $name     name of property to process
368
     * @param string $constant load default property value from constant
369
     */
370 24
    public function setupProperty($options, $name, $constant = null)
371
    {
372 24
        if (isset($options[$name])) {
373 22
            $this->$name = $options[$name];
374 22
        } else {
375 24
            if (is_null($this->$name) && !empty($constant) && defined($constant)) {
376 24
                $this->$name = constant($constant);
377 24
            }
378
        }
379 24
    }
380
381
    /**
382
     * Inicializace CURL
383
     */
384 70
    public function curlInit()
385
    {
386 70
        $this->curl = \curl_init(); // create curl resource
387 70
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
388 70
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
389 70
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
390 70
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
391 70
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
392 70
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
393 70
        curl_setopt($this->curl, CURLOPT_USERPWD,
394 70
            $this->user.':'.$this->password); // set username and password
395 70
    }
396
397
    /**
398
     * Zinicializuje objekt dle daných dat. Možné hodnoty:
399
     *
400
     *  * 234                              - interní číslo záznamu k načtení
401
     *  * code:LOPATA                      - kód záznamu
402
     *  * BAGR                             - kód záznamu ka načtení
403
     *  * ['id'=>24,'nazev'=>'hoblík']     - pole hodnot k předvyplnění
404
     *  * 743.json?relations=adresa,vazby  - část url s parametry k načtení
405
     *
406
     * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění
407
     */
408 44
    public function processInit($init)
409
    {
410 44
        if (is_integer($init)) {
411 42
            $this->loadFromFlexiBee($init);
412 44
        } elseif (is_array($init)) {
413 22
            $this->takeData($init);
414 22
        } elseif (preg_match('/\.(json|xml|csv)/', $init)) {
415
            $this->takeData($this->getFlexiData((($init[0] != '/') ? $this->getEvidenceURL($init)
0 ignored issues
show
Unused Code introduced by
The call to FlexiBeeRO::getEvidenceURL() has too many arguments starting with $init.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
416
                            : $init)));
417
        } else {
418
            $this->loadFromFlexiBee('code:'.str_replace('code:', '', $init));
419
        }
420 44
    }
421
422
    /**
423
     * Set URL prefix
424
     *
425
     * @param string $prefix
426
     */
427 45
    public function setPrefix($prefix)
428
    {
429
        switch ($prefix) {
430 45
            case 'a': //Access
431 45
            case 'c': //Company
432 45
            case 'u': //User
433 45
            case 'g': //License Groups
434 45
            case 'admin':
435 45
            case 'status':
436 45
            case 'login-logout':
437 45
                $this->prefix = '/'.$prefix.'/';
438 45
                break;
439 23
            case null:
440 23
            case '':
441 23
            case '/':
442 23
                $this->prefix = '';
443 23
                break;
444 23
            default:
445 23
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
446 23
        }
447 45
    }
448
449
    /**
450
     * Set communication format.
451
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
452
     *
453
     * @param string $format
454
     * @return boolen format is availble
455
     */
456 23
    public function setFormat($format)
457
    {
458 23
        $result = true;
459 23
        if (($this->debug === true) && !empty($this->evidence) && isset(Formats::$$this->evidence)) {
460
            if (array_key_exists($format, array_flip(Formats::$$this->evidence))
461
                === false) {
462
                $result = false;
463
            }
464
        }
465 23
        if ($result === true) {
466 23
            $this->format = $format;
467 23
            $this->updateApiURL();
468 23
        }
469 23
        return $result;
470
    }
471
472
    /**
473
     * Nastaví Evidenci pro Komunikaci.
474
     * Set evidence for communication
475
     *
476
     * @param string $evidence evidence pathName to use
477
     * @return boolean evidence switching status
478
     */
479 45
    public function setEvidence($evidence)
480
    {
481 45
        switch ($this->prefix) {
482 45
            case '/c/':
483 44
                if (array_key_exists($evidence, EvidenceList::$name)) {
484 41
                    $this->evidence = $evidence;
485 41
                    $result         = true;
486 41
                } else {
487 23
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
488 23
                        $evidence));
489
                }
490 41
                break;
491 4
            default:
492 4
                $this->evidence = $evidence;
493 4
                $result         = true;
494 4
                break;
495 45
        }
496 45
        $this->updateApiURL();
497 45
        return $result;
498
    }
499
500
    /**
501
     * Vrací právě používanou evidenci pro komunikaci
502
     * Obtain current used evidence
503
     *
504
     * @return string
505
     */
506 47
    public function getEvidence()
507
    {
508 47
        return $this->evidence;
509
    }
510
511
    /**
512
     * Set used company.
513
     * Nastaví Firmu.
514
     *
515
     * @param string $company
516
     */
517 23
    public function setCompany($company)
518
    {
519 23
        $this->company = $company;
520 23
    }
521
522
    /**
523
     * Obtain company now used
524
     * Vrací právě používanou firmu
525
     *
526
     * @return string
527
     */
528 23
    public function getCompany()
529
    {
530 23
        return $this->company;
531
    }
532
533
    /**
534
     * Vrací název evidence použité v odpovědích z FlexiBee
535
     *
536
     * @return string
537
     */
538 44
    public function getResponseEvidence()
539
    {
540 44
        switch ($this->evidence) {
541 44
            case 'c':
542
                $evidence = 'company';
543
                break;
544 44
            case 'evidence-list':
545 2
                $evidence = 'evidence';
546 2
                break;
547 42
            default:
548 42
                $evidence = $this->getEvidence();
549 42
                break;
550 44
        }
551 44
        return $evidence;
552
    }
553
554
    /**
555
     * Převede rekurzivně Objekt na pole.
556
     *
557
     * @param object|array $object
558
     *
559
     * @return array
560
     */
561 23
    public static function object2array($object)
562
    {
563 23
        $result = null;
564 23
        if (is_object($object)) {
565 23
            $objectData = get_object_vars($object);
566 23
            if (is_array($objectData) && count($objectData)) {
567 23
                $result = array_map('self::object2array', $objectData);
568 23
            }
569 23
        } else {
570 23
            if (is_array($object)) {
571 23
                foreach ($object as $item => $value) {
572 23
                    $result[$item] = self::object2array($value);
573 23
                }
574 23
            } else {
575 23
                $result = $object;
576
            }
577
        }
578
579 23
        return $result;
580
    }
581
582
    /**
583
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
584
     *
585
     * @param object|array $object
586
     *
587
     * @return array
588
     */
589 23
    public static function objectToID($object)
590
    {
591 23
        $resultID = null;
592 23
        if (is_object($object)) {
593 23
            $resultID = $object->__toString();
594 23
        } else {
595 23
            if (is_array($object)) {
596 23
                foreach ($object as $item => $value) {
597 23
                    $resultID[$item] = self::objectToID($value);
598 23
                }
599 23
            } else { //String
600 23
                $resultID = $object;
601
            }
602
        }
603
604 23
        return $resultID;
605
    }
606
607
    /**
608
     * Return basic URL for used Evidence
609
     *
610
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
611
     *
612
     * @return string Evidence URL
613
     */
614 45
    public function getEvidenceURL()
615
    {
616 45
        $evidenceUrl = $this->url.$this->prefix.$this->company;
617 45
        $evidence    = $this->getEvidence();
618 45
        if (!empty($evidence)) {
619 43
            $evidenceUrl .= '/'.$evidence;
620 43
        }
621 45
        return $evidenceUrl;
622
    }
623
624
    /**
625
     * Add suffix to Evidence URL
626
     *
627
     * @param string $urlSuffix
628
     *
629
     * @return string
630
     */
631
    public function evidenceUrlWithSuffix($urlSuffix)
632
    {
633
        $evidenceUrl = $this->getEvidenceUrl();
634
        if (!empty($urlSuffix)) {
635
            if (($urlSuffix[0] != '/') && ($urlSuffix[0] != ';') && ($urlSuffix[0]
636
                != '?')) {
637
                $evidenceUrl .= '/';
638
            }
639
            $evidenceUrl .= $urlSuffix;
640
        }
641
        return $evidenceUrl;
642
    }
643
644
    /**
645
     * Update $this->apiURL
646
     */
647 24
    public function updateApiURL()
648
    {
649 24
        $this->apiURL = $this->getEvidenceURL();
650 24
        $id           = $this->__toString();
651 24
        if (!empty($id)) {
652 13
            $this->apiURL .= '/'.urlencode($id);
653 13
        }
654 24
        $this->apiURL .= '.'.$this->format;
655 24
    }
656
657
    /**
658
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
659
     *
660
     * @param string $urlSuffix část URL za identifikátorem firmy.
661
     * @param string $method    HTTP/REST metoda
662
     * @param string $format    Requested format
663
     * @return array|boolean Výsledek operace
664
     */
665 44
    public function performRequest($urlSuffix = null, $method = 'GET',
666
                                   $format = null)
667
    {
668 44
        $this->rowCount = null;
669
670 44
        if (preg_match('/^http/', $urlSuffix)) {
671 22
            $url = $urlSuffix;
672 44
        } elseif ($urlSuffix[0] == '/') {
673 2
            $url = $this->url.$urlSuffix;
674 2
        } else {
675 21
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
676
        }
677
678 44
        $responseCode = $this->doCurlRequest($url, $method, $format);
679
680 44
        return strlen($this->lastCurlResponse) ? $this->parseResponse($this->rawResponseToArray($this->lastCurlResponse,
681 44
                    $this->responseFormat), $responseCode) : null;
682
    }
683
684
    /**
685
     * Parse Raw FlexiBee response in several formats
686
     *
687
     * @param string $responseRaw raw response body
688
     * @param string $format      Raw Response format json|xml|etc
689
     *
690
     * @return array
691
     */
692 23
    public function rawResponseToArray($responseRaw, $format)
693
    {
694
        switch ($format) {
695 23
            case 'json':
696 23
                $responseDecoded = json_decode($responseRaw, true, 10);
697 23
                $decodeError     = json_last_error_msg();
698 23
                if ($decodeError == 'No error') {
699 23
                    if (array_key_exists($this->nameSpace, $responseDecoded)) {
700 21
                        $responseDecoded = $responseDecoded[$this->nameSpace];
701 21
                    }
702 23
                } else {
703
                    $this->addStatusMessage('JSON Decoder: '.$decodeError,
704
                        'error');
705
                    $this->addStatusMessage($responseRaw, 'debug');
706
                }
707 23
                break;
708
            case 'xml':
709
                $responseDecoded = self::xml2array($this->lastCurlResponse);
710
                break;
711
            case 'txt':
712
            default:
713
                $responseDecoded = $this->lastCurlResponse;
714
                break;
715
        }
716 23
        return $responseDecoded;
717
    }
718
719
    /**
720
     * Parse Response array
721
     *
722
     * @param array $responseDecoded
723
     * @param int $responseCode Request Response Code
724
     *
725
     * @return array main data part of response
726
     */
727 23
    public function parseResponse($responseDecoded, $responseCode)
728
    {
729 23
        $response = null;
730
        switch ($responseCode) {
731 23
            case 201: //Success Write
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...
732
                if (isset($responseDecoded[$this->resultField][0]['id'])) {
733
                    $this->lastInsertedID = $responseDecoded[$this->resultField][0]['id'];
734
                    $this->setMyKey($this->lastInsertedID);
735
                    $this->apiURL         = $this->getEvidenceURL().'/'.$this->lastInsertedID;
736
                } else {
737
                    $this->lastInsertedID = null;
738
                }
739 23
            case 200: //Success Read
740 14
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
741 14
                if (isset($responseDecoded['@rowCount'])) {
742
                    $this->rowCount = (int) $responseDecoded['@rowCount'];
743
                }
744 14
                break;
745
746 9
            case 500: // Internal Server Error
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...
747
                if ($this->debug === true) {
748
                    $this->error500Reporter($responseDecoded);
749
                }
750 9
            case 404: // Page not found
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...
751 8
                if ($this->ignoreNotFound === true) {
752
                    break;
753
                }
754 9
            case 400: //Bad Request parameters
755 9
            default: //Something goes wrong
756 9
                $this->addStatusMessage($this->curlInfo['url'], 'warning');
757 9
                if (is_array($responseDecoded)) {
758 9
                    $this->parseError($responseDecoded);
759 9
                }
760 9
                $this->logResult($responseDecoded, $this->curlInfo['url']);
761 9
                break;
762
        }
763 23
        return $response;
764
    }
765
766
    /**
767
     * Parse error message response
768
     *
769
     * @param array $responseDecoded
770
     * @return int number of errors processed
771
     */
772 9
    public function parseError(array $responseDecoded)
773
    {
774 9
        if (array_key_exists('results', $responseDecoded)) {
775
            $this->errors = $responseDecoded['results'][0]['errors'];
776
        } else {
777 9
            if (array_key_exists('message', $responseDecoded)) {
778 8
                $this->errors = [['message' => $responseDecoded['message']]];
779 8
            }
780
        }
781 9
        return count($this->errors);
782
    }
783
784
    /**
785
     * Vykonej HTTP požadavek
786
     *
787
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
788
     * @param string $url    URL požadavku
789
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
790
     * @param string $format požadovaný formát komunikace
791
     * @return int HTTP Response CODE
792
     */
793 23
    public function doCurlRequest($url, $method, $format = null)
794
    {
795 23
        if (is_null($format)) {
796 23
            $format = $this->format;
797 23
        }
798 23
        curl_setopt($this->curl, CURLOPT_URL, $url);
799
// Nastavení samotné operace
800 23
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
801
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
802 23
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
803
804 23
        $httpHeaders = $this->defaultHttpHeaders;
805
806 23
        $formats = Formats::bySuffix();
807
808 23
        if (!isset($httpHeaders['Accept'])) {
809 23
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
810 23
        }
811 23
        if (!isset($httpHeaders['Content-Type'])) {
812 23
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
813 23
        }
814 23
        $httpHeadersFinal = [];
815 23
        foreach ($httpHeaders as $key => $value) {
816 23
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
817 23
                $value .= ' v'.self::$libVersion;
818 23
            }
819 23
            $httpHeadersFinal[] = $key.': '.$value;
820 23
        }
821
822 23
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
823
824
// Proveď samotnou operaci
825 23
        $this->lastCurlResponse            = curl_exec($this->curl);
826 23
        $this->curlInfo                    = curl_getinfo($this->curl);
827 23
        $this->curlInfo['when']            = microtime();
828 23
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
829 23
        $this->responseFormat              = Formats::contentTypeToSuffix($this->curlInfo['content_type']);
830 23
        $this->lastResponseCode            = $this->curlInfo['http_code'];
831 23
        $this->lastCurlError               = curl_error($this->curl);
832 23
        if (strlen($this->lastCurlError)) {
833
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
834
                    $this->lastResponseCode, $this->lastCurlError), 'error');
835
        }
836
837 23
        if ($this->debug === true) {
838
            $this->saveDebugFiles();
839
        }
840
841 23
        return $this->lastResponseCode;
842
    }
843
844
    /**
845
     * Nastaví druh prováděné akce.
846
     *
847
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
848
     * @param string $action
849
     * @return boolean
850
     */
851 20
    public function setAction($action)
852
    {
853 20
        $result           = false;
854 20
        $actionsAvailable = $this->getActionsInfo();
855 20
        if (is_array($actionsAvailable) && array_key_exists($action,
856 20
                $actionsAvailable)) {
857 15
            $this->action = $action;
858 15
            $result       = true;
859 15
        }
860 20
        return $result;
861
    }
862
863
    /**
864
     * Convert XML to array.
865
     *
866
     * @param string $xml
867
     *
868
     * @return array
869
     */
870 23
    public static function xml2array($xml)
871
    {
872 23
        $arr = [];
873
874 23
        if (is_string($xml)) {
875 23
            $xml = simplexml_load_string($xml);
876 23
        }
877
878 23
        foreach ($xml->children() as $r) {
879 23
            if (count($r->children()) == 0) {
880 23
                $arr[$r->getName()] = strval($r);
881 23
            } else {
882 23
                $arr[$r->getName()][] = self::xml2array($r);
883
            }
884 23
        }
885
886 23
        return $arr;
887
    }
888
889
    /**
890
     * Odpojení od FlexiBee.
891
     */
892 23
    public function disconnect()
893
    {
894 23
        if (is_resource($this->curl)) {
895 23
            curl_close($this->curl);
896 23
        }
897 23
        $this->curl = null;
898 23
    }
899
900
    /**
901
     * Disconnect CURL befere pass away
902
     */
903 23
    public function __destruct()
904
    {
905 23
        $this->disconnect();
906 23
    }
907
908
    /**
909
     * Načte řádek dat z FlexiBee.
910
     *
911
     * @param int $recordID id požadovaného záznamu
912
     *
913
     * @return array
914
     */
915 23
    public function getFlexiRow($recordID)
916
    {
917 23
        $record   = null;
918 23
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
919 23
        if (isset($response[$this->evidence])) {
920
            $record = $response[$this->evidence][0];
921
        }
922
923 23
        return $record;
924
    }
925
926
    /**
927
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
928
     *
929
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
930
     * @param array $conditions pole podmínek   - rendrují se do ()
931
     * @param array $urlParams  pole parametrů  - rendrují za ?
932
     */
933
    public function extractUrlParams(&$conditions, &$urlParams)
934
    {
935
        foreach ($this->urlParams as $urlParam) {
936
            if (isset($conditions[$urlParam])) {
937
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
938
            }
939
        }
940
    }
941
942
    /**
943
     * Načte data z FlexiBee.
944
     *
945
     * @param string $suffix     dotaz
946
     * @param string|array $conditions Volitelný filtrovací výraz
947
     *
948
     * @return array Data obtained
949
     */
950 41
    public function getFlexiData($suffix = null, $conditions = null)
951
    {
952 41
        $finalUrl  = '';
953 41
        $urlParams = $this->defaultUrlParams;
954
955 41
        if (!is_null($conditions)) {
956 16
            if (is_array($conditions)) {
957
                $this->extractUrlParams($conditions, $urlParams);
958
                $conditions = $this->flexiUrl($conditions);
959
            }
960
961 16
            if (strlen($conditions) && ($conditions[0] != '/')) {
962 14
                $conditions = rawurlencode('('.($conditions).')');
963 14
            }
964 16
        }
965
966 41
        if (strlen($suffix)) {
967 22
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/') || is_numeric($suffix)) {
968 22
                $finalUrl = $suffix;
969 22
            }
970 22
        }
971
972 41
        $finalUrl .= $conditions;
973
974 41
        if (count($urlParams)) {
975 41
            if (strstr($finalUrl, '?')) {
976
                $finalUrl .= '&';
977
            } else {
978 41
                $finalUrl .= '?';
979
            }
980 41
            $finalUrl .= http_build_query($urlParams, null, '&',
981 41
                PHP_QUERY_RFC3986);
982 41
        }
983
984 41
        $transactions = $this->performRequest($finalUrl, 'GET');
985
986 41
        $responseEvidence = $this->getResponseEvidence();
987 41
        if (is_array($transactions) && array_key_exists($responseEvidence,
988 41
                $transactions)) {
989 30
            $result = $transactions[$responseEvidence];
990 30
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
991
                $result = null; // Response is empty Array
992
            }
993 30
        } else {
994 11
            $result = $transactions;
995
        }
996
997 41
        return $result;
998
    }
999
1000
    /**
1001
     * Načte záznam z FlexiBee a uloží v sobě jeho data
1002
     * Read FlexiBee record and store it inside od object
1003
     *
1004
     * @param int $id ID or conditions
1005
     *
1006
     * @return int počet načtených položek
1007
     */
1008 45
    public function loadFromFlexiBee($id = null)
1009
    {
1010 45
        $data = [];
1011 45
        if (is_null($id)) {
1012 23
            $id = $this->getMyKey();
1013 23
        }
1014 45
        if (is_array($id)) {
1015
            $id = '('.self::flexiUrl($id).')';
1016
        }
1017 45
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1018 45
        $this->apiURL = $this->curlInfo['url'];
1019 45
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1020 22
            $data = current($flexidata);
1021 22
        }
1022 45
        return $this->takeData($data);
1023
    }
1024
1025
    /**
1026
     * Převede data do Json formátu pro FlexiBee.
1027
     * Convert data to FlexiBee like Json format
1028
     *
1029
     * @param array $data
1030
     *
1031
     * @return string
1032
     */
1033 23
    public function jsonizeData($data)
1034
    {
1035
        $dataToJsonize = [
1036 23
            $this->nameSpace => [
1037 23
                '@version' => $this->protoVersion,
1038 23
                $this->evidence => $this->objectToID($data),
1039 23
            ],
1040 23
        ];
1041
1042 23 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...
1043 15
            $dataToJsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
1044 15
            $this->action                                               = null;
1045 15
        }
1046
1047 23 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...
1048
            $dataToJsonize[$this->nameSpace][$this->evidence.'@filter'] = $this->filter;
1049
        }
1050
1051 23
        return json_encode($dataToJsonize);
1052
    }
1053
1054
    /**
1055
     * Test if given record ID exists in FlexiBee.
1056
     *
1057
     * @param string|int $identifer
1058
     */
1059 23
    public function idExists($identifer = null)
1060
    {
1061 23
        if (is_null($identifer)) {
1062
            $identifer = $this->getMyKey();
1063
        }
1064 23
        $flexiData = $this->getFlexiData(
1065 23
            'detail=custom:'.$this->getmyKeyColumn(),
1066 23
            [$this->getmyKeyColumn() => $identifer]);
1067
1068 23
        return $flexiData;
1069
    }
1070
1071
    /**
1072
     * Test if given record exists in FlexiBee.
1073
     *
1074
     * @param array $data
1075
     * @return boolean Record presence status
1076
     */
1077 15
    public function recordExists($data = [])
1078
    {
1079
1080 15
        if (empty($data)) {
1081 15
            $data = $this->getData();
1082 15
        }
1083
1084 15
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1085 15
            self::flexiUrl($data));
0 ignored issues
show
Documentation introduced by
self::flexiUrl($data) is of type string, but the function expects a array.

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...
1086
1087
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1088
            || !count($res[0])) {
1089
            $found = false;
1090
        } else {
1091
            $found = true;
1092
        }
1093
        return $found;
1094
    }
1095
1096
    /**
1097
     * Vrací z FlexiBee sloupečky podle podmínek.
1098
     *
1099
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1100
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1101
     *                                     sloupečku
1102
     * @return array
1103
     */
1104
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1105
    {
1106
        if (is_int($conditions)) {
1107
            $conditions = [$this->getmyKeyColumn() => $conditions];
1108
        }
1109
1110
        $flexiData = $this->getFlexiData('', $conditions);
1111
1112
        if (!is_null($indexBy)) {
1113
            $flexiData = $this->reindexArrayBy($flexiData);
1114
        }
1115
1116
        return $flexiData;
1117
    }
1118
1119
    /**
1120
     * Vrací z FlexiBee sloupečky podle podmínek.
1121
     *
1122
     * @param string[] $columnsList seznam položek
1123
     * @param array    $conditions  pole podmínek nebo ID záznamu
1124
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1125
     *
1126
     * @return array
1127
     */
1128 23
    public function getColumnsFromFlexibee($columnsList, $conditions = [],
1129
                                           $indexBy = null)
1130
    {
1131 23
        $detail = 'full';
1132 23
        switch (gettype($columnsList)) {
1133 23
            case 'integer': //Record ID
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...
1134
                $conditions = [$this->getmyKeyColumn() => $conditions];
1135 23
            case 'array': //Few Conditions
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...
1136 23
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1137 23
                        $columnsList)) {
1138 23
                    $columnsList[] = $indexBy;
1139 23
                }
1140 23
                $columns = implode(',', array_unique($columnsList));
1141 23
                $detail  = 'custom:'.$columns;
1142 23
            default:
1143
                switch ($columnsList) {
1144 23
                    case 'id':
1145
                        $detail = 'id';
1146
                        break;
1147 23
                    case 'summary':
1148
                        $detail = 'summary';
1149
                        break;
1150 23
                    default:
1151 23
                        break;
1152 23
                }
1153 23
                break;
1154 23
        }
1155
1156 23
        $conditions['detail'] = $detail;
1157
1158 23
        $flexiData = $this->getFlexiData(null, $conditions);
1159
1160 23
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1161 21
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1162 18
        }
1163
1164 20
        return $flexiData;
1165
    }
1166
1167
    /**
1168
     * Vrací kód záznamu.
1169
     * Obtain record CODE
1170
     *
1171
     * @param mixed $data
1172
     *
1173
     * @return string
1174
     */
1175 23
    public function getKod($data = null, $unique = true)
1176
    {
1177 23
        $kod = null;
1178
1179 23
        if (is_null($data)) {
1180 23
            $data = $this->getData();
1181 23
        }
1182
1183 23
        if (is_string($data)) {
1184 23
            $data = [$this->nameColumn => $data];
1185 23
        }
1186
1187 23
        if (isset($data['kod'])) {
1188 23
            $kod = $data['kod'];
1189 23
        } else {
1190 23
            if (isset($data[$this->nameColumn])) {
1191 23
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1192 23
                    \Ease\Sand::rip($data[$this->nameColumn]));
1193 23
            } else {
1194 23
                if (isset($data[$this->myKeyColumn])) {
1195 23
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1196 23
                }
1197
            }
1198
        }
1199
1200 23
        if (!strlen($kod)) {
1201 23
            $kod = 'NOTSET';
1202 23
        }
1203
1204 23
        if (strlen($kod) > 18) {
1205 23
            $kodfinal = strtoupper(substr($kod, 0, 18));
1206 23
        } else {
1207 23
            $kodfinal = strtoupper($kod);
1208
        }
1209
1210 23
        if ($unique) {
1211 23
            $counter = 0;
1212 23
            if (count($this->codes)) {
1213 23
                foreach ($this->codes as $codesearch => $keystring) {
1214 23
                    if (strstr($codesearch, $kodfinal)) {
1215 23
                        ++$counter;
1216 23
                    }
1217 23
                }
1218 23
            }
1219 23
            if ($counter) {
1220 23
                $kodfinal = $kodfinal.$counter;
1221 23
            }
1222
1223 23
            $this->codes[$kodfinal] = $kod;
1224 23
        }
1225
1226 23
        return $kodfinal;
1227
    }
1228
1229
    /**
1230
     * Write Operation Result.
1231
     *
1232
     * @param array  $resultData
1233
     * @param string $url        URL
1234
     * @return boolean Log save success
1235
     */
1236 32
    public function logResult($resultData = null, $url = null)
1237
    {
1238 32
        $logResult = false;
1239 32
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1240 31
            if (isset($resultData['message'])) {
1241 8
                $this->addStatusMessage($resultData['message'], 'warning');
1242 8
            }
1243 31
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1244 31
                'warning');
1245 31
            unset($url);
1246 31
        }
1247 32
        if (is_null($resultData)) {
1248
            $resultData = $this->lastResult;
1249
        }
1250 32
        if (isset($url)) {
1251 24
            $this->logger->addStatusMessage(urldecode($url));
1252 24
        }
1253
1254 32
        if (isset($resultData['results'])) {
1255 23
            if ($resultData['success'] == 'false') {
1256 23
                $status = 'error';
1257 23
            } else {
1258 23
                $status = 'success';
1259
            }
1260 23
            foreach ($resultData['results'] as $result) {
1261 23
                if (isset($result['request-id'])) {
1262 23
                    $rid = $result['request-id'];
1263 23
                } else {
1264 23
                    $rid = '';
1265
                }
1266 23
                if (isset($result['errors'])) {
1267 23
                    foreach ($result['errors'] as $error) {
1268 23
                        $message = $error['message'];
1269 23
                        if (isset($error['for'])) {
1270
                            $message .= ' for: '.$error['for'];
1271
                        }
1272 23
                        if (isset($error['value'])) {
1273
                            $message .= ' value:'.$error['value'];
1274
                        }
1275 23
                        if (isset($error['code'])) {
1276
                            $message .= ' code:'.$error['code'];
1277
                        }
1278 23
                        $this->addStatusMessage($rid.': '.$message, $status);
1279 23
                    }
1280 23
                }
1281 23
            }
1282 23
        }
1283 32
        return $logResult;
1284
    }
1285
1286
    /**
1287
     * Save RAW Curl Request & Response to files in Temp directory
1288
     */
1289
    public function saveDebugFiles()
1290
    {
1291
        $tmpdir   = sys_get_temp_dir();
1292
        $fname    = $this->evidence.'-'.$this->curlInfo['when'].'.'.$this->format;
1293
        $reqname  = $tmpdir.'/request-'.$fname;
1294
        $respname = $tmpdir.'/response-'.$fname;
1295
        file_put_contents($reqname, $this->postFields);
1296
        file_put_contents($respname, $this->lastCurlResponse);
1297
    }
1298
1299
    /**
1300
     * Připraví data pro odeslání do FlexiBee
1301
     *
1302
     * @param string $data
1303
     */
1304
    public function setPostFields($data)
1305
    {
1306
        $this->postFields = $data;
1307
    }
1308
1309
    /**
1310
     * Generuje fragment url pro filtrování.
1311
     *
1312
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1313
     *
1314
     * @param array  $data
1315
     * @param string $joiner default and/or
1316
     * @param string $defop  default operator
1317
     *
1318
     * @return string
1319
     */
1320 23
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1321
    {
1322 23
        $parts = [];
1323
1324 23
        foreach ($data as $column => $value) {
1325 23
            if (!is_numeric($column)) {
1326 23
                if (is_integer($data[$column]) || is_float($data[$column])) {
1327 23
                    $parts[$column] = $column.' eq \''.$data[$column].'\'';
1328 23
                } elseif (is_bool($data[$column])) {
1329 23
                    $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1330 23
                } elseif (is_null($data[$column])) {
1331 23
                    $parts[$column] = $column." is null";
1332 23
                } else {
1333
                    switch ($value) {
1334 23
                        case '!null':
1335 23
                            $parts[$column] = $column." is not null";
1336 23
                            break;
1337 23
                        case 'is empty':
1338 23
                        case 'is not empty':
1339
                            $parts[$column] = $column.' '.$value;
1340
                            break;
1341 23
                        default:
1342 23
                            if ($column == 'stitky') {
1343
                                $parts[$column] = $column."='".self::code($data[$column])."'";
1344
                            } else {
1345 23
                                $parts[$column] = $column." $defop '".$data[$column]."'";
1346
                            }
1347 23
                            break;
1348 23
                    }
1349
                }
1350 23
            } else {
1351
                $parts[] = $value;
1352
            }
1353 23
        }
1354 23
        return implode(' '.$joiner.' ', $parts);
1355
    }
1356
1357
    /**
1358
     * Obtain record/object identificator code: or id:
1359
     * Vrací identifikátor objektu code: nebo id:
1360
     *
1361
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1362
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1363
     */
1364 47
    public function getRecordID()
1365
    {
1366 47
        $myCode = $this->getDataValue('kod');
1367 47
        if ($myCode) {
1368 33
            $id = 'code:'.$myCode;
1369 33
        } else {
1370 47
            $id = $this->getDataValue('id');
1371 47
            if (($this->debug === true) && is_null($id)) {
1372 9
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1373 9
                    'warning');
1374 9
            }
1375
        }
1376 47
        return is_numeric($id) ? intval($id) : strval($id);
1377
    }
1378
1379
    /**
1380
     * Obtain record/object identificator code: or id:
1381
     * Vrací identifikátor objektu code: nebo id:
1382
     *
1383
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1384
     * @return string indentifikátor záznamu reprezentovaného objektem
1385
     */
1386 47
    public function __toString()
1387
    {
1388 47
        return strval($this->getRecordID());
1389
    }
1390
1391
    /**
1392
     * Gives you FlexiPeeHP class name for Given Evidence
1393
     *
1394
     * @param string $evidence
1395
     * @return string Class name
1396
     */
1397 23
    public static function evidenceToClassName($evidence)
1398
    {
1399 23
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1400
    }
1401
1402
    /**
1403
     * Obtain ID of first record in evidence
1404
     *
1405
     * @return string|null id or null if no records
1406
     */
1407 22
    public function getFirstRecordID()
1408
    {
1409 22
        $firstID    = null;
1410 22
        $firstIdRaw = $this->getColumnsFromFlexibee(['id'],
1411 22
            ['limit' => 1, 'order' => 'id'], 'id');
1412 19
        if (count($firstIdRaw)) {
1413 19
            $firstID = (int) current($firstIdRaw)['id'];
1414 19
        }
1415 19
        return $firstID;
1416
    }
1417
1418
    /**
1419
     * Vrací hodnotu daného externího ID
1420
     *
1421
     * @param string $want Which ? If empty,you obtain the first one.
1422
     * @return string
1423
     */
1424 23
    public function getExternalID($want = null)
1425
    {
1426 23
        $extid = null;
1427 23
        $ids   = $this->getDataValue('external-ids');
1428 23
        if (is_null($want)) {
1429
            if (count($ids)) {
1430
                $extid = current($ids);
1431
            }
1432
        } else {
1433 23
            if (!is_null($ids) && is_array($ids)) {
1434
                foreach ($ids as $id) {
1435
                    if (strstr($id, 'ext:'.$want)) {
1436
                        $extid = str_replace('ext:'.$want.':', '', $id);
1437
                    }
1438
                }
1439
            }
1440
        }
1441 23
        return $extid;
1442
    }
1443
1444
    /**
1445
     * Obtain actual GlobalVersion
1446
     * Vrací aktuální globální verzi změn
1447
     *
1448
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1449
     * @return type
1450
     */
1451 22
    public function getGlobalVersion()
1452
    {
1453 22
        $globalVersion = null;
1454 22
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1455 22
            $this->getFlexiData(null,
1456 22
                ['add-global-version' => 'true', 'limit' => 1]);
1457 22
        }
1458
1459 22
        if (isset($this->lastResult['@globalVersion'])) {
1460
            $globalVersion = intval($this->lastResult['@globalVersion']);
1461
        }
1462
1463 22
        return $globalVersion;
1464
    }
1465
1466
    /**
1467
     * Obtain content type of last response
1468
     *
1469
     * @return string
1470
     */
1471 23
    public function getResponseFormat()
1472
    {
1473 23
        if (isset($this->curlInfo['content_type'])) {
1474 23
            $responseFormat = $this->curlInfo['content_type'];
1475 23
        } else {
1476
            $responseFormat = null;
1477
        }
1478 23
        return $responseFormat;
1479
    }
1480
1481
    /**
1482
     * Return the same response format for one and multiplete results
1483
     *
1484
     * @param array $responseBody
1485
     * @return array
1486
     */
1487 35
    public function unifyResponseFormat($responseBody)
1488
    {
1489 35
        if (!is_array($responseBody) || array_key_exists('message',
1490 35
                $responseBody)) { //Unifi response format
1491 22
            $response = $responseBody;
1492 22
        } else {
1493 35
            $evidence = $this->getResponseEvidence();
1494 35
            if (array_key_exists($evidence, $responseBody)) {
1495 35
                $response        = [];
1496 35
                $evidenceContent = $responseBody[$evidence];
1497 35
                if (array_key_exists(0, $evidenceContent)) {
1498 35
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1499 35
                } else {
1500 22
                    $response[$evidence][0] = $evidenceContent; //One result
1501
                }
1502 35
            } else {
1503
                if (isset($responseBody['priloha'])) {
1504
                    $response = $responseBody['priloha'];
1505
                } else {
1506
                    $response = $responseBody;
1507
                }
1508
            }
1509
        }
1510 35
        return $response;
1511
    }
1512
1513
    /**
1514
     * Obtain structure for current (or given) evidence
1515
     *
1516
     * @param string $evidence
1517
     * @return array Evidence structure
1518
     */
1519 23 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...
1520
    {
1521 23
        $columnsInfo = null;
1522 23
        if (is_null($evidence)) {
1523 23
            $evidence = $this->getEvidence();
1524 23
        }
1525 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1526 23
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1527 21
            $columnsInfo = Properties::$$propsName;
1528 21
        }
1529 23
        return $columnsInfo;
1530
    }
1531
1532
    /**
1533
     * Obtain actions for current (or given) evidence
1534
     *
1535
     * @param string $evidence
1536
     * @return array Evidence structure
1537
     */
1538 23 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...
1539
    {
1540 23
        $actionsInfo = null;
1541 23
        if (is_null($evidence)) {
1542 23
            $evidence = $this->getEvidence();
1543 23
        }
1544 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1545 23
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1546 21
            $actionsInfo = Actions::$$propsName;
1547 21
        }
1548 23
        return $actionsInfo;
1549
    }
1550
1551
    /**
1552
     * Obtain relations for current (or given) evidence
1553
     *
1554
     * @param string $evidence
1555
     * @return array Evidence structure
1556
     */
1557 23
    public function getRelationsInfo($evidence = null)
1558
    {
1559 23
        $relationsInfo = null;
1560 23
        if (is_null($evidence)) {
1561 23
            $evidence = $this->getEvidence();
1562 23
        }
1563 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1564 23
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1565 19
            $relationsInfo = Relations::$$propsName;
1566 19
        }
1567 23
        return $relationsInfo;
1568
    }
1569
1570
    /**
1571
     * Obtain info for current (or given) evidence
1572
     *
1573
     * @param string $evidence
1574
     * @return array Evidence info
1575
     */
1576 23 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...
1577
    {
1578 23
        $evidencesInfo = null;
1579 23
        if (is_null($evidence)) {
1580 23
            $evidence = $this->getEvidence();
1581 23
        }
1582 23
        if (isset(EvidenceList::$evidences[$evidence])) {
1583 16
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1584 16
        }
1585 23
        return $evidencesInfo;
1586
    }
1587
1588
    /**
1589
     * Obtain name for current (or given) evidence path
1590
     *
1591
     * @param string $evidence Evidence Path
1592
     * @return array Evidence info
1593
     */
1594 23 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...
1595
    {
1596 23
        $evidenceName = null;
1597 23
        if (is_null($evidence)) {
1598 23
            $evidence = $this->getEvidence();
1599 23
        }
1600 23
        if (isset(EvidenceList::$name[$evidence])) {
1601 16
            $evidenceName = EvidenceList::$name[$evidence];
1602 16
        }
1603 23
        return $evidenceName;
1604
    }
1605
1606
    /**
1607
     * Perform given action (if availble) on current evidence/record
1608
     * @url https://demo.flexibee.eu/devdoc/actions
1609
     *
1610
     * @param string $action one of evidence actions
1611
     * @param string $method ext|int External method call operation in URL.
1612
     *                               Internal add the @action element to request body
1613
     */
1614 15
    public function performAction($action, $method = 'ext')
1615
    {
1616 15
        $actionsAvailble = $this->getActionsInfo();
1617
1618 15
        if (is_array($actionsAvailble) && array_key_exists($action,
1619 15
                $actionsAvailble)) {
1620 15
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1621 15
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1622 15
                case 'ONLY_WITH_INSTANCE': //Add instance
1623
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1624
                    break;
1625
1626 15
                default:
1627 15
                    $urlSuffix = '/'.$action;
1628 15
                    break;
1629 15
            }
1630
1631
            switch ($method) {
1632 15
                case 'int':
1633
                    $this->setAction($action);
1634
                    $this->setPostFields($this->jsonizeData($this->getData()));
1635
                    $result = $this->performRequest(null, 'POST');
1636
                    break;
1637
1638 15
                default:
1639 15
                    $result = $this->performRequest($urlSuffix, 'GET');
1640 15
                    break;
1641 15
            }
1642 15
        } else {
1643
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1644
                $action, $this->getEvidence()));
1645
        }
1646
1647 15
        return $result;
1648
    }
1649
1650
    /**
1651
     * Save current object to file
1652
     *
1653
     * @param string $destfile path to file
1654
     */
1655 23
    public function saveResponseToFile($destfile)
1656
    {
1657 23
        if (strlen($this->lastCurlResponse)) {
1658 1
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1659 1
        }
1660 23
        file_put_contents($destfile, $this->lastCurlResponse);
1661 23
    }
1662
1663
    /**
1664
     * Obtain established relations listing
1665
     *
1666
     * @return array Null or Relations
1667
     */
1668 9
    public function getVazby($id = null)
1669
    {
1670 9
        if (is_null($id)) {
1671 9
            $id = $this->getRecordID();
1672 9
        }
1673 9
        if (!empty($id)) {
1674 7
            $vazbyRaw = $this->getColumnsFromFlexibee(['vazby'],
1675 7
                ['relations' => 'vazby', 'id' => $id]);
1676 7
            $vazby    = array_key_exists('vazby', $vazbyRaw[0]) ? $vazbyRaw[0]['vazby']
1677 4
                    : null;
1678 4
        } else {
1679 2
            throw new \Exception(_('ID requied to get record relations '));
1680
        }
1681 4
        return $vazby;
1682
    }
1683
1684
    /**
1685
     * Gives You URL for Current Record in FlexiBee web interface
1686
     *
1687
     * @return string url
1688
     */
1689
    public function getFlexiBeeURL()
1690
    {
1691
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1692
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1693
                : '';
1694
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1695
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1696
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1697
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1698
        $pass       = ($user || $pass) ? "$pass@" : '';
1699
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1700
        return $scheme.$user.$pass.$host.$port.$path;
1701
    }
1702
1703
    /**
1704
     * Set Record Key
1705
     *
1706
     * @param int|string $myKeyValue
1707
     * @return boolean
1708
     */
1709
    public function setMyKey($myKeyValue)
1710
    {
1711
        $res = parent::setMyKey($myKeyValue);
1712
        $this->updateApiURL();
1713
        return $res;
1714
    }
1715
1716
    /**
1717
     * Set or get ignore not found pages flag
1718
     *
1719
     * @param boolean $ignore set flag to
1720
     *
1721
     * @return boolean get flag state
1722
     */
1723
    public function ignore404($ignore = null)
1724
    {
1725
        if (!is_null($ignore)) {
1726
            $this->ignoreNotFound = $ignore;
1727
        }
1728
        return $this->ignoreNotFound;
1729
    }
1730
1731
    /**
1732
     * Send Document by mail
1733
     *
1734
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1735
     *
1736
     * @param string $to
1737
     * @param string $subject
1738
     * @param string $body Email Text
1739
     *
1740
     * @return int http response code
1741
     */
1742
    public function sendByMail($to, $subject, $body, $cc = null)
1743
    {
1744
        $this->setPostFields($body);
1745
        $result = $this->doCurlRequest(urlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1746
            , 'PUT', 'xml');
1747
        return $result == 200;
1748
    }
1749
1750
    /**
1751
     * Send all unsent Invoices by mail
1752
     *
1753
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1754
     * @return int http response code
1755
     */
1756
    public function sendUnsent()
1757
    {
1758
        return $this->doCurlRequest('automaticky-odeslat-neodeslane', 'PUT',
1759
                'xml');
1760
    }
1761
1762
    /**
1763
     * FlexiBee date to PHP DateTime
1764
     *
1765
     * @param string $flexidate
1766
     *
1767
     * @return \DateTime | false
1768
     */
1769
    public static function flexiDateToDateTime($flexidate)
1770
    {
1771
        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 1771 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...
1772
    }
1773
1774
    /**
1775
     * Získá dokument v daném formátu
1776
     * Obtain document in given format
1777
     *
1778
     * @param string $format  pdf/csv/xml/json/ ...
1779
     *
1780
     * @return string|null filename downloaded or none
1781
     */
1782
    public function getInFormat($format)
1783
    {
1784
        $response = null;
1785
        if ($this->setFormat($format)) {
1786
            if (($this->doCurlRequest(($format == 'html') ? $this->apiURL.'?inDesktopApp=true'
1787
                            : $this->apiURL, 'GET') == 200)) {
1788
                $response = $this->lastCurlResponse;
1789
            }
1790
        }
1791
        return $response;
1792
    }
1793
1794
    /**
1795
     * Uloží dokument v daném formátu do složky v systému souborů
1796
     * Save document in given format to directory in filesystem
1797
     *
1798
     * @param string $format  pdf/csv/xml/json/ ...
1799
     * @param string $destDir where to put file (prefix)
1800
     *
1801
     * @return string|null filename downloaded or none
1802
     */
1803
    public function downloadInFormat($format, $destDir = './')
1804
    {
1805
        $fileOnDisk = null;
1806
        if ($this->setFormat($format)) {
1807
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
1808
            if (($this->doCurlRequest($this->apiURL, 'GET') == 200) && (file_put_contents($downloadTo,
1809
                    $this->lastCurlResponse) !== false)) {
1810
                $fileOnDisk = $downloadTo;
1811
            }
1812
        }
1813
        return $fileOnDisk;
1814
    }
1815
1816
    /**
1817
     * Compile and send Report about Error500 to FlexiBee developers
1818
     * If FlexiBee is running on localost try also include java backtrace
1819
     *
1820
     * @param array $errorResponse result of parseError();
1821
     */
1822
    public function error500Reporter($errorResponse)
1823
    {
1824
        $ur = str_replace('/c/'.$this->company, '',
1825
            str_replace($this->url, '', $this->curlInfo['url']));
1826
        if (!array_key_exists($ur, $this->reports)) {
1827
            $tmpdir   = sys_get_temp_dir();
1828
            $myTime   = $this->curlInfo['when'];
1829
            $curlname = $tmpdir.'/curl-'.$this->evidence.'-'.$myTime.'.json';
1830
            file_put_contents($curlname,
1831
                json_encode($this->curlInfo, JSON_PRETTY_PRINT));
1832
1833
            $report = new \Ease\Mailer($this->reportRecipient,
1834
                'Error report 500 - '.$ur);
1835
1836
            $d     = dir($tmpdir);
1837
            while (false !== ($entry = $d->read())) {
1838
                if (strstr($entry, $myTime)) {
1839
                    $ext  = pathinfo($tmpdir.'/'.$entry, PATHINFO_EXTENSION);
1840
                    $mime = Formats::suffixToContentType($ext);
1841
                    $report->addFile($tmpdir.'/'.$entry,
1842
                        empty($mime) ? 'text/plain' : $mime);
1843
                }
1844
            }
1845
            $d->close();
1846
1847
            if ((strstr($this->url, '://localhost') || strstr($this->url,
1848
                    '://127.')) && file_exists('/var/log/flexibee.log')) {
1849
1850
                $fl = fopen("/var/log/flexibee.log", "r");
1851
                if ($fl) {
1852
                    $tracelog = [];
1853
                    for ($x_pos = 0, $ln = 0, $output = array(); fseek($fl,
1854
                            $x_pos, SEEK_END) !== -1; $x_pos--) {
1855
                        $char = fgetc($fl);
1856
                        if ($char === "\n") {
1857
                            $tracelog[] = $output[$ln];
1858
                            if (strstr($output[$ln], $errorResponse['message'])) {
1859
                                break;
1860
                            }
1861
                            $ln++;
1862
                            continue;
1863
                        }
1864
                        $output[$ln] = $char.((array_key_exists($ln, $output)) ? $output[$ln]
1865
                                : '');
1866
                    }
1867
1868
                    $trace     = implode("\n", array_reverse($tracelog));
1869
                    $tracefile = $tmpdir.'/trace-'.$this->evidence.'-'.$myTime.'.log';
1870
                    file_put_contents($tracefile, $trace);
1871
                    $report->addItem("\n\n".$trace);
1872
                    fclose($fl);
1873
                }
1874
            } else {
1875
                $report->addItem($errorResponse['message']);
1876
            }
1877
1878
            $licenseInfo = $this->performRequest($this->url.'/default-license.json');
1879
1880
            $report->addItem("\n\n".json_encode($licenseInfo['license'],
1881
                    JSON_PRETTY_PRINT));
1882
1883
            if ($report->send()) {
1884
                $this->reports[$ur] = $myTime;
1885
            }
1886
        }
1887
    }
1888
1889
    /**
1890
     * Returns code:CODE
1891
     *
1892
     * @param string $code
1893
     *
1894
     * @return string
1895
     */
1896
    public static function code($code)
1897
    {
1898
        return 'code:'.self::uncode($code);
1899
    }
1900
1901
    /**
1902
     * Returns CODE without code: prefix
1903
     *
1904
     * @param string $code
1905
     *
1906
     * @return string
1907
     */
1908
    public static function uncode($code)
1909
    {
1910
        return str_replace('code:', '', $code);
1911
    }
1912
}
1913